Asked by Justin Solomon
on 28 Aug 2012

Say I have a column vector x=[a;b;c]. I want to repeat each element n times to make a long length(x)*n vector. For example, for n=3, the answer would be:

ans=

a

a

a

b

b

b

c

c

c

Can anyone think of an elegant way to do this without looping?

Thanks,

Justin

Answer by Azzi Abdelmalek
on 28 Aug 2012

Edited by Azzi Abdelmalek
on 28 Aug 2012

Accepted Answer

n=3 ; x=(1:3)' % example

r=repmat(x,1,n)';

r=r(:)'

Jan
on 29 Aug 2012

This is more efficient than KRON. Small improvement: r = repmat(x, n, 1); without tranposing.

Azzi Abdelmalek
on 29 Aug 2012

%you mean

r = repmat(x', n, 1)

Jan
on 29 Aug 2012

Sign in to comment.

Answer by Walter Roberson
on 28 Aug 2012

kron(x, ones(n,1))

Phat Nguyen
on 7 Apr 2017

Very nice man

Abdelrahman Abdeltawab
on 13 Dec 2018

Dear Walter Roberson,

why you did not use outer product and you chosen kronecker ( just curious ) because the guy's question was having vectors ?

Walter Roberson
on 14 Dec 2018

The * matrix multiplication operator cannot by itself repeat elements. You would need something like

(x.' * repmat(eye(length(x)), 1, n)).'

if you wanted to use the * operator to duplicate elements -- forcing you to call upon repmat() to duplicate elements.

Using the kronecker is a known idiom for duplicating data. It can be used for non-vectors too.

>> kron([1 2;3 4], ones(3,1))

ans =

1 2

1 2

1 2

3 4

3 4

3 4

Sign in to comment.

Answer by Kevin Moerman
on 29 Aug 2012

There is several others ways of doing it which in some cases are more efficient. Have a look at what the size of your vector is and compare the methods. Below I compare speeds and it appears that on my computer the third and fourth methods are mostly faster for large arrays.

n=100000; x=1:3;

a=zeros(n,numel(x)); b=a; c=a; d=a; %memory allocation

tic; a=repmat(x, n, 1); t1=toc; %Repmat method

tic; b=kron(x, ones(n,1)); t2=toc; %kron method

tic; c=x(ones(1,n),:); t3=toc; %indexing method

tic; d=ones(n,1)*x; t4=toc; %multiplication method

Kevin

Answer by Justin Solomon
on 28 Aug 2012

Thanks guys, these all work perfectly!

Sign in to comment.

Answer by Jianshe Feng
on 3 Oct 2016

y = repmat(x,1,3); y = transpose(y); y = y(:);

Sign in to comment.

Answer by Jianshe Feng
on 3 Oct 2016

ind = [1;1;1;2;2;2;3;3;3]; x(ind)

Walter Roberson
on 7 Apr 2017

Ah, but how do you construct the ind vector for general length n repetitions ?

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## John (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/46898-repeat-element-of-a-vector-n-times-without-loop#comment_328477

Sign in to comment.