MATLAB Answers

0

Generate a N length vector from a M length list (permutation)

Asked by Yue Zhang on 2 Sep 2019
Latest activity Commented on by Yue Zhang on 2 Sep 2019
I have want to generate a 5-element vector:
A = [a1, a2, a3, a4, a5]
such that each element (a1...a5) could take on one of the three values [1, 2, 3];
There should be 3^5 number of outputs.
It should be easy but i have been trying for the last 90 minutes and got no luck.

  4 Comments

Show 1 older comment
Sorry about the confusion. I fixed my statement.
I guess what I'm trying to say is that this should be permutation instead of combination (sequence matters).
The key here is that the number of outputs should be 3^5. [1, 1, 1, 1, 2] and [1, 1, 1, 2, 1] should be two different outputs.
Neither 5 nor 4 is permitted.
You still haven’t answered Stephen’s last question.
No. [1, 1, 1, 1, 2] and [1, 1, 1, 1, 2] should not be two different outputs. However [1, 1, 1, 1, 2] and [1, 1, 1, 2, 1] should.

Sign in to comment.

2 Answers

Answer by Walter Roberson
on 2 Sep 2019

[Ac{1:5}] = ndgrid(1:3);
result = cell2mat(cellfun(@(M) M(:), Ac, 'uniform', 0));

  1 Comment

Thank you! This worked wonders!

Sign in to comment.


Answer by Andrei Bobrov
on 2 Sep 2019

out = fullfact(3*ones(1,5));

  0 Comments

Sign in to comment.