MATLAB: How to sum logical 1 voxels at a specific dimension

sum logical voxels

Hi Guys!
I have a 3D logical array (142 x 177 x 156) denoted A. I wish to take the sum of all the logical 1 voxels in the first, followed by the second and third dimension respectively. The code written below do not work. Appreciate if someone could highlight to me how do I do this please?
x_true= sum(A(:),1);
y_true= sum(A(:),2);
z_true= sum(A(:),3);
nline= x_true + y_yrue + z_true

Best Answer

Perhaps, this is what you want
B = [ 0 0 0 0 1
0 1 1 1 0
1 0 0 0 0]
vertcount = sum(any(B, 1))
horzcount = sum(any(B, 2))
For 3D matrices:
vertcount = sum(any(any(B, 2), 3))) %with R2018b only: sum(any(B, [2 3]))
horzcount = sum(any(any(B, 1), 3))) %with R2018b only: sum(any(B, [1 3]))
pagecount = sum(any(any(B, 1), 2))) %with R2018b only: sum(any(B, [1 2]))
Note: you can use nnz instead of sum.