Recursive function with for loop inside?
9 ビュー (過去 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!