A similar function to R's rep in Matlab [duplicate]

Solution 1:

You can reproduce the syntax of the rep function in R fairly closely by first defining a function as follows:

function [result]=rep(array, count)
matrix = repmat(array, count,1);
result = matrix(:);

Then you can reproduce the desired behavior by calling with either a row or column vector:

>> rep([1 2 3],3)
ans =
 1     1     1     2     2     2     3     3     3

>> rep([1 2 3]',3)
ans =
 1     2     3     1     2     3     1     2     3

Note I have used the transpose (') operator in the second call to pass the input array as a column vector (a 3x1 matrix).

I benchmarked this on my laptop, and for a base array with 100,000 elements repeated 100 times, it was between 2 to 8 times faster than using the ceil option above, depending on whether you want the first or the second arrangement.

Solution 2:

Good question +1. A neat one-liner method to accomplish this is via the Kronecker tensor product, eg:

A = [1 2 3];
N = 3;
B = kron(A, ones(1, N));

Then:

B =

     1     1     1     2     2     2     3     3     3

UPDATE: @Dan has provided a very neat solution that looks to be more efficient than my kron method, so check that answer out before leaving the page :-)

UPDATE: @bcumming has also provided a nice solution that should scale very nicely when the input vector is large.