# Ending a recursive function

11 views (last 30 days)
Anirudh Agarwala on 15 Jan 2020
Commented: Anirudh Agarwala on 18 Jan 2020
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

Walter Roberson on 16 Jan 2020
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 on 18 Jan 2020
Thanks, for the option, but what if I just need two inputs, can I still store the inital start in anything?

Star Strider on 15 Jan 2020
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.