bsxfun @times the row sum and @rdivide the (1./row sum) does not produce same results
Show older comments
Hi, I am using bsxfun to divide a matrix by row sum. That is to say, each number is divided by the sum of row it is located.
I tried both @times and @rdivide, but the result is not equal. There is a tiny difference as seen from the sum of difference.
Which one is more reliable?
Matrix_grab = rand(34,45);
Matrix_grab1 = bsxfun(@times,Matrix_grab,1./sum(Matrix_grab,2));
Matrix_grab2 = bsxfun(@rdivide,Matrix_grab,sum(Matrix_grab,2));
sum(sum((Matrix_grab1-Matrix_grab2)))%6.5052e-19
Accepted Answer
More Answers (1)
Walter Roberson
on 26 Feb 2023
1 vote
A./B is expected to be higher accuracy than A.*(1/B) for scalar B.
Consider for example B = 10 then (1/B) is 1/10 which is a number that is not exactly representable in binary floating-point. You would be multiplying the elements by not-exactly 1/10 and that can show up in the result.
If I recall correctly, 49*(1/49) is not 1 because of round-off, also 98*(1/98) but the other integers 1 to 100 N*(1/N) round to 1.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!