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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by