Extrapolating from linear fit

56 views (last 30 days)
Benjamin Cowen
Benjamin Cowen on 9 Nov 2018
Edited: Bruno Luong on 9 Nov 2018
I have a code, and it works, except is there a way to extend the linear fits past the data they are fitted to? Currently, it plots a line over my data. How can I specify the limits of the linear fit (I'd like to extrapolate). Here is my code:
close all
clear
clc
[D,S] = xlsread('C:\PATH\kvsl.xlsx','500K');
one_over_l = D(:,10);
one_over_k = D(:,11);
ballistic_x = one_over_l((1:7),1);
ballistic_y = one_over_k((1:7),1);
diffusive_x = one_over_l((8:17),1);
diffusive_y = one_over_k((8:17),1);
figure(1)
plot(ballistic_x, ballistic_y,'o')
hold on
P = polyfit(ballistic_x,ballistic_y,1);
yfit1 = P(1)*ballistic_x+P(2);
hold on;
plot(ballistic_x,yfit1,'r-.');
Q = polyfit(diffusive_x,diffusive_y,1);
yfit2 = Q(1)*diffusive_x+Q(2);
hold on;
plot(diffusive_x,yfit2,'b-');
plot(diffusive_x, diffusive_y,'x')
grid on
ylabel('1/\kappa (W/m.K)^{-1}')
xlabel('1/L (\mum^{-1})')

Answers (2)

madhan ravi
madhan ravi on 9 Nov 2018
Edited: madhan ravi on 9 Nov 2018

Bruno Luong
Bruno Luong on 9 Nov 2018
Edited: Bruno Luong on 9 Nov 2018
" Currently, it plots a line over my data. How can I specify the limits of the linear fit (I'd like to extrapolate)."
You get it all wrong, polyfit returns coefficients, for later usage it doesn't care the interval used for fit. You can plot in larger interval if you want
Instead of
yfit1 = P(1)*ballistic_x+P(2);
which is similar to stock function
yfit1 = polyval(P,ballistic_x);
Simply extend x
minx = min(ballistic_x);
maxx = max(ballistic_x);
dx = 0.1*(maxx-minx);
xextended = [minx-dx, maxx+dx];
yextended = polyval(P,xextended );
plot(xextended, yextended ,'r-.');

Community Treasure Hunt

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

Start Hunting!