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?

采纳的回答

David Hill
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
  1 个评论
Todd Jones
Todd Jones 2020-5-27
Thanks! This makes a lot of sense. My program ends up crashing though. I guess I just have to test for a smaller interval of values so I can still observe some data at least.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by