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

6 ビュー (過去 30 日間)
Simon
Simon 2014 年 6 月 30 日
コメント済み: Paul Safier 2022 年 12 月 8 日
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 日
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 件のコメント
Cedric
Cedric 2014 年 6 月 30 日
The REPMAT solution is more efficient.

サインインしてコメントする。

その他の回答 (4 件)

Andrei Bobrov
Andrei Bobrov 2014 年 7 月 1 日
k = [1;1]*(0:n);
out = k(:)';
  1 件のコメント
Paul Safier
Paul Safier 2022 年 12 月 8 日
Perfect.

サインインしてコメントする。


Jos (10584)
Jos (10584) 2014 年 6 月 30 日
n = 10 % max value
k = 3 % number of repetitions
V = floor((0:k*(n+1)-1)/k)
  3 件のコメント
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 日
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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by