How to sum logical 1 voxels at a specific dimension?

9 次查看(过去 30 天)
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
  2 个评论
Stephen23
Stephen23 2018-10-9
编辑:Stephen23 2018-10-10
It is not clear what you are trying to achieve, or what the expected output should be.
"I wish to take the sum of all the logical 1 voxels in the first, followed by the second and third dimension respectively."
  • If you sum along the 1st dimension, then you will get a 1x177x156 array.
  • If you sum along the 2nd dimension, then you will get a 142x1x156 array.
  • If you sum along the 3rd dimension, then you will get a 142x177x1 array.
Those arrays have totally different sizes, and different numbers of elements. They cannot be added like this:
nline= x_true + y_yrue + z_true
Even if you convert them to vectors, because in general they have a different number of elements you would not be able to add them like that.
And if you convert A into a column vector, like you are doing with your example code, then you lose any dimensional information, and so is unlikely to be useful for you.
Please clarify what output you expect to get, together with a small example with both input and output arrays.
Sophie
Sophie 2018-10-10
编辑:Sophie 2018-10-10
for example B =
0 0 0 0 1
0 1 1 1 0
1 0 0 0 0
the number I'm looking for along the 1st dimension (vertically) is 3 while the number of logical 1 voxels along the 2nd dimension (horizontally) is 5.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2018-10-10
编辑:Guillaume 2018-10-10
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.

更多回答(1 个)

Image Analyst
Image Analyst 2018-10-10
编辑:Image Analyst 2018-10-11
Try this:
A = logical(randi([0, 1], 142, 177, 156)); % Create random data.
% Need to use squeeze() along all except the last dimension
along1 = squeeze(sum(A, 1));
along2 = squeeze(sum(A, 2));
along3 = sum(A, 3);
The along's are three 2-D arrays like Stephen said. You can't sum them. Even if they were the same size, it doesn't make any sense.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by