calling subfunctions multiple times

6 views (last 30 days)
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?

Accepted Answer

David Hill
David Hill on 27 May 2020
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 Comment
Todd Jones
Todd Jones on 27 May 2020
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!