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

Hi all,
like mentioned in the title, is there a fast way of creating a vector with repeating digits?
Thanks!
Simon

 Akzeptierte Antwort

per isakson
per isakson am 30 Jun. 2014
Bearbeitet: per isakson am 30 Jun. 2014

2 Stimmen

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, [] )

Weitere Antworten (4)

Jos (10584)
Jos (10584) am 30 Jun. 2014

2 Stimmen

n = 10 % max value
k = 3 % number of repetitions
V = floor((0:k*(n+1)-1)/k)

3 Kommentare

Cedric
Cedric am 30 Jun. 2014
Bearbeitet: Cedric am 30 Jun. 2014
Interestingly the RESHAPE/REPMAT solution above is faster than the FLOOR approach for k=2 and n=1e7 .. I didn't expect that.
Jos (10584)
Jos (10584) am 1 Jul. 2014
Reshaping does not take a lot of time. Is it also faster for larger values of k?
per isakson
per isakson am 1 Jul. 2014
Bearbeitet: per isakson am 3 Jul. 2014
Is this solution immune to floating point errors?

Melden Sie sich an, um zu kommentieren.

n = 5;
x1 = repelem(0:n, 2)
x1 = 1×12
0 0 1 1 2 2 3 3 4 4 5 5

1 Kommentar

Paul Safier
Paul Safier am 8 Dez. 2022
Oh wow, very nice. I'd never heard of the repelem function. Thanks.

Melden Sie sich an, um zu kommentieren.

Danilo NASCIMENTO
Danilo NASCIMENTO am 30 Jun. 2014

0 Stimmen

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

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Hilfe-Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by