MATLAB Answers

Finding minima using for loop and if construct

1 view (last 30 days)
Elijah L
Elijah L on 16 Sep 2020
Commented: Star Strider on 16 Sep 2020
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) ....


Show 1 older comment
Elijah L
Elijah L on 16 Sep 2020
This is the route I'm trying to take... Obviously it doesn't work but is there an easier way to write this script?
zmn = zpoint
for i=1:length(zpoint)
if zpoint(i) < zpoint(i+1) && zpoint(i-1)
Rik on 16 Sep 2020
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 on 16 Sep 2020
Note that one of the two duplicate postings (three total) of this has an Accepted Answer: Finding minima using if and for loops

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 16 Sep 2020
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)
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.


Sign in to comment.

Community Treasure Hunt

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

Start Hunting!