フィルターのクリア

Generate automatically vectors of precise length and given values

13 ビュー (過去 30 日間)
Dimitris M
Dimitris M 2014 年 5 月 23 日
コメント済み: Jos (10584) 2014 年 5 月 23 日
Hello
I want to automatically construct a vector of user defined size using a set of elements defined within a second vector by filling the 1st vector linearly.
As a small example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
vector_2 = [1,100,2,100,3,100,4]
length_vector_1 = 12
% vector to be automatically generated
vector_1 = [1,100,2,100,3,100,4,100,1,100,2,100]
length_vector_1 = 3
% vector to be automatically generated
vector_1 = [1,100,2]
Is there a way to generate such vectors ?
Thanks in advance

採用された回答

José-Luis
José-Luis 2014 年 5 月 23 日
編集済み: José-Luis 2014 年 5 月 23 日
vector_2 = [1,100,2,100,3,100,4];
numVal = 19;
your_vec = repmat(vector_2,1,ceil(numVal/numel(vector_2)));
your_vec = your_vec(1:numVal);
Please accept an answer if it helped you.
  2 件のコメント
Dimitris M
Dimitris M 2014 年 5 月 23 日
Very nice answer ! Thanks
José-Luis
José-Luis 2014 年 5 月 23 日
My pleasure

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 5 月 23 日
No need to create an intermediate vector with repmat that could be much longer than the final one. Just use simple indexing into the original vector:
vector_2 = [1,100,2,100,3,100,4];
length_vector_1 = 19;
vector_1 = vector_2(rem(0:length_vector_1 - 1, numel(vector_2))+1)
  2 件のコメント
José-Luis
José-Luis 2014 年 5 月 23 日
Here's the trade-off:
vector_2 = rand(1,777777);
numVal = 100000000;
tic
your_vec = repmat(vector_2,1,ceil(numVal/numel(vector_2)));
your_vec = your_vec(1:numVal);
toc
vector_1 = vector_2(rem(0:numVal - 1, numel(vector_2))+1);
toc
Elapsed time is 3.062471 seconds.
Elapsed time is 5.132982 seconds.
Jos (10584)
Jos (10584) 2014 年 5 月 23 日
Indeed, my code is faster!
(You forgot to put a tic …)

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by