How I finish a recursive function?

18 ビュー (過去 30 日間)
Alejandro Fernández Guerrero
Alejandro Fernández Guerrero 2020 年 9 月 3 日
Hello,
I am really new in matlab programming and I wanted to finish my recursive fuction called partition,
Is a function how find contact points with some conditions implemented in existCP function.
I get the solution of my problen when c(1) == b(1) (STOP CONDITION), but when it should left the partition funcion and export CP as resullt in Recursive function it doesn´t work.
I mean when I run Partition in debugger, the green arrow goes out of partition function but then instead of finish Recursive function the green arrow comes again in Particion(P,X,r,c,b,puntos).
function [CP]=Recursive(P,s,r)
n=length(P);
X(1)=0;
for jj = 1:n-1
X(jj+1)=X(jj)+s;
end
a=[X(1),P(1)];
b=[X(end),P(end)];
points=a;
CP=Particion(P,X,r,a,b,points);
end
function [CP] = Particion(P,X,r,a,b,points)
while 1
[flag,c]=existCP(P,X,r,a,b);
if flag==true
Particion(P,X,r,a,c,points);
else
b=[X(end),P(end)];
if c(1) == b(1)
CP=points;
return
else
points = [points;c];
Particion(P,X,r,c,b,points);
end
end
end
end
  1 件のコメント
Alejandro Fernández Guerrero
Alejandro Fernández Guerrero 2020 年 9 月 3 日
what white arrows means in debugger?

サインインしてコメントする。

回答 (1 件)

Jon
Jon 2020 年 9 月 3 日
In your recursive function there must finally be a branch where you encounter a return.
Once it hits this return, it will back its way up the stack until it finally exits.
If your code never terminates, or hits recursion limit, then somehow your logic must not provide a path for the calculation to finally reach the return statement.
I think the white arrows show where it left the current code and went to the next recursion level.
  2 件のコメント
Jon
Jon 2020 年 9 月 3 日
If I want to try running your code, what values of P,s and r should I use to demonstrate the issue you are having?
Alejandro Fernández Guerrero
Alejandro Fernández Guerrero 2020 年 9 月 3 日
Thanks a lot for your help, but I has just solved the problem,
My noob mistake was not to asign an output value when I was calling Partition.
I fixed in this way and it works if you were curious (see attached).
The clue of my stop condition was that in my last iteration Cexist found a c=b, that is my limit value, so when it call Partition(P,X,r,c,b,puntos) with c=b finally end with the calls.
Anyway, thank you so much for your help.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by