Tic Toc Function Help

Okay so I had a code which had an error, and I thought I fixed it, but now I'm getting another error in it
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;
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);
when i try to run: fh2=@sqrt; [m1,m2]=mycomplexityplot(fh2,5,100)
I get the errors:
Error using polyfit (line 48) X and Y vectors must be the same size.
Error in mycomplexityplot (line 35) p1=polyfit(n(length(n)/2:end),time1(n/2:end),1);
Error in TestCasesLab9 (line 2) [m1,m2]=mycomplexityplot(fh2,5,100
what can do to fix this? sorry for the repost!!

 채택된 답변

Matt Fig
Matt Fig 2012년 11월 2일

0 개 추천

Try these lines instead:
p1=polyfit(n(length(n)/2:end),time1(length(n)/2:end),1);
p2=polyfit(n(length(n)/2:end),time2(length(n)/2:end),1);

댓글 수: 6

Matt
Matt 2012년 11월 2일
thanks, Matt, it's actually running! But I am getting,
m1 =
2.2743e-06
m2 =
4.3520e-04
instead of
m1= 1
m2= 2
is there something wrong i'm doing in my code?
Matt Fig
Matt Fig 2012년 11월 2일
Why do you expect those values?
Matt
Matt 2012년 11월 2일
편집: Matt 2012년 11월 2일
Here is the actual function description, sorry, I should have included that in the first place:
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 the loglog plots are approximately linear, have the 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.
Matt Fig
Matt Fig 2012년 11월 2일
You still have not answered why you expect m1 to be 1 and m2 to be 2.....
Matt Fig
Matt Fig 2012년 11월 2일
Perhaps you are looking for this:
p1=polyfit(log10(n(length(n)/2:end)),log10(time1(length(n)/2:end)),1);
p2=polyfit(log10(n(length(n)/2:end)),log10(time2(length(n)/2:end)),1);
If your question was answered, please accept the answer...
Matt
Matt 2012년 11월 2일
It is 1 and 2 because those are the numbers my instructor gave me to test if my code was right and there's something wrong with it. Thanks though

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2012년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by