# Fast creation of vector [0 0 1 1 2 2 3 3... n n]

33 views (last 30 days)
Simon on 30 Jun 2014
Commented: Paul Safier on 8 Dec 2022
Hi all,
like mentioned in the title, is there a fast way of creating a vector with repeating digits?
Thanks!
Simon

per isakson on 30 Jun 2014
Edited: per isakson on 30 Jun 2014
Test
>> reshape( cat( 1, [0:n], [0:n] ), 1, [] )
ans =
0 0 1 1 2 2 3 3 4 4 5 5
and
>> reshape( repmat( [0:n], 2,1 ), 1, [] )
Cedric Wannaz on 30 Jun 2014
The REPMAT solution is more efficient.

Andrei Bobrov on 1 Jul 2014
k = [1;1]*(0:n);
out = k(:)';
Paul Safier on 8 Dec 2022
Perfect.

Jos (10584) on 30 Jun 2014
n = 10 % max value
k = 3 % number of repetitions
V = floor((0:k*(n+1)-1)/k)
per isakson on 1 Jul 2014
Edited: per isakson on 3 Jul 2014
Is this solution immune to floating point errors?

Steven Lord on 8 Dec 2022
n = 5;
x1 = repelem(0:n, 2)
x1 = 1×12
0 0 1 1 2 2 3 3 4 4 5 5
Paul Safier on 8 Dec 2022
Oh wow, very nice. I'd never heard of the repelem function. Thanks.

Danilo NASCIMENTO on 30 Jun 2014
V=zeros(1,20);
k=0;
i=1;
while i<20
V(i)=k;
V(i+1)=k;
k=k+1;
i=i+2;
end
V