Normalise a Histogram excluding NaN?

14 views (last 30 days)
Shown under M1, i am attempting to plot a histogram and it's Normal Distribution, however the data has a large quantity of NaN. I was able to omit them in the plotting for the line but not the histogram bars themselves.
Does anyone know how to fix this?

Accepted Answer

Star Strider
Star Strider on 6 Jan 2018
One option is:
histogram(m(~isnan(m)), 50, 'Normalization','PDF')
This eliminates the NaN values from your data before doing the analysis.
Experiment to get the result you want.

More Answers (1)

Erik Giesen Loo
Erik Giesen Loo on 19 Sep 2018
Using a deprecated method, but may be useful to compare the validity of MATLAB's histogram. I start by defining a function that finds the length of a vector ignoring all nan's (similar to how nanmean and nanstd work).
function nx = nanlength(x)
% nanlength(x) returns the number of elements of vector x that are not nan.
dim = find(size(x) ~= 1, 1);
if dim == 2
x = x(:)';
else % dim == 1
x = x(:);
end
xnans = isnan(x);
if any(xnans(:))
nx = sum(~xnans,dim);
else
nx = size(x,dim); % a scalar, => a scalar call to tinv
end
Now we proceed to implement the pdf normalization ourselves:
[y,x] = hist(data,m); % m = number of bins using any desired algorithm
width = x(2) - x(1);
y_bar = y/(nanlength(data)*width);
bar(x,y_bar,'hist')
It might be nice if MATLAB implemented an option to ignore NAN's like in many other functions.

Community Treasure Hunt

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

Start Hunting!