How to calculate standard deviation of nonzero elements along the third dimension of a 3D Array
Show older comments
Hi,
I have a 3D-Array called A1, with dimensions 576x640x100.
I want to calculate the standard deviation of elements along the third axis, without taking into account the elements which are equal to 0.
The result would be a 576x640 matrix.
What I have tried :
Since I haven't found a way to use the default function std() in this case, I have tried using 3 loops and calculating the standard deviation using another formula (see figure below)
% Pre-allocate the final result Ds
Ds=zeros(576,640);
% Loop through all lines and columns
for i = 1:576
for j = 1:640
% m is the sum of elements, 'summcar' is the sum of squares m^2
m=0;
summcar=0;
n=100;
for k = 1:100
% if an element = 0 --> substract 1 from number of total elements,
if A1(i,j,k)==0
n=n-1;
else
m = m+A1(i,j,k);
summcar = summcar+m^2;
end
end
if n==0
% if all elements along the third axis are equal to 0 --> assign value 0
Ds(i,j)=0;
else
% np is the sum of all elements that are different than 0
np=sum(A1(i,j,:)~=0);
Ds(i,j)=sqrt(double((summcar-(m^2/np))/np-1));
end
end
end
Formula used for standard deviation (on the right) :

Any help is much appreciated.
Thank you.
Accepted Answer
More Answers (0)
Categories
Find more on Interpolation of 2-D Selections in 3-D Grids 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!