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

 采纳的回答

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 个)

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

3 个评论

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?

请先登录,再进行评论。

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

类别

帮助中心File Exchange 中查找有关 Operators and Elementary Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by