Clear Filters
Clear Filters

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

39 views (last 30 days)
Yuki Koyama
Yuki Koyama on 10 May 2020
Commented: Akira Agata on 24 Jun 2024 at 3:08
たとえば,[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
  4 Comments
michio
michio on 22 Jun 2024
R2023b からは combinations 関数もおすすめです。
Akira Agata
Akira Agata on 24 Jun 2024 at 3:08
ご参考までに。。。
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 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!