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

1 Ansicht (letzte 30 Tage)
raym am 26 Feb. 2023
Bearbeitet: the cyclist am 26 Feb. 2023
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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

the cyclist am 26 Feb. 2023
Bearbeitet: the cyclist am 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);
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Walter Roberson am 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.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by