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

조회 수: 3 (최근 30일)
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

채택된 답변

the cyclist
the cyclist 2023년 2월 26일
편집: the cyclist 2023년 2월 26일
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);

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 2월 26일
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by