Finding minima using for loop and if construct

조회 수: 4 (최근 30일)
Elijah L
Elijah L 2020년 9월 16일
댓글: Star Strider 2020년 9월 16일
I have a 205x1 matrix of data points called zpoint. I need to write a script using a 'for' loop and an 'if' construct to identify all minima in zpoint.
I want the script to utilize the fact that the previous and next points around the minima points will be greater than it. (possibly using localmin)
This is the start of my script:
n = length(zpoint)
for i = 1:n
if zpoint(i) ....
end
  댓글 수: 4
Rik
Rik 2020년 9월 16일
It might make intuitive sense that you would write it like that, but you're missing several important points:
  • The order of operations: Matlab is first checking if zpoint(i) is smaller than zpoint(i+1). That will return a logical. Next Matlab will evaluate true && zpoint(i-1), which not what you mean. You need to split this into two comparisons.
  • If that statement is true, then what? What should happen? Also, an if in Matlab is a code block: it requires an end statement, just like the for. So your code is missing an end statement. It is even difficult to write what you did in the editor here, because it will automatically add the closing end for you.
Regarding the easier way: there is a way to factor out the loop by using the diff function and looking at the sign of the resulting values.
Star Strider
Star Strider 2020년 9월 16일
Note that one of the two duplicate postings (three total) of this has an Accepted Answer: Finding minima using if and for loops

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

답변 (1개)

Image Analyst
Image Analyst 2020년 9월 16일
You also need to start at 2 and end at the end-1
for i = 2 : length(zpoint)-1
if zpoint(i) < zpoint(i+1) && zpoint(i) < zpoint(i-1)
end
end
And your zmn is not really used for anything so you can get rid of it.
Also, you might want to take a look at movmin(), and imregionalmin() which do the same thing.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by