Recursive function with for loop inside?
6 次查看(过去 30 天)
显示 更早的评论
Hi Comunity.
I come asking for your wisdom
Im writing a recursive function that has a for loop inside.
The idea is to find a precise factor that must be inside the range [5, 10]
This factor is used to calculate the number of points inside a matrix that are above a threshold.
To achieve this I'm iterating over the range untill the number of elements over threshold is 1
For example, lets asume that the factor im looking for is 9.945
Iterating over 5 to 10 is not precise, so im calling the function recursively sending as arguments more precise limits, in this case 9 and 10
The function is working well: the correct factor is returned in the "recursive breaking condition", but due to the loop, continues in the first calls of the recursion, the result is overwriten.
Some ideas of how to achieve this correctly?
A simple idea would be to iterate from 5 to 10 whit a little step, like 0.00001, but the idea is to make it efficient. If the factor is inside the range [9, 10], previous values must be skipped quicly
Here's the code
temp is the matrix that contains numeric values.
Threshold is calculated with as 30 * factor
fact = factor(10, 5, 1, temp, 30);
function f = factor(upLim, downLim, step, temp, threshold)
for i = downLim : step: upLim
numNR = numel(temp(temp > threshold * i))
if step == 0.0001 % Return condition
f = i
return
elseif numNR == 1
f = factor(i, i-(step), step/10, temp, threshold); % Here the range is restricted and the step reduced
end
end
end
When finding the factor value = 9.945 with the step 0.0001, the function is returned, but in the previous calls the for loop continue iterating.
How to totally break the loop when intering the return condition?
Thx a lot for the ideas
5 个评论
采纳的回答
David Hill
2021-3-25
I think you just need a break after your recurssive call.
function f = factor(upLim, downLim, step, temp, threshold)
for i = downLim : step: upLim
numNR = numel(temp(temp > threshold * i))
if step == 0.0001 % Return condition
f = i
return
elseif numNR == 1
f = factor(i, i-(step), step/10, temp, threshold); % Here the range is restricted and the step reduced
break;%I think you just need a break here
end
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!