Ending a recursive function

3 Ansichten (letzte 30 Tage)
Anirudh Agarwala
Anirudh Agarwala am 15 Jan. 2020
Kommentiert: Anirudh Agarwala am 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
  2 Kommentare
Walter Roberson
Walter Roberson am 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
Anirudh Agarwala am 18 Jan. 2020
Thanks, for the option, but what if I just need two inputs, can I still store the inital start in anything?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Star Strider
Star Strider am 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.

Community Treasure Hunt

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

Start Hunting!

Translated by