Repeat specific elements in vector with keeping the basic vector

3 ビュー (過去 30 日間)
Ali Tawfik
Ali Tawfik 2019 年 11 月 9 日
Hi All,
I have been trying to create a new vector based on old one, by repeating specific elements, I have been looking for a lot of arguments, I found the easily one is repelem, but unfortunately, it repeats elements wtihout keeping the basic one...
I mean I have this vector= [-7.5 -5 -2.5 0 2.5 5 7.5], I'd like the output to be: [-7.5 -5 -2.5 -2.5 0 2.5 5 5 7.5], NOT as my code output
So I need to create the same vector with repeating each 3 elements....
clear all; clc;
x=[-7.5 -5 -2.5 0 2.5 5 7.5];
y=repelem(x(3:3:end),2)
I hope anyone can realy help !!!

回答 (1 件)

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2019 年 11 月 10 日
repelem indeed solves your problem, you just have to give the repetition indexes as a element-wise argument and pass the whole vector
x=[-7.5 -5 -2.5 0 2.5 5 7.5];
y = repelem(x,[1 1 2 1 1 2 1]) % Easier to understand what is happening
% Vectorized solution
Indices = ones(size(x));
Indices(3:3:end) = 2;
y = repelem(x,Indices) % In
y =
-7.5000 -5.0000 -2.5000 -2.5000 0 2.5000 5.0000 5.0000 7.5000

カテゴリ

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