calling subfunctions multiple times
6 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
David Hill
2020-5-27
function problem5(n)
k=0:20;%method1 gets very slow causing the function to take a few minutes for low values of n=3
for i=k
tic;
method1(n+i);
t1(i+1)=toc;
tic;
method2(n+i);
t2(i+1)=toc;
end
figure;
plot(k,t1,k,t2); legend('Method 1','Method2');
figure
semilogy(k,t1,k,t2); legend('Method 1','Method2');
end
%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
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
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!