Return function in a recursive function code
Show older comments
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 Comments
Ameer Hamza
on 25 Apr 2018
Can you show us your friends function code, along with data you are using to call that function?
Ameer Hamza
on 25 Apr 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
on 25 Apr 2018
Walter Roberson
on 25 Apr 2018
Edited: Walter Roberson
on 25 Apr 2018
The line
Function(A,P,K)
does not change C, so there is no point running the call.
Rdmn Raja
on 25 Apr 2018
Ameer Hamza
on 25 Apr 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
on 25 Apr 2018
Rdmn Raja
on 26 Apr 2018
Ameer Hamza
on 26 Apr 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
on 26 Apr 2018
Ameer Hamza
on 26 Apr 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
on 26 Apr 2018
Ameer Hamza
on 26 Apr 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
on 26 Apr 2018
Ameer Hamza
on 26 Apr 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
on 27 Apr 2018
Answers (0)
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!