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;endtime2=zeros(1,N);for i2=1:N tic for k2=1:i2 for k3=1:i2 fh2(x2); end end time2(i2)=toc;endn=1:N;%plotting
loglog(n,time1,'b-')hold onloglog(n,time2,'g--')legend('1 loop','2 loops')xlabel('N')ylabel('time(s)')hold offp1=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
Best Answer