MATLAB Answers

Simon
0

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

Asked by Simon
on 30 Jun 2014
Latest activity Edited by per isakson
on 3 Jul 2014
Hi all,
like mentioned in the title, is there a fast way of creating a vector with repeating digits?
Thanks!
Simon

  0 Comments

Sign in to comment.

Tags

4 Answers

Answer by per isakson
on 30 Jun 2014
Edited by per isakson
on 30 Jun 2014
 Accepted Answer

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

  1 Comment

Cedric Wannaz
2014 年 6 月 30 日
The REPMAT solution is more efficient.

Sign in to comment.


Answer by Jos (10584)
on 30 Jun 2014

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

  3 Comments

Cedric Wannaz
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.
Reshaping does not take a lot of time. Is it also faster for larger values of k?
Is this solution immune to floating point errors?

Sign in to comment.


回答者: Andrei Bobrov
2014 年 7 月 1 日

k = [1;1]*(0:n);
out = k(:)';

  0 Comments

Sign in to comment.


Answer by 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

  0 Comments

Sign in to comment.