Need help with defining a variable in my tic toc function
3 次查看(过去 30 天)
显示 更早的评论
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
1 个评论
Jan
2012-11-2
When you do not understand the explanation of the TA, ask him or her again. She or he is payed for the assistence and active students, who ask until they understand, are kept in the memory.
采纳的回答
Amin Bashi
2012-11-2
it's obvious
look at line 29 and 30!
n is vector? or n is scaler?
更多回答(1 个)
Jan
2012-11-2
编辑:Jan
2012-11-2
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!