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.
u = repelem( v , n ) , where v is a scalar or vector, returns a vector of repeated elements of v . If n is a scalar, then each element of v is repeated n times. The length of u is length(v)*n . If n is a vector, then it must be the same length as v .
B = repmat( A , n ) returns an array containing n copies of A in the row and column dimensions.
The bsxfun function expands the vectors into matrices of the same size, which is an efficient way to evaluate fun for many combinations of the inputs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With