- 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.
How to sum logical 1 voxels at a specific dimension?
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Stephen23
le 9 Oct 2018
Modifié(e) : Stephen23
le 10 Oct 2018
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."
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.
Réponse acceptée
Guillaume
le 10 Oct 2018
Modifié(e) : Guillaume
le 10 Oct 2018
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.
Plus de réponses (1)
Image Analyst
le 10 Oct 2018
Modifié(e) : Image Analyst
le 11 Oct 2018
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.
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!