LoginSignup
1
0

More than 1 year has passed since last update.

【MATLAB】重複を許し​て並べるパターンをすべて列挙する

Last updated at Posted at 2021-12-30

やりたいこと

例えば、1,2,3 のうちから重複を許して3つ選び、その並べ方をすべて列挙したい、というケースです。この場合、$3^3=27$通りあります。

方法

MATLABのndgrid関数を使います。

1~3の整数から3つ選んで並べる

[x1,x2,x3] = ndgrid(1:3,1:3,1:3);
[x3(:),x2(:),x1(:)]

出力結果

ans =

     1     1     1
     1     1     2
     1     1     3
     1     2     1
     1     2     2
     1     2     3
     1     3     1
     1     3     2
     1     3     3
     2     1     1
     2     1     2
     2     1     3
     2     2     1
     2     2     2
     2     2     3
     2     3     1
     2     3     2
     2     3     3
     3     1     1
     3     1     2
     3     1     3
     3     2     1
     3     2     2
     3     2     3
     3     3     1
     3     3     2
     3     3     3

A,B,Cで作られる4文字の単語

応用すれば、辞書順も作れます。

[x1,x2,x3,x4] = ndgrid('ABC','ABC','ABC','ABC');
[x4(:),x3(:),x2(:),x1(:)]

出力結果

ans =

  81×4  char 配列

    'AAAA'
    'AAAB'
    'AAAC'
    'AABA'
    'AABB'
    'AABC'
    'AACA'
    'AACB'
    'AACC'
    'ABAA'
    'ABAB'
    'ABAC'
    'ABBA'
    'ABBB'
    'ABBC'
    'ABCA'
    'ABCB'
    'ABCC'
    'ACAA'
    'ACAB'
    'ACAC'
    'ACBA'
    'ACBB'
    'ACBC'
    'ACCA'
    'ACCB'
    'ACCC'
    'BAAA'
    ...
    'CCCC'

参考サイト

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

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0