Search code examples
matlabplotmatlab-figurelinear-regressionloglog

Wrong Y-intercept for best fit line of loglog plot


I've tried the solutions from many guides to plot the best fit line for my loglog plot but I keep getting a line that appears to have the correct slope but a y-intercept that is way too large. The graph is plotted in the last chunk of code.

Example screenshot of plot:

Example screenshot of plot

N=2; % Starting/current matrix size
M=1; % Number of trials per matrix
incr=2; %matrix size increment
reps=20; %number of increments
all_errs=zeros(reps,1); %vector of mean erros for each N
used_N=zeros(reps,1); %values of N used for plot

%find M such that max margin of error <0.01 for confidence interval
desired_margin=0.01; %desired margin of error
conf=0.98; %value for confidence interval
curr_margin=conf/sqrt(M); %current margin of error

while curr_margin>=desired_margin
    M=M+1;
    curr_margin=conf/sqrt(M);
end

for h=1:reps
    used_N(h)=N; %add current value of N to list of used N values
    errs=zeros(M,1); % Vector of errors
    x=ones(N,1); % exact solution vector

    for i=1:M
        A=spdiags(rand(N,3), -1:1, N,N); %constructs tridiagonal matrx with random entries
        b=A*x; % Compute the right-hand side vector
        z=A\b; % Solve the linear system
        errs(i)=max(abs(z-x)); % Compute the error
    end

    mean_err=mean(errs);
    all_errs(h)=mean(errs);
    N=N+incr; %increments N

end
%disp(all_errs)

p=polyfit(log10(used_N), log10(all_errs), 1); %fits line to data
fit=exp(polyval(p,log10(used_N))); %y-coordinates of best fit line
loglog(used_N, all_errs, 'o',used_N,fit,'-'); %plots the error versus N in a loglog plot w/best fit line
title(['Log-Log Plot for Matrix Size vs. Mean Error'],'fontsize',14)
xlabel('log_{10}(Size of Matrix)','fontsize',12)
ylabel('log_{10}(Mean Error)','fontsize',12)

Solution

  • You're taking the log base 10 before polyfit, but then transforming back using e. Instead you should be using 10.

    fit=10.^(polyval(p,log10(used_N)));