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 Center および File ExchangeDescriptive Statistics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by