Finding unique slices of a multidimensional array

조회 수: 8 (최근 30일)
Jake Martin
Jake Martin 2020년 11월 20일
댓글: the cyclist 2020년 11월 20일
I'm trying to find unique slices of a multi-dimensional array. For example, if I have something like
A = repmat(magic(4),1,1,3);
A(:,:,2) = A(:,:,2) - 1
A(:,:,1) =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
A(:,:,2) =
15 1 2 12
4 10 9 7
8 6 5 11
3 13 14 0
A(:,:,3) =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
I would like to be able to call something (with the dimension along which I'm slicing specified) and get
[C, ia, ic] = highdim_unique(A, 3)
C(:,:,1) =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
C(:,:,2) =
15 1 2 12
4 10 9 7
8 6 5 11
3 13 14 0
ia =
1
2
ic =
1
2
1
Any chance that something like this exists or has a straightforward solution? Ideally I would want to do this for arbitrariliy many dimensions, but doing it in 3 would be fine.
Thanks,
Jake

채택된 답변

the cyclist
the cyclist 2020년 11월 20일
% Define a 3-d array of pretend data, that has a couple duplicate slices
% (Use your data instead)
rng default
A = rand(2,2,4) > 0.5;
% Find the size of A, for generality
[s1,s2,s3] = size(A);
% Reshape the slices into rows (by working down column-wise, and then across columns)
A_r = reshape(A,s1*s2,s3,1)';
% Find the unique rows (which corresponds to unique slices of original array)
A_ru = unique(A_r,'rows','stable');
% Reshape the rows back to 3-d
A_u = reshape(A_ru',s1,s2,[]);
  댓글 수: 2
Jake Martin
Jake Martin 2020년 11월 20일
Works great, thanks!
the cyclist
the cyclist 2020년 11월 20일
Excellent.
I didn't really think about how to do it for N-dimensional array for N>3, but I see no reason why you could not do the same "reshape into rows" method.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by