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

 채택된 답변

per isakson
per isakson 2014년 6월 30일
편집: per isakson 2014년 6월 30일

2 개 추천

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

추가 답변 (4개)

Jos (10584)
Jos (10584) 2014년 6월 30일

2 개 추천

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

댓글 수: 3

Cedric
Cedric 2014년 6월 30일
편집: Cedric 2014년 6월 30일
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) 2014년 7월 1일
Reshaping does not take a lot of time. Is it also faster for larger values of k?
per isakson
per isakson 2014년 7월 1일
편집: per isakson 2014년 7월 3일
Is this solution immune to floating point errors?

댓글을 달려면 로그인하십시오.

Steven Lord
Steven Lord 2022년 12월 8일
n = 5;
x1 = repelem(0:n, 2)
x1 = 1×12
0 0 1 1 2 2 3 3 4 4 5 5

댓글 수: 1

Paul Safier
Paul Safier 2022년 12월 8일
Oh wow, very nice. I'd never heard of the repelem function. Thanks.

댓글을 달려면 로그인하십시오.

Danilo NASCIMENTO
Danilo NASCIMENTO 2014년 6월 30일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

질문:

2014년 6월 30일

댓글:

2022년 12월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by