フィルターのクリア

repeated value of a vector

14 ビュー (過去 30 日間)
alessandro mutasci
alessandro mutasci 2021 年 9 月 7 日
コメント済み: Chien Poon 2021 年 9 月 7 日
Good evening, I have a doubt that I can't solve... If I have a vector, like (1, 5, 15, 2), and I want to create another one that has every single value of the vector repeated for a certain number of times, for example 2, having as output (1, 1, 5, 5, 15, 15, 2, 2), what is the best way to do it?
I thougth of using a for cycle for each value of the vector but I don't know how.
  1 件のコメント
Chien Poon
Chien Poon 2021 年 9 月 7 日
a = [1, 5, 15, 2]; % Your vector
b = repmat(a,2,1); % This creates a copy of the vector in the 2nd dimension
c = reshape(b,[],1)'; % We then reshape the matrix back to a vector

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

採用された回答

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 9 月 7 日
編集済み: Abolfazl Chaman Motlagh 2021 年 9 月 7 日
a naive way is to use a loop for every index:
x = [1,5,15,2]; % for example
num = 2; % number of repeat you want
index=1;
for i=1:numel(x) % numel(x) means number of elements in x
for j=1:num
y(index) = x(i);
index = index + 1;
end
end
y
y = 1×8
1 1 5 5 15 15 2 2
by simple loop you can just :
for i=1:num*numel(x)
y2(i) = x(ceil(i/num));
end
y2
y2 = 1×8
1 1 5 5 15 15 2 2
so for example : for both i=1 and i=2, ceil(i/2) would be 1 .
Some easier way :
y3 = repmat(x,[num 1]);
y3 = y(:)'
y3 = 1×8
1 1 5 5 15 15 2 2
the repmat, repeat your array in whatever direction you want. when i use [num 1] it repeats your array num-times in y derection and create a matrix. caling (:) for y will make the result linear in y-direction. finally by ' transpose it, so it would be a linear vector in x-direction.
  1 件のコメント
alessandro mutasci
alessandro mutasci 2021 年 9 月 7 日
thank you so much! very comprehensive!!

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

その他の回答 (1 件)

Dave B
Dave B 2021 年 9 月 7 日
repelem is perfect for this kind of problem:
x = [1 5 15 2]
x = 1×4
1 5 15 2
repelem(x,2)
ans = 1×8
1 1 5 5 15 15 2 2

カテゴリ

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