How to make a loop that writes in a new vector only values that meet a condition?

조회 수: 3 (최근 30일)
I'm trying to make some kind of data filter that goes through a vector, compares every value with the previous one and writes the value in a new vector only if it is bigger than the previous one.
VPo=[0 0 0 0 1 0 2 3 4 0 5 4 3 0 2 1 0 0 0 0];
I wrote this simple loop:
[row, column]=find (VPo == max(VPo));
for i=2:row
if VPo (i,1) >= VPo (i-1,1)
VPoF(i) = VPo(i,1);
end
end
The problem is that it writes all the values from VPo to VPoF until max(VPo) and doesn't do anything:
VPoF = VPo=[0 0 0 0 1 0 2 3 4 0 5];

채택된 답변

James Tursa
James Tursa 2020년 1월 24일
Assuming you don't want the first value since there is no previous value to compare to:
x = [false, diff(VPo) > 0];
VPoF = VPo(x);
If you do want that first value, change the false to true.
  댓글 수: 3
James Tursa
James Tursa 2020년 1월 24일
The diff( ) function calculates the difference between successive elements. The expression above simply looks for when this is positive (indicating the value increased) as a logical result. Then this is used as a logical index into VPo to extract your result.
Tsvetan Yorov
Tsvetan Yorov 2020년 1월 25일
Thank you for the detailed explanation! It makes sense now.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by