Finding minima using for loop and if construct
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Rik
le 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
le 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
Réponses (1)
Image Analyst
le 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)
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.
0 commentaires
Voir également
Catégories
En savoir plus sur Function Creation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!