Ending a recursive function

8 visualizaciones (últimos 30 días)
Anirudh Agarwala
Anirudh Agarwala el 15 de En. de 2020
Comentada: Anirudh Agarwala el 18 de En. de 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 comentarios
Walter Roberson
Walter Roberson el 16 de En. de 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 el 18 de En. de 2020
Thanks, for the option, but what if I just need two inputs, can I still store the inital start in anything?

Iniciar sesión para comentar.

Respuestas (1)

Star Strider
Star Strider el 15 de En. de 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.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by