4

I want to divide each element of a matrix by the sum of the row that element belongs to. For example:

[1 2      [1/3 2/3 
 3 4] ==>  3/7 4/7]

How can I do it? Thank you.

Martin08
  • 20,990
  • 22
  • 84
  • 93
  • 1
    This sort of thing has been asked before (same idea, different arithmetic operation): [How do I divide matrix elements by column sums in MATLAB?](http://stackoverflow.com/questions/1773099/how-do-i-divide-matrix-elements-by-column-sums-in-matlab), [How can I divide each row of a matrix by a fixed row?](http://stackoverflow.com/questions/4723824/how-can-i-divide-each-row-of-a-matrix-by-a-fixed-row) – gnovice Apr 04 '11 at 14:09

2 Answers2

8

A =[1 2; 3 4]

diag(1./sum(A,2))*A

Community
  • 1
  • 1
Jirka cigler
  • 405
  • 3
  • 6
3

I suggest using bsxfun. Should be quicker and more memory efficient:

bsxfun(@rdivide, A, sum(A,2))

Note that the vecor orientation is important. Column will divide each row of the matrix, and row vector will divide each column.

Here's a small time comparison:

A = rand(100);

tic
for i = 1:1000    
   diag(1./sum(A,2))*A;
end
toc

tic
for i = 1:1000    
   bsxfun(@rdivide, A, sum(A,2));
end
toc

Results:

Elapsed time is 0.116672 seconds.
Elapsed time is 0.052448 seconds.
orli
  • 181
  • 1
  • 5