How to iterate over cell array, creating only unique combinations of cells

5 ビュー (過去 30 日間)
Phoebe Daphne
Phoebe Daphne 2021 年 1 月 11 日
コメント済み: Phoebe Daphne 2021 年 1 月 11 日
Hello,
I have data stored in a n x n cell array. For example:
data = {[1 1 1] [2 2 2]; [3 3 3] [4 4 4]};
I want to iterate over this cell array and create all unique combinations of cells. In this case, they would be:
  • [1 1 1] [2 2 2]
  • [1 1 1] [3 3 3]
  • [1 1 1] [4 4 4]
  • [2 2 2] [3 3 3]
  • [2 2 2] [4 4 4]
  • [3 3 3] [4 4 4]
Please note that every combination (e.g. [1 1 1][2 2 2]) only exists once regardless of order (i.e., there is no [2 2 2][1 1 1] combination).
I have tried doing this with for loops, however, I can't get behind how to not create the second combination.
Important note: I am trying to do this with for-loops since I need a way to keep track of from which column the combination is coming from (i.e. if the two data points are from the same column --> this would apply to [1 1 1][3 3 3] and [2 2 2][4 4 4] in my example). Therefore any function which simply returns me the permutations or binary coefficient won't work.

採用された回答

Stephen23
Stephen23 2021 年 1 月 11 日
編集済み: Stephen23 2021 年 1 月 11 日
data = {1,2;3,4};
n = numel(data);
m = nchoosek(1:n,2) % each row is one combination pair.
m = 6×2
1 2 1 3 1 4 2 3 2 4 3 4
out = data(m) % output
out = 6x2 cell array
{[1]} {[3]} {[1]} {[2]} {[1]} {[4]} {[3]} {[2]} {[3]} {[4]} {[2]} {[4]}
[idr,idc] = ind2sub(size(data),m);
idx = ~diff(idc,1,2) % output is from the same column
idx = 6x1 logical array
1 0 0 0 0 1

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by