How to divide matrix elements by row sum

I want to divide each element of the matrix by the sum of the row to which the element belongs. For instance:

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

How can i do this? Thanks.

+4
source share
2 answers

A = [1 2; 3 4]

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

+7
source

I suggest using bsxfun. There should be a more efficient and effective memory:

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

Note that vector orientation is important. A column will split each row of the matrix, and a row vector will divide each column.

Here's a little 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. 
+2
source

Source: https://habr.com/ru/post/1346410/


All Articles