In matlab, how to generate a vector like this:
[1,1,1,...,1,1, 2,2,2,...,2,2, 3,3,3,...,3,3, 4,4,4,...,4,4]
Given the simple structure of your vector, a very simple solution is available:
ceil((1:24)/6)
Very fast for small vectors, and competitive for large ones. When the vector gets really large the reshape
alternative has better speed.
Of course it can easily be generalized:
N = 4;
M = 6;
ceil((1:M*N)/M)
You can use:
N = 4;
M = 6;
result = reshape(repmat(1:N,M,1),1,[])
This works by generating [1,2,3,...,N]
, then copying into M
rows (repmat
), and then reading by columns (reshape
).
A usually faster alternative is to replace repmat
by matrix product and reshape
by linear indexing (thanks to @Dan and @Floris):
result = ones(M,1)*(1:N);
result = result(:).'
Also see @Dan's answer, which may be faster depending on the version/machine, or @Dennis's, which is probably the fastest.
kron(1:4, ones(1,6))
I think using a kronecker product might be quicker, but it also might not. See A similar function to R's rep in Matlab