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

たとえば,[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

2 votes

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

4 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
鮮やかな方法ですね,非常に参考になりました.並べ替えもありがとうございます.
michio
michio on 22 Jun 2024
R2023b からは combinations 関数もおすすめです。
ご参考までに。。。
T = combinations([0 1], [0 1], [0 1]);
A = table2array(T) % A = T{:,:} でも可
A = 8x3
0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Sign in to comment.

More Answers (0)

Categories

Find more on 演算子と基本的な演算 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!