开发者

how to divide matrix elements by sum of row

开发者 https://www.devze.com 2023-02-22 04:59 出处:网络
I want to divide each element of a matrix by the sum of the row that element belongs to.开发者_如何学Python For example:

I want to divide each element of a matrix by the sum of the row that element belongs to.开发者_如何学Python For example:

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

How can I do it? Thank you.


A =[1 2; 3 4]

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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消