How to obtain an array of the indices from the original array when using nchoosek

5 ビュー (過去 30 日間)
How do I use nchoosek and also efficiently generate an array that has the indices from the original array. For instance,
A = [7, 8, 9]
B = nchoosek(A, 2)
so B = [7, 8; 7, 9; 8, 9]
I want a matrix C that holds the indices in A of all the members of B:
C = [1, 2; 1, 3; 2, 3].
I can generate C using a for loop since we know how nchoosek is going to generate the combinations, but this seems very wasteful precisely because we know how nchoosek is going to generate the combinations, all the information of the indices is already there in our first call of nchoosek. How do I get C efficiently?

採用された回答

the cyclist
the cyclist 2023 年 8 月 22 日
編集済み: the cyclist 2023 年 8 月 22 日
I have to admit I am not absolutely certain about what you want as input and output. Here is my best guess:
A = [7, 8, 9];
C = nchoosek(1:numel(A),2)
C = 3×2
1 2 1 3 2 3
B = A(C)
B = 3×2
7 8 7 9 8 9

その他の回答 (1 件)

Torsten
Torsten 2023 年 8 月 22 日
編集済み: Torsten 2023 年 8 月 22 日
You better get B from C, not C from B:
A = [7, 8, 9];
v = 1:numel(A);
C = nchoosek(v,2)
C = 3×2
1 2 1 3 2 3
B = A(C)
B = 3×2
7 8 7 9 8 9
  1 件のコメント
Kevin H
Kevin H 2023 年 8 月 22 日
Thank you. Same answer as the cyclist and I think he was like a minute before you so I accepted his.

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

カテゴリ

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