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

13 visualizaciones (últimos 30 días)
Simon
Simon el 30 de Jun. de 2014
Comentada: Paul Safier el 8 de Dic. de 2022
Hi all,
like mentioned in the title, is there a fast way of creating a vector with repeating digits?
Thanks!
Simon

Respuesta aceptada

per isakson
per isakson el 30 de Jun. de 2014
Editada: per isakson el 30 de Jun. de 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, [] )

Más respuestas (4)

Andrei Bobrov
Andrei Bobrov el 1 de Jul. de 2014
k = [1;1]*(0:n);
out = k(:)';

Jos (10584)
Jos (10584) el 30 de Jun. de 2014
n = 10 % max value
k = 3 % number of repetitions
V = floor((0:k*(n+1)-1)/k)
  3 comentarios
Jos (10584)
Jos (10584) el 1 de Jul. de 2014
Reshaping does not take a lot of time. Is it also faster for larger values of k?
per isakson
per isakson el 1 de Jul. de 2014
Editada: per isakson el 3 de Jul. de 2014
Is this solution immune to floating point errors?

Iniciar sesión para comentar.


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

Iniciar sesión para comentar.


Danilo NASCIMENTO
Danilo NASCIMENTO el 30 de Jun. de 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

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by