How to repeat a vector over and over?

5 ビュー (過去 30 日間)
Ali Almakhmari
Ali Almakhmari 2023 年 4 月 6 日
コメント済み: Ali Almakhmari 2023 年 4 月 6 日
I have a vector with a length of 1023 elements (1 by 1023 elements). I want this vector to be 1 by 50000, in other words, change it up to 50000 elements by copying the 1023 elements over and over and over until it stretches to 50000 elements. The thing is, sometimes the original vector's length and the desired one are not compatiable, like this example I gave. 50000/1023 is not necessarily an integer, so the code will have to copy the 1023 elements 48 times and then there will be 896 spaces left, so they will have to be filled with the first 896 elements of the 1023 original elements. I hope someone can help me do this efficiently because I have to do this process like a million time for some analysis I am running :)
  1 件のコメント
Ali Almakhmari
Ali Almakhmari 2023 年 4 月 6 日
Love you all. Thank you so much!

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

採用された回答

John D'Errico
John D'Errico 2023 年 4 月 6 日
編集済み: John D'Errico 2023 年 4 月 6 日
So write a function that does it for you.
vec = 1:4;
repvec(vec,7)
ans = 1×7
1 2 3 4 1 2 3
vec = [0;1];
repvec(vec,8)
ans = 8×1
0 1 0 1 0 1 0 1
function newvec = repvec(vec,finallength)
% replicates elements of a vector to have a final length
nvec = numel(vec);
reps = ceil(finallength/nvec);
newvec = repmat(vec(:),reps,1);
newvec(finallength+1:end) = [];
if isrow(vec), newvec = newvec.'; end
end
repvec will insure the resulting vector is a row or column vector, depending on what came in.

その他の回答 (2 件)

Torsten
Torsten 2023 年 4 月 6 日
移動済み: Torsten 2023 年 4 月 6 日
a = rand(1,1023);
a = repmat(a,1,ceil(50000/1023));
a = a(1:50000)

the cyclist
the cyclist 2023 年 4 月 6 日
編集済み: the cyclist 2023 年 4 月 6 日
Here is one way:
% Inputs (for example small enough to easily see the result)
N = 7;
v = [2 3 5];
% Algorithm
vlen = numel(v);
b = rem(N,vlen);
out = [repmat(v,1,(N-b)/vlen) v(1:b)]
out = 1×7
2 3 5 2 3 5 2

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by