Nested Objective function with for loop structure

조회 수: 4 (최근 30일)
Elias
Elias 2022년 3월 5일
편집: Walter Roberson 2022년 3월 5일
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

답변 (1개)

Walter Roberson
Walter Roberson 2022년 3월 5일
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.
  댓글 수: 3
Elias
Elias 2022년 3월 5일
Thanks alot I will look at it .

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by