選択肢から重複を許し​て並べる順列のパター​ンを列挙した行列を作​る方法

32 views (last 30 days)
Yuki Koyama
Yuki Koyama on 10 May 2020
Commented: Yuki Koyama on 11 May 2020
たとえば,[0 1]から重複を許して3つ選び,それらを並べるパターンは
[0 0 0],[0 0 1],[0 1 1],...のように列挙できますが,
[[0 0 0];[0 0 1];[0 1 1];...]
のような行列として作りたい場合,for文を用いずに作る方法はありますか?

Accepted Answer

Akira Agata
Akira Agata on 10 May 2020
meshgrid ndgrid 関数を利用する方法では如何でしょうか?
たとえば [0 1] から重複を許して3つ選ぶという例ですと、以下のようになります。
[x1,x2,x3] = meshgrid([0 1],[0 1],[0 1]);
A = [x1(:),x2(:),x3(:)];
>> A
A =
0 0 0
0 1 0
1 0 0
1 1 0
0 0 1
0 1 1
1 0 1
1 1 1
  2 Comments
Akira Agata
Akira Agata on 10 May 2020
追伸:
出力に sortrows 関数をかけると、出力がより見やすくなります。
A = sortrows(A);
>> A
A =
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Yuki Koyama
Yuki Koyama on 11 May 2020
鮮やかな方法ですね,非常に参考になりました.並べ替えもありがとうございます.

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!