19 views (last 30 days)

Here is my Problem: In this part of the problem, we want to explore O(Nx), a measure of asymptotic complexity of evaluating a function using nested for-loops. For the purposes of this exercise, we will use the following approach. We want to compare the complexity of evaluating a function in a single for-loop with the same function evaluated in a nested for-loop, both going through the same number of iterations

Create a function, called mycomplexityplot, which takes in a function handle, fh2, a scalar value, x2, at which to evaluate fh2, and the number of iterations, N, up to which the for-loops should be evaluated. Use loglog to plot the time it takes to evaluate the function either inside one loop or inside two for-loops (each loop iterates N times) for increasing values of N. Finally, assuming your loglog plots are approximately linear, have your function output the slope of each line, rounded to the nearest whole number using polyfit. For the single loop calculation, call the slope m1. For the double loop calculation, call it m2. Code:

function [m1,m2]=mycomplexityplot(fh2,x2,N)

time1=zeros(1,N);

for i = 1:N

tic

for k1=1:i

fh2(x2);

end

time1(i)=toc;

end

time2=zeros(1,N);

for i2=1:N

tic

for k2=1:i2

for k3=1:i2

fh2(x2);

end

end

time2(i2)=toc;

end

n=1:N;

%plotting

loglog(n,time1,'b-')

hold on

loglog(n,time2,'g--')

legend('1 loop','2 loops')

xlabel('N')

ylabel('time(s)')

hold off

p1=polyfit(n(length(n)/2:end),time1(n/2:end),1);

p2=polyfit(n(length(n)/2:end),time2(n/2:end),1);

m1=p1(1);

m2=p2(1);

I get the Error: Undefined function or variable 'fh2'.

what is wrong with my code? I tried asking my TA but he I wasn't able to understand his explanation

Amin Bashi
on 2 Nov 2012

it's obvious

look at line 29 and 30!

n is vector? or n is scaler?

Jan
on 2 Nov 2012

In my counting the lines 29 and 30 are:

xlabel('N')

ylabel('time(s)')

It is not obvious how these lines create the error "Undefined function or variable 'fh2'".

Jan
on 2 Nov 2012

Edited: Jan
on 2 Nov 2012

You forgot to mention the only important line of code: The command which calls the function. Do you call it like this:

[m1,m2] = mycomplexityplot(@sum, rand(1, 1000), 100)

? A call like this would create the above error:

[m1,m2] = mycomplexityplot

It would reveal the cause of the error, when you post the complete error message using copy&paste. Posting just a part of it conceals the problem and an answer require guessing.

Opportunities for recent engineering grads.

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

Start Hunting!
## 1 Comment

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/52561-need-help-with-defining-a-variable-in-my-tic-toc-function#comment_108815

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/52561-need-help-with-defining-a-variable-in-my-tic-toc-function#comment_108815

Sign in to comment.