Return function in a recursive function code
Afficher commentaires plus anciens
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 commentaires
Ameer Hamza
le 25 Avr 2018
Can you show us your friends function code, along with data you are using to call that function?
Ameer Hamza
le 25 Avr 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
le 25 Avr 2018
Walter Roberson
le 25 Avr 2018
Modifié(e) : Walter Roberson
le 25 Avr 2018
The line
Function(A,P,K)
does not change C, so there is no point running the call.
Rdmn Raja
le 25 Avr 2018
Ameer Hamza
le 25 Avr 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
le 25 Avr 2018
Rdmn Raja
le 26 Avr 2018
Ameer Hamza
le 26 Avr 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
le 26 Avr 2018
Ameer Hamza
le 26 Avr 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
le 26 Avr 2018
Ameer Hamza
le 26 Avr 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
le 26 Avr 2018
Ameer Hamza
le 26 Avr 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
le 27 Avr 2018
Réponses (0)
Catégories
En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!