Return function in a recursive function code
显示 更早的评论
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 个评论
Ameer Hamza
2018-4-25
Can you show us your friends function code, along with data you are using to call that function?
Ameer Hamza
2018-4-25
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
2018-4-25
Walter Roberson
2018-4-25
编辑:Walter Roberson
2018-4-25
The line
Function(A,P,K)
does not change C, so there is no point running the call.
Rdmn Raja
2018-4-25
Ameer Hamza
2018-4-25
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
2018-4-25
Rdmn Raja
2018-4-26
Ameer Hamza
2018-4-26
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
2018-4-26
Ameer Hamza
2018-4-26
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
2018-4-26
Ameer Hamza
2018-4-26
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
2018-4-26
Ameer Hamza
2018-4-26
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
2018-4-27
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!