Recursive function with for loop inside?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Felipe Bayona
el 25 de Mzo. de 2021
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 comentarios
Jan
el 25 de Mzo. de 2021
Editada: Jan
el 25 de Mzo. de 2021
I assume Mathieu would insert the break after the "f = factor(..." line. Wouldn't this solve the problem?
But I still think that you should be able to solve this algebraic using the value of the threshold and the one or two largest elements of the array.
Respuesta aceptada
David Hill
el 25 de Mzo. de 2021
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!