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

39 次查看(过去 30 天)
Yuki Koyama
Yuki Koyama 2020-5-10
评论: Akira Agata 2024-6-24,3:08
たとえば,[0 1]から重複を許して3つ選び,それらを並べるパターンは
[0 0 0],[0 0 1],[0 1 1],...のように列挙できますが,
[[0 0 0];[0 0 1];[0 1 1];...]
のような行列として作りたい場合,for文を用いずに作る方法はありますか?

采纳的回答

Akira Agata
Akira Agata 2020-5-10
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 个评论
michio
michio 2024-6-22
R2023b からは combinations 関数もおすすめです。
Akira Agata
Akira Agata 2024-6-24,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>

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!