How to make a recursive call to a function using output values stored in a array?

2 次查看(过去 30 天)
I have a matlab code for mobius function which gives output for the entered single n value. Now, I want make these functions to be called again for array of numbers to make further operations. Here is my code
function mobius (n)
n=input('Enter n');
j=0;
p = factor(n);
N = hist([0 p],max(p)+1);
r = sum(N(2:end) > 1);
disp('The mobius value of'), disp(n), disp('is');
if (n == 1)
u = 1;
elseif (r > 0)
u = 0;
else
k = sum(N(2:end) > 0);
u = (-1)^k;
end
a=[ 4 5 6 8 20];
x=mobius(a(i))+mobius(a(j));
disp(x);
end

采纳的回答

Voss
Voss 2021-12-19
I know you're asking about a recursive call, but I don't think you need a recursive call here because the u calculated one time through the function is correct for the input n. It sounds like you mean you want to call this function multiple times for different n's stored in an array. To do that, you just have to return a value from the function and move the calling of the function out of the function definition (because, again, no recusion is necessary):
function u = mobius (n) % return u
if ~nargin % only prompt the user for n if it wasn't already given
n=input('Enter n');
end
% j=0;
p = factor(n);
N = hist([0 p],max(p)+1);
r = sum(N(2:end) > 1);
disp('The mobius value of'), disp(n), disp('is');
if (n == 1)
u = 1;
elseif (r > 0)
u = 0;
else
k = sum(N(2:end) > 0);
u = (-1)^k;
end
% a=[ 4 5 6 8 20];
% x=mobius(a(i))+mobius(a(j));
% disp(x);
end
So then, somewhere else (e.g., from the command line or in a different function or in a script), you call the function:
a=[ 4 5 6 8 20];
for i = 1:numel(a)
x=mobius(a(i));
disp(x);
end
  6 个评论
Stephen23
Stephen23 2021-12-20
"needs to be complied in another m. file"
MATLAB is (from a user perspective) an interpreted language, it is not compiled.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by