MATLAB Answers

How to return a value in a recursive function in MATLAB

20 views (last 30 days)
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;
num = varargin{1};
s = num2str(n);
if (length(s) == 1)
disp(['Persistence: ' num2str(num)]);
num = num + 1;
res = 1;
for i = 1:length(s)
res = res * str2double(s(i));
per(res, num);
Something like num = per(n)


Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 25 Mar 2019
function num = per(n, varargin)
and at the end, probably
num = per(res, num)

  1 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.