Element-wise array replication in Matlab Element-wise array replication in Matlab arrays arrays

Element-wise array replication in Matlab


I'm a fan of the KRON function:

>> a = 1:3;>> N = 3;>> b = kron(a,ones(1,N))b =    1     1     1     2     2     2     3     3     3

You can also look at this related question (which dealt with replicating elements of 2-D matrices) to see some of the other solutions involving matrix indexing. Here's one such solution (inspired by Edric's answer):

>> b = a(ceil((1:N*numel(a))/N))b =    1     1     1     2     2     2     3     3     3


As of R2015a, there is a built-in and documented function to do this, repelem:

repelem Replicate elements of an array.
    W = repelem(V,N), with vector V and scalar N, creates a vector W where each element of V is repeated N times.

The second argument can also be a vector of the same length as V to specify the number of replications for each element. For 2D replication:

B = repelem(A,N1,N2)

No need for kron or other tricks anymore!

UPDATE: For a performance comparison with other speedy methods, please see the Q&A Repeat copies of array elements: Run-length decoding in MATLAB.