MATLAB: How to find variance and std in matlab without using zeros in matrix

population variancer2013astdvarvariance

I have a matrix (pm2d), and i need to calculate the std and (population) variance in each column without using the zero values. I was wondering if i could use a for loop or an if statement?
For my variance i used:
var = sum(pm2d.^2)/(length(pm2d)-1) – (length(pm2d))*mean(pm2d).^2/(length(pm2d)-1)
But that took the zeros into account…
And for the standard deviation i used:
S = std(pm2d)
which definitely used the zeros.
Every code i try to write is not working. Any assistance would be appreciated! Thanks!

Best Answer

Hi,
You can use nanvar and nanstd functions in statistics toolbox.
>> b = pm2d; % just to retain the original matrix
>> b(b==0) = NaN;
>> nz_var = nanvar(b);
>> nz_std = nanstd(b);
Of course, this solution works only if you have license to statistics toolbox.