Ending a recursive function

조회 수: 3 (최근 30일)
Anirudh Agarwala
Anirudh Agarwala 2020년 1월 15일
댓글: Anirudh Agarwala 2020년 1월 18일
Hi,
I am having a problem ending this function, it should end once it reaches back to the initial start value.
function out = mysequence(start,dec)
n = 0;
if start>0 && dec>0
fprintf('%d ',start);
% n = n+1
start = start - dec;
mysequence(start,dec);
elseif start>0 && dec<0
fprintf('%d ',start);
start = start - dec;
mysequence(start,dec);
elseif start<=0
fprintf('%d ',start);
flag = 1;
start = start + dec;
mysequence(start,-dec);
end
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 1월 16일
if start>0 && dec>0
fprintf('%d ',start);
% n = n+1
start = start - dec;
mysequence(start,dec);
elseif start>0 && dec<0
fprintf('%d ',start);
start = start - dec;
mysequence(start,dec);
What is the difference between those two cases, other than the commented out n = n + 1 ?
You return out from the function, but you never define out .
You have variables n and flag but you do not appear to use them.
it should end once it reaches back to the initial start value.
function out = mysequence(start,dec,initialstart)
if ~exist('initialstart', 'var')
initialstart = start;
end
if start>0
fprintf('%d ',start);
start = start - dec;
if start ~= initialstart
out = mysequence(start,dec,initialstart);
else
out = shrug_you_are_not_clear_on_that;
end
end
Anirudh Agarwala
Anirudh Agarwala 2020년 1월 18일
Thanks, for the option, but what if I just need two inputs, can I still store the inital start in anything?

댓글을 달려면 로그인하십시오.

답변 (1개)

Star Strider
Star Strider 2020년 1월 15일
I have not run your posted code, however two things are immediately apoparent.
First, in the calls to ‘mysequence’, the function calls are not assigning the output to any variable, so that result never gets passed to the function as a variable it can use, other than as as ‘ans‘, that it apparently never uses.
Second, the function calling itself could lead to an infinite recursion (or at least to the MATLAB recursion limit).
Neither of these will likely produce produce the desired result.

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by