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/14findthenumericmeanoftheprimenumbersinamatrix/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.
Test  Status  Code Input and Output 

1  Pass 
x = 3;
y_correct = 3;
assert(isequal(meanOfPrimes(x),y_correct))

2  Pass 
x = [1 2 3];
y_correct = 2.5;
assert(isequal(meanOfPrimes(x),y_correct))

3  Fail 
x = [3 3; 3 3];
y_correct = 3;
assert(isequal(meanOfPrimes(x),y_correct))

4  Pass 
x = [7 3 8 8]';
y_correct = 5;
assert(isequal(meanOfPrimes(x),y_correct))

1766 Solvers
Find common elements in matrix rows
1059 Solvers
232 Solvers
514 Solvers
345 Solvers
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!