-
3 Comments
in= [3 3; 3 3]
in =
3 3
3 3
>> sum(in.*isprime(in))/sum(isprime(in))
ans =
3.0000
The fault is in two respects:
(1) the numerator and denominator for Test 3 will be vectors, not scalars, because that's how sum() works;
(2) the MATLAB algorithm for matrix division is therefore being employed, and it has introduced a truncation error. Your code yields a purported answer of 3 – (4.4409E–16) for Test 3. Of course, if only a few decimal places are displayed, this is shown as "3.0000".
To avoid this problem, reshape the input matrix to a vector. This can be done with the reshape command, but an easier way is to simply index as "in(:)".
This is done in https://au.mathworks.com/matlabcentral/cody/problems/14-find-the-numeric-mean-of-the-prime-numbers-in-a-matrix/solutions/1142672
Another effective (but somewhat less elegant) way of avoiding the problem is to nest your summations: sum(sum(sum( ... ))). (But you must use at least as many "sum" command as your matrices have dimensions.)
For debugging, try using the whos command.
@David Verrelli
Thanks! It works.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!