Count number of column pairs occurrence in 3d array

4 ビュー (過去 30 日間)
Hampus Alfredsson
Hampus Alfredsson 2018 年 2 月 26 日
コメント済み: Hampus Alfredsson 2018 年 2 月 26 日
I have a 3d array like the example below:
A(:,:,1) = [5.5 2.2; 5.3 2.5; 5.3 2.1; 5.4 2.6]
A(:,:,2) = [5.2 2.9; 5.4 2.6; 5.4 2.6; 5.5 2.2]
I want to calculate the number of occurrences of all column pairs. So for example [5.4 2.6] should equal 3 and [5.5 2.2] should equal 2 while the rest of all pairs will equal 1.
I want the numbers to be stored in a new array at the same location as its representative pair, like this:
B(:,:,1) = [2 1 1 3]
B(:,:,2) = [1 3 3 2]
How can I do this as efficiently as possible? I should add that the real array is much larger so I really need an automated solution.
  2 件のコメント
Jan
Jan 2018 年 2 月 26 日
編集済み: Jan 2018 年 2 月 26 日
Do you mean a 2D matrix as output:
B = [2 1 1 3; ...
1 3 3 2]
? Or maybe its transposed?
Hampus Alfredsson
Hampus Alfredsson 2018 年 2 月 26 日
No, A has "n" different sheets of pairs. I want B to have the same amount of sheets since it sounds simpler to relate between pair and number of occurrences that way. I solved the problem using several nested for-loops, but I feel that there is an easier way to do it.

サインインしてコメントする。

採用された回答

Jan
Jan 2018 年 2 月 26 日
編集済み: Jan 2018 年 2 月 26 日
A(:,:,1) = [5.5 2.2; 5.3 2.5; 5.3 2.1; 5.4 2.6];
A(:,:,2) = [5.2 2.9; 5.4 2.6; 5.4 2.6; 5.5 2.2];
[s1, s2, s3] = size(A);
B = reshape(permute(A, [1,3,2]), s1*s3, []);
[C, ~, iB] = unique(B, 'rows', 'stable'); % Find unique pairs
[N, ~, bin] = histcounts(iB,'BinMethod','integers'); % Count the pairs
R = reshape(N(bin), s1, []) % Create output matrix
  1 件のコメント
Hampus Alfredsson
Hampus Alfredsson 2018 年 2 月 26 日
Good solution @Jan Simon. I might use this depending on how my continued coding turns out. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by