How to make a recursive call to a function using output values stored in a array?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Shanmugavelan S
am 19 Dez. 2021
Kommentiert: Stephen23
am 20 Dez. 2021
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 Kommentare
Akzeptierte Antwort
Voss
am 19 Dez. 2021
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 Kommentare
Stephen23
am 20 Dez. 2021
"needs to be complied in another m. file"
MATLAB is (from a user perspective) an interpreted language, it is not compiled.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!