How to return a value in a recursive function in MATLAB

15 ビュー (過去 30 日間)
Arindam Bose
Arindam Bose 2019 年 3 月 25 日
コメント済み: Arindam Bose 2019 年 3 月 25 日
I have a recursive function to calculate the multiplicative persistence of an integer. I can print the value inside the function. My question is how can I return the value to the outside of the function.
Here is my code:
I want to return the value of num
function per(n, varargin)
if nargin == 1
num = 0;
else
num = varargin{1};
end
s = num2str(n);
if (length(s) == 1)
disp(['Persistence: ' num2str(num)]);
return;
end
num = num + 1;
res = 1;
for i = 1:length(s)
res = res * str2double(s(i));
end
per(res, num);
end
Something like num = per(n)

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 25 日
function num = per(n, varargin)
and at the end, probably
num = per(res, num)
  1 件のコメント
Arindam Bose
Arindam Bose 2019 年 3 月 25 日
Wow, thanks a bunch. Works like a charm.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by