Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise array replication in Matlab

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.

like image 941
Dima Avatar asked Dec 22 '09 17:12

Dima


People also ask

How do you repeat an array of elements in MATLAB?

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 .

How do you replicate an array in MATLAB?

B = repmat( A , n ) returns an array containing n copies of A in the row and column dimensions.

What is Bsxfun MATLAB?

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.


1 Answers

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
like image 85
gnovice Avatar answered Sep 28 '22 13:09

gnovice