standard deviation of non-zero elements of columns of a matrix
Show older comments
Hello,
How can I find the standard deviation of each column of a matrix ignoring the zero values? I must add that I do not have the stats package so I cannot use nanstd! Thank you!
Accepted Answer
More Answers (2)
Walter Roberson
on 1 Mar 2012
0 votes
There is a MATLAB File Exchange contribution to provide these functions.
David Freese
on 11 Oct 2013
A way to go about it using just matrix operations:
% Some input data
x = rand(7,6);
x(1,1) = 0; % Put in a couple zeros by hand
x(6,5) = 0;
% Calculate and store the standard deviations of the non-zero elements.
% using the identity std^2 = Var(x) = mean(x.^2,2) - mean(x,2).^2
avg = sum(x,2)./sum(x~=0,2);
sd = sqrt(sum(x.^2,2)./sum(x~=0,2) - avg.^2);
% Zero out any of the columns that were all zeros
sd(isnan(sd)) = 0;
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!