0
votes

I have this matrix

K=
0 0 1
0 2 1
0 1 1

L= 
1
3
2

where L is the sum of each row of K

I need to make a new matrix through dividing each row of K by its sum, for example from 2nd row [0 2 1] the output that I should get is [0 2/3 1/3] or [0 0.67 0.33]:

Output=
0   0     1
0   0.67  0,33
0   0.5   0.5 

I'm trying to use this code, but got only zeros:

for i=1:3;
    j=1:3;
    if K(i,j)>0
        K(i,j)=(K(i,j))/L(i)
    else
        K(i,j)=0
    end
end

How can I divide each row of K by its own sum?

4

4 Answers

0
votes
K=[0 0 1; 0 2 1; 0 1 1]; % your matrix
rowSum = sum(K, 2); % compute the sum
K_norm = K./repmat(rowSum, 1, size(K, 2));

repmat here builds a matrix with the same dimensions as K but with each column being the sum of rows of K.

0
votes
K=[0 0 1
0 2 1
0 1 1 ];
L = sum(K,2) ;
iwant = bsxfun(@rdivide,K,L)  ;
0
votes

You can write it in two lines; first calculate the sum and then use repmat to make a matrix the same size as K and divide elementwise

L = sum(K,2);
iwant = K./repmat(L,1,size(K,2));
-1
votes
K=[0 0 1
0 2 1
0 1 1 ];
L = sum(K,2) ;
iwant = zeros(size(K)) ;
for i = 1:size(K,1)
    iwant(i,:) = K(i,:)/L(i) ;
end