Nested Objective function with for loop structure
5 views (last 30 days)
Show older comments
Hi, I have the following code for nested objected function and it has an infinite loop.
Can someone help me to resolve this problem?
% main objective function distance between point and curve set
function d = main_fun (crv,pnts) %accept curve & points as input &return d
t=0:0.01:1;
d=0;
d = distance_fun(t);
for i=1:81
d= d + main_fun(crv,pnts(i));
end
d= sqrt(d);
% secondary objective function for finding t
function y = distance_fun(t) % t is an input here
t= fminbnd(@distance_fun,0,1);
pc = fnval(crv,t);
y = (pnts(1,i)-pc(1,i))^2 + (pnts(2,i)-pc(2,i))^2;
end
end
0 Comments
Answers (1)
Walter Roberson
on 5 Mar 2022
Suppose that you had a function that called itself (your main_fun calls itself for example.) That is a technique called "recursion".
In order for recursion to work, unless you are doing purely theoretical work on hierarchies of infinity, then every recursive call that is made must return at some point.
In order for a recursive call to be sure of returning, the function needs to test its input conditions, determine whether the inputs lead to a trivial solution, and if so compute it non-recursively and return. Only then after the function has determined that the question is complicated should the function call itself.
If you want to be sure that the recursion eventually ends, then each time you make an additional call, the conditions that you pass in should somehow represent a simpler case. For example, decrement a counter that signals end when it reaches 0. Or passes a smaller segment of an array with action ending with 0 or 1 element in the array.
If this is not the case, that each subset gets "simpler" than the previous one, then there needs to be a mathematical argument as to why you should expect eventual end. For example, distance to a prime is unknown but mathematically you can be sure that one exists.
Now... look at your code. You reach distance_fun and the first thing it does is call fminbnd on distance_fun, without having somehow made the work more simple in the subset and without having checked if you are done. distance_fun is an infinite loop of calling itself.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!