Count unique combinations of elements in a 3D matrix
4 views (last 30 days)
Show older comments
Tommy Carter
on 17 Mar 2021
Commented: Star Strider
on 18 Mar 2021
Hi all,
I was wondering if there was a way to count a unique combination of numbers within a 3D Matrix. The best way I can describe this is with an example:
Suppose I have a 3D Matrix which is laid out as such
A(:,:,1)
1 2
3 1
A(:,:,2)
1 2
3 1
A(:,:,3)
1 3
3 1
So if I wanted to know the count of the combination (1,1,1) it would be 2, as the combination of the 3 numbers (1, 1, 1) appears twice in the matrix, once at (1,1,:) and once at (2,1,:). Another example might be, if I wanted to know the count of (3,3,3) within the matrix, it would be 1, as the combination only appears once in the matrix, at (2,1,:)
I hope I explained this well. Again, I'd like the count of these unique combinations, rather than any indexing information. I've tried count and/or sum as well as unique, but they did not give me the results I've hoped for, however I probably utilized them wrong
A loop of this, so that I could get the counts of all unique combinations of the elements would also be much appreciated, but I understand if this is harder.
This is my first time posting so I apologize if this isn't formulated right.
Thanks in advance for any help you can give!
0 Comments
Accepted Answer
Star Strider
on 17 Mar 2021
The only way I can see to do this is first to reshape ‘A’ and then use the unique function on the resulting rows, and do the counting with accumarray:
A(:,:,1) = [...
1 2
3 1];
A(:,:,2) = [...
1 2
3 1];
A(:,:,3) = [...
1 3
3 1];
Ar = reshape(A, [],3);
[Aru,~,ix] = unique(Ar,'rows','stable')
Count = accumarray(ix,1);
Out = [Aru, Count]
producing:
Out =
1 1 1 2
3 3 3 1
2 2 3 1
I am not certain how robust this approach would be for other matrices, or for other matrices with additional dimensions.
5 Comments
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!