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
0 个评论
采纳的回答
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
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 Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!