MATLAB: How to calculate a mean value of a vector and ignore from the “0” when appears inside the vectors

MATLABmean

Hello.
I need to calculate a mean value of a velocity vector. The vector contains a damaged cells which appears as "0" inside the vector. How do I calculate a mean value of a vector and ignore from the "0" when appears inside the vectors?

Best Answer

If you have a recent release (I don’t remember when the 'omitnan' option appeared) or the Statistics and Machine Learning Toolbox nanmean function you can change the zeros to NaN and use those functions:
V = randi([0 9], 5)
V(V==0)= NaN
Out_1 = nanmean(V)
Out_2 = mean(V, 'omitnan')
V =
0 4 6 0 4
1 5 1 9 3
6 2 3 7 5
7 7 6 4 5
6 1 7 4 8
V =
NaN 4 6 NaN 4
1 5 1 9 3
6 2 3 7 5
7 7 6 4 5
6 1 7 4 8
Out_1 =
5 3.8 4.6 6 5
Out_2 =
5 3.8 4.6 6 5
The problem with the logical indexing approach is that it defaults to ‘linear indexing’ because the rows and columns are no longer equal. That produces a vector argument to the mean function, and the mean of the vector.