How to do a nanmean not including zero values.

Hello,
I have some awkward sea ice data, where I need to do some averaging of just the none zero values.
Land values are NAN and I would like to keep them as such, and ocean values are zeros. I would like to do some monthly averaging between years, which I would normally do as-
siz = size(A) ;
B = zeros(siz(1), siz(2), siz(3), 12) ;
for mId = 1 : 12
B(:,:,:,mId) = nanmean(A(:,:,:,mId:12:end), 4) ;
end
Normally I would just set all zero values to NAN for this, however, I need to keep them as zero for my file to work further down the line.
Thank you,
Holly

3 Comments

" I would like to do some monthly averaging between years"
For this, I would strongly recommend storing your data into a table or timetable. Assuming one of the table or timetable variable is Date, then getting the monthly average is as simple as
monthlyaverage = groupsummary(yourtable, 'Date', 'monthly', 'mean')
I'm not entirely clear on what you're asking but if you want to ignore 0s in the monthly mean it's a simple modification of the above.
If you need help converting your data into a table then explain how it is currently stored.
Note that there's been very little reason to use the nanmean function from the stats toolbox for a long time now. The mean function from base matlab has been able to ignore NaNs since 2014, IIRC.
It does sound like just ignoring zeros...so if the tabular storage works for you, instead of
'mean'
I guess you'd want to use something like
@(x)mean(x(x~=0),2,'omitnan')
where dimension 2 assumes you're operating a table column
I agree it would be nice if your data can be converted to the more meaningful timetable and operations look more human readable...
...But to the original question, I might be interpreting way too simplistically, but just in case, is it as simple as making a copy of A to modify for purposes of averaging, and using the original A downstream?
While we're at it, note that the original code can be simplified to
B = mean(reshape(A, size(A, 1), size(A, 2), size(A, 3), 12, []), 5, 'omitnan');

Sign in to comment.

Answers (1)

Matt J
Matt J on 20 Dec 2019
Edited: Matt J on 20 Dec 2019
Normally I would just set all zero values to NAN for this, however, I need to keep them as zero for my file to work further down the line.
I don't see what prevents you from simply modifying a copy of A instead of A itself,
siz = size(A) ;
Atmp=reshape(A,siz(1), siz(2), siz(3), 12,[]);
Atmp(A==0)=nan;
B=mean(Atmp,5,'omitnan');

Asked:

HA
on 20 Dec 2019

Edited:

on 20 Dec 2019

Community Treasure Hunt

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

Start Hunting!