Re: Debug for my code, help~
- From: "John D'Errico" <woodchips@xxxxxxxxxxxxxxxx>
- Date: Wed, 16 May 2007 10:00:39 -0400
jackypp wrote:
I try to do a small operation to a matrix that to turn it into a
new
one with the sum of every column and row equals to one, the code I
wrote is as following:
function C=BvN1(A)
for i=1:length(A)
for j=1:length(A)
if sum(A(i,:)<1) & sum(A(:,j)<1)
R(i,j) = 1-min(sum(A(i,:)),sum(A(:,j)));
else
end
end
end
however, it show that there is something wrong with it, could
anyone
help me to correct it? Thx
There are many reasons why this code
will not work here, so I won't list
them all.
Do you really wish to find an additive
shift for A, or instead multiplicative
scale factors that will do this?
For example, even if A is entirely
made of positive numbers, it is very
possible that after an additive shift
the result will not be entirely
positive.
What do I mean by an additive shift?
There should exist column vectors b
and c, each of length n, such that
R = A + repmat(b,1,n) + repmat(c',n,1)
that has the property that R is both
unit row sum normalized and unit
column sum normalized. However, these
vectors will not be unique, since if
b and c have the above property, then
so must the vectors (b+k) and (c-k)
for any scalar constant k.
Likewise, there should also exist
vectors b and c such that
R = diag(b)*A*diag(c)
has the required property. Again, they
are not unique, using similar reasoning.
To solve the additive problem, use a
system of linear equations. For example...
n = 4;
A = rand(n,n);
% A =
% 0.01964 0.50281 0.18965 0.54167
% 0.68128 0.70947 0.19343 0.15087
% 0.37948 0.42889 0.68222 0.6979
% 0.8318 0.30462 0.30276 0.37837
% A is clearly not row or column sum
% normalized.
sum(A,1) % column sums
% ans =
% 1.9122 1.9458 1.3681 1.7688
sum(A,2) % row sums
% ans =
% 1.2538
% 1.7351
% 2.1885
% 1.8176
M = [ones(n),n*eye(n);n*eye(n),ones(n)];
bc = pinv(M)*[1-sum(A,2);1-sum(A,1)'];
b = bc(1:n);
c = bc((n+1):end);
% As a verification,
R = A + repmat(b',n,1) + repmat(c,1,n);
sum(R,1)
% ans =
% 1 1 1 1
sum(R,2)
% ans =
% 1
% 1
% 1
% 1
Look carefully at how I set up the
matrix M. Think about why it works as
it does. Also consider that I used pinv
to solve the system of equations. Is
there a good reason why I used pinv
instead of backslash? (There was.)
HTH,
John D'Errico
.
- References:
- Debug for my code, help~
- From: jackypp
- Debug for my code, help~
- Prev by Date: Re: Why isn't my graph plotting?
- Next by Date: Re: MATLAB Programming Contest: May 9 - May 16, 20
- Previous by thread: Re: Debug for my code, help~
- Next by thread: Continuous serial read
- Index(es):
Relevant Pages
|