calling subfunctions multiple times
Afficher commentaires plus anciens
I have a main function which runs 2 different subfunctions. Both subfunctions do the exact same thing but in different ways (Find the LCM of of all numbers below input n). I want to compare the efficiencies of the subfunctions across many different values and plot them. Here is what I have for my main function with the subfunctions written below it.
function problem5(n)
for i = 0:20
tic; method1(n+i); t1(i+1) = toc;
tic; method2(n+i); t2(i+1) = toc;
end
figure;
plot(0:20,t1,'ro',0:20,t2,'bs'); legend('Method 1','Method2');
figure
semilogy(0:20,t1,'ro',0:20,t2,'bs'); legend('Method 1','Method2');
%Method 1
function[N] = method1(n)
for N = n:n:1e15
for i = n:-1:1
if mod(N,i) ~= 0
break
end
end
if i == 1
N;
break
end
end
%Method 2
function[N] = method2(n)
N = 1;
p = primes(n);
limit = sqrt(n);
a = 1;
i = 1;
while p(i) <= n
if p(i) <= limit
a(i) = floor( log(n) / log(p(i)) );
N = N*(p(i)^a(i));
else
N = N*p(i);
end
i = i+1;
if i == length(p) + 1
break
end
end
Both subfunctions work individually but when I run the script as shown above it doesn't work. Any tips?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Statistics and Machine Learning Toolbox dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!