Get mean of a matrix which has NaN in it

I want to get the mean of each of the columns in a 3x4 array.
grades = [2,4,6; 5, NaN, 1; 7, 2,NaN]
The NaNs will cause the mean in that column to be a NaN so I think I have to first convert the matrix. I tried:
grades1 = cell2mat(grades)
But Matlab throws this error msg:
??? Cell contents reference from a non-cell array object.
Error in ==> cell2mat at 44
cellclass = class(c{1});
The grades matrix is a type double, so perhaps if I could convert it to something else, it would work, but when I tried a char array, it did work, but then I was still left with the NaN issue so converting it to something else appears tough.
*Note: I cannot use scripting for thiss. That means no for loops, if / else. I am just learning Matlab and I cannot use these yet.

 Accepted Answer

grades = [2,4,6; 5, NaN, 1; 7, 2,NaN]
grades = 3×3
2 4 6 5 NaN 1 7 2 NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
mean(grades,'omitnan')
ans = 1×3
4.6667 3.0000 3.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

4 Comments

I don't think I can. I mentioned I'm using Matlab version 2008b. This gives error:
??? Subscript indices must either be real positive integers or logicals.
So 'omitnan' I don't think is supported. It doesn't show using (Reference Page Not Found)
doc omitnan
Then use "nanmean":
grades = [2,4,6; 5, NaN, 1; 7, 2,NaN];
nanmean(grades,1)
ans = 1×3
4.6667 3.0000 3.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
This worked, very simple - thanks!
Matt J
Matt J on 4 Aug 2025
Edited: Matt J on 4 Aug 2025
I am just learning Matlab ... I mentioned I'm using Matlab version 2008b.
You should really upgrade, if at all possible, or get the trial/free version of Matlab Online. It is not a very good educational exercise to learn Matlab via a 17-year old version.

Sign in to comment.

More Answers (1)

grades = [2,4,6; 5, NaN, 1; 7, 2,NaN]
grades = 3×3
2 4 6 5 NaN 1 7 2 NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
mean(grades,1,"omitnan")
ans = 1×3
4.6667 3.0000 3.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Products

Release

R2008b

Tags

Asked:

on 4 Aug 2025

Edited:

on 4 Aug 2025

Community Treasure Hunt

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

Start Hunting!