Return function in a recursive function code
Mostrar comentarios más antiguos
When I create a recursive code and have the desired output, after following it with 'return' the next line - it continues running and outputting unwanted results - can someone help me avoid this please.
17 comentarios
Ameer Hamza
el 25 de Abr. de 2018
Can you show us your friends function code, along with data you are using to call that function?
Ameer Hamza
el 25 de Abr. de 2018
I think in the first condition you meant K=P. The only reason it can be happening is C never becomes equal to P.
Rdmn Raja
el 25 de Abr. de 2018
Walter Roberson
el 25 de Abr. de 2018
Editada: Walter Roberson
el 25 de Abr. de 2018
The line
Function(A,P,K)
does not change C, so there is no point running the call.
Rdmn Raja
el 25 de Abr. de 2018
Ameer Hamza
el 25 de Abr. de 2018
If you want to return P from the last termination call to recursive function than you will need to assign it to the output of Function in else condition like this
[C]=Function(A,P,K)
%A is adjacency matrix of a Graph say
%P, K are vectors
if (terminating condition)
C=P;
return
else
......
P=.....%redefined
K=.....%redefined
C = Function(A,P,K);
end
end
No point of using disp if you want the output in a matrix.
Rdmn Raja
el 25 de Abr. de 2018
Rdmn Raja
el 26 de Abr. de 2018
Ameer Hamza
el 26 de Abr. de 2018
There is no recursion in above code. It is hard to spot an error if we cannot see where the recursion is happening.
Rdmn Raja
el 26 de Abr. de 2018
Ameer Hamza
el 26 de Abr. de 2018
Are you sure that termination condition is met? Apparently, the above code is logically correct and it should fall out of recursion once termination condition is met.
Rdmn Raja
el 26 de Abr. de 2018
Ameer Hamza
el 26 de Abr. de 2018
What do you mean by "further steps". The only statement after that is return. What exactly it is doing after
assignin('base','x',C);
Rdmn Raja
el 26 de Abr. de 2018
Ameer Hamza
el 26 de Abr. de 2018
From the code you gave, all calls to HELP function are followed by end. There are no statements after that. How can the function start editing matrices? Or are there any other statements which you haven't included in the given code?
One possible solution can be adding a return after every call to HELP. For example
if isempty(P)==1
HELP(A,[],1:length(A),[],i+1,1,0,[],C);
return;
else
HELP(A,R,P,X,i,j+1,n-1,D,C);
return;
end
Similar for other two calls to HELP.
Rdmn Raja
el 27 de Abr. de 2018
Respuestas (0)
Categorías
Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!