How to substitute some elements from a vector

조회 수: 2 (최근 30일)
Viridiana  Torres
Viridiana Torres 2016년 5월 10일
답변: Andrei Bobrov 2016년 5월 10일
Hello everyone!
If i have the next vector Z=[10;10;10;11;11;13;13] which is associated to another vector: X=[1;6;65;34;21;73;14] a nd I want to create a third vector, Y, with almost all the elements in X, but just replacing a 0 in X BEFORE the element (i,j) from Z changes. How can I do this? In this example my desire outcome would be the next vector Y=[1;6;0;34;0;73;14]
Thanks a lot for your help!

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 5월 10일
Y = X;
Y([diff(Z(:))~=0;false]) = 0

추가 답변 (1개)

Star Strider
Star Strider 2016년 5월 10일
편집: Star Strider 2016년 5월 10일
This works:
Z=[10;10;10;11;11;13;13];
X=[1;6;65;34;21;73;14];
idx = diff([Z; 0]) > 0; % Logical Vector Detecting Transitions
Y = zeros(size(X));
Y(~idx) = X(~idx)
Y =
1
6
0
34
0
73
14
EDIT — Added output result for Y.

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by