bsxfun @times the row sum and @rdivide the (1./row sum) does not produce same results

1 view (last 30 days)
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
ans = 8.5977e-17

Accepted Answer

the cyclist
the cyclist on 26 Feb 2023
Edited: the cyclist on 26 Feb 2023
In all cases, you are getting answers to within floating-point precision. For almost all purposes, you can consider these to be equally "reliable", but the direct division is potentially more accurate. (Refer to this documentation for details on floating point operations and accuracy.)
If you have a relative recent version of MATLAB, you can bypass bsxfun, and use implicit expansion:
M = rand(34,45);
M_div_rowsum = M./sum(M,2);

More Answers (1)

Walter Roberson
Walter Roberson on 26 Feb 2023
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.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!