Generating Array from nested loops

10 views (last 30 days)
So Ive been trying to create an array of 4 numbers using nested loops The first number goes from 1:5 The second number goes from 1:2 The third number goes from 1:3 The fourth number goes from 1:4
so that
A= [1 1 1 1
1 2 1 1
1 2 2 1
1 2 2 2
1 3 1 1
1 3 2 1
. . . .
. . . .
5 2 3 4 ]
So i been trying to use nested loops to generate that example
for n1 = 1: 5
n(n1,:) = [n1]
for n2 = 1: 2
n(n2,:) = [n2]
end
end
But this replaces my previous input. How do i make so i make that 4 element array of all possible values.

Accepted Answer

Stephen23
Stephen23 on 21 Apr 2017
Edited: Stephen23 on 21 Apr 2017
Download combinations or allcomb from MATLAB FEX:
>> sortrows(combinations(1:5,1:2,1:3,1:4))
ans =
1 1 1 1
1 1 1 2
1 1 1 3
1 1 1 4
1 1 2 1
1 1 2 2
1 1 2 3
1 1 2 4
1 1 3 1
1 1 3 2
1 1 3 3
1 1 3 4
1 2 1 1
1 2 1 2
1 2 1 3
1 2 1 4
1 2 2 1
1 2 2 2
1 2 2 3
1 2 2 4
1 2 3 1
1 2 3 2
1 2 3 3
1 2 3 4
2 1 1 1
2 1 1 2
2 1 1 3
2 1 1 4
2 1 2 1
2 1 2 2
2 1 2 3
2 1 2 4
2 1 3 1
2 1 3 2
2 1 3 3
2 1 3 4
2 2 1 1
2 2 1 2
2 2 1 3
2 2 1 4
2 2 2 1
2 2 2 2
2 2 2 3
2 2 2 4
2 2 3 1
2 2 3 2
2 2 3 3
2 2 3 4
3 1 1 1
3 1 1 2
3 1 1 3
3 1 1 4
3 1 2 1
3 1 2 2
3 1 2 3
3 1 2 4
3 1 3 1
3 1 3 2
3 1 3 3
3 1 3 4
3 2 1 1
3 2 1 2
3 2 1 3
3 2 1 4
3 2 2 1
3 2 2 2
3 2 2 3
3 2 2 4
3 2 3 1
3 2 3 2
3 2 3 3
3 2 3 4
4 1 1 1
4 1 1 2
4 1 1 3
4 1 1 4
4 1 2 1
4 1 2 2
4 1 2 3
4 1 2 4
4 1 3 1
4 1 3 2
4 1 3 3
4 1 3 4
4 2 1 1
4 2 1 2
4 2 1 3
4 2 1 4
4 2 2 1
4 2 2 2
4 2 2 3
4 2 2 4
4 2 3 1
4 2 3 2
4 2 3 3
4 2 3 4
5 1 1 1
5 1 1 2
5 1 1 3
5 1 1 4
5 1 2 1
5 1 2 2
5 1 2 3
5 1 2 4
5 1 3 1
5 1 3 2
5 1 3 3
5 1 3 4
5 2 1 1
5 2 1 2
5 2 1 3
5 2 1 4
5 2 2 1
5 2 2 2
5 2 2 3
5 2 2 4
5 2 3 1
5 2 3 2
5 2 3 3
5 2 3 4

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!