All the combinations for 3 variables

30 ビュー (過去 30 日間)
Salad Box
Salad Box 2023 年 1 月 13 日
コメント済み: Salad Box 2023 年 1 月 13 日
Hi,
I have 3 variables, each of which is an array containing differnet numbers of elements.
If I take a simple case as an example, for instance,
x = [0, 1];
y = [0, 1];
z = [0, 1];
Then in reality I would have in total 8 different combinations of xyz that are xyz =
[0 0 0;
0 0 1;
0 1 0;
0 1 1;
1 0 0;
1 0 1;
1 1 0;
1 1 1];
I wonder whether Matlab has a function for this application or do I have to loop it and write my own algorithm in order to obtain all different combinations.
If there is a function, I expect it to be more robust for cases that x, y and z doesn't have to be the same length. In another word, x, y and z doesnt have to contain same number of elements.
Because in reality I would have a lot of points in each of those x, y and z, if I loop it it is gonna take forever I guess.

採用された回答

Torsten
Torsten 2023 年 1 月 13 日
編集済み: Torsten 2023 年 1 月 13 日
Or use ndgrid:
x = [0, 1];
y = [0, 1];
z = [0, 1];
[X,Y,Z] = ndgrid(x,y,z);
result = [X(:) Y(:) Z(:)]
result = 8×3
0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1
  1 件のコメント
Salad Box
Salad Box 2023 年 1 月 13 日
That worked perfectly. Thank you very much.:)

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

その他の回答 (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