2

Unlike Python, MATLAB list generation expression is limited. In MATLAB I am only allowed to do a:b:c. Can I generate a list [1 2 3 2 3 4 3 4 5 ...] in MATLAB without using for loop?

廖俊杰
  • 31
  • 1

3 Answers3

7
N = 3;
M = 4;
result = reshape((1:N).'+(0:M-1), 1, []);

gives

result =
     1     2     3     2     3     4     3     4     5     4     5     6

How it works

(1:N).'+(0:M-1) uses implicit expansion to create the M×N matrix

 1     2     3   ...  M
 2     3     4   ...  M+1
 3     4     5   ...  M+2
   ...
 N     N+1   N+2 ...  N+M-1

Then reshape(..., 1, []) reshapes this matrix into a row vector, reading the elements in column-major order (down, then across).

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

One approach would be to make three lists [1,2,3...], [2,3,4...] and [3,4,5...] and interleave them. Alternatively, you can take advantage of the pattern: [1,2,3,4,5,6,7,8,9]-[0,0,0,2,2,2,4,4,4]=[1,2,3,2,3,4,3,4,5]. The repelem() function is useful for this kind of operation.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Kyle
  • 31
  • 5
0

You can try cell2mat + arrayfun like belwn

n = 3;
m = 3;
res = cell2mat(arrayfun(@(x) x+(1:n),1:m,'UniformOutput',false));

such that

res =

   2   3   4   3   4   5   4   5   6
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81