Finding minima using for loop and if construct
1 次查看(过去 30 天)
显示 更早的评论
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
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
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!