Create array of values returned from inside an if statement.

Here is sample code for what I am trying to achieve. This loop correctly returns the values I want (where the value is larger than the previous and subsequent values). Thus, it returns 4, 5, and 9 correctly. However, I want ex_vals to be an array of these values (ex_vals = [4,5,9]) but this code just returns and overwrites ex_vals each time. This seems simple but I have not used Matlab in a while. Any help is appreciated.
ex = [1,2,3,4,3,4,5,4,5,6,7,8,9,7];
for i = 2:length(ex)-1
if ex(i) > ex(i-1) & ex(i) > ex(i+1)
ex_vals = ex(i)
end
end

 채택된 답변

Subscript it —
ex = [1,2,3,4,3,4,5,4,5,6,7,8,9,7];
for i = 2:length(ex)-1
if ex(i) > ex(i-1) & ex(i) > ex(i+1)
ex_vals(i) = ex(i);
end
end
ex_vals
ex_vals = 1×13
0 0 0 4 0 0 5 0 0 0 0 0 9
.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 6월 3일

답변:

2021년 6월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by