MATLAB: Standard deviation of non-zero elements of columns of a matrix

matrixnon-zerostandard deviation

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!

Best Answer

Here is a straightforward way.
% Some input data
x = rand(7,6);
x(1,1) = 0; % Put in a couple zeros by hand
x(6,5) = 0;
% Preallocate the array that will hold the standard deviations
sd = zeros(1,6);
% Calculate and store the standard deviations of the non-zero elements.
for nc = 1:6
indexToNonZero = x(:,nc)~=0;
sd(nc) = std(x(indexToNonZero,nc));
end