Let's say I have a one-dimensional array:
a = [1, 2, 3];
Is there a built-in Matlab function that takes an array and an integer n
and replicates each
element of the array n times?
For example calling replicate(a, 3)
should return [1,1,1,2,2,2,3,3,3]
.
Note that this is not at all the same as repmat
. I can certainly implement replicate
by doing repmat
on each element and concatenating the result, but I am wondering if there is a built in function that is more efficient.
As of R2015a, there is a built-in and documented function to do this,
repelem
: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: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.
I'm a fan of the KRON function:
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):
If you have the image processing toolbox, there is another alternative:
Some exotic alternatives. Admittedly more funny than useful:
Assign the (first) result of
meshgrid
to a vector:Build a matrix that multiplied by
a
gives the result:Use
ind2sub
to generate the indices: