-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmynanmean.m
30 lines (26 loc) · 1.05 KB
/
mynanmean.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function m = mynanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
%The same function as Matlabs inbuild function nanmean (duplicated to not
%need statistical toolbox)
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
% NANMEAN(X,DIM) takes the mean along dimension DIM of X.
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end