Linear And Cubic Curve Fitting
- Curve Fitting Equations
For the curve fitting we used linear regression for linear fit.
For linear fit the expression is given as: y=mx + c,
Where y is a function of x and m is slope and, c is y intercept of function. m and c are constant.
We need to calculate the constant to make a linear fit for given data and to find the constant we can use these equations.
For Cubic fit the expression is given as: y=ax3 + bx2 + cx + d,
Where y is a function of x and a, b, c, d are constants these constants can be solved by matrix calculation;
In [Y] and [X] matrix take only four points to solve the matrix problem but take at equal interval throughout the data.
Then constants can be equated using the equation:
%Program for Calculating Curve fit
clear all
close all
clc
%Preparing Data
file=load('data');
temp=file(:,1);
cp=file(:,2);
%Curve Fit
Co=LR(temp,cp); %Coefficient for linear fit
Co3=CR(temp,cp); %Coefficient for cubic fit
P_cp=polyval(Co,temp); %Predicted Cp for linear fit
for i=1:length(file(:,2))
P_cp3(i)=Co3(1)*temp(i)^3+Co3(2)*temp(i)^2+Co3(3)*temp(i)+Co3(4);
%Predicted Cp for cubic fit
end
%PLOT
plot(temp,cp,'linewidth',2)
%Compare Curve Fit
hold on
plot(temp,P_cp,'linewidth',2,'color','r')
plot(temp,P_cp3,'linewidth',2,'color','g')
axis([0 4000 900 1500])
xlabel('Temprature K')
ylabel('Specific Heat Kj/KmolK')
legend('Given Data','Linear Fit','Cubic Fit')
%Function to calculate coefficients for linear fit
%We used equation of linear fit here to write this code
function Co=LR(x,y)
n=length(x);
xy=x.*y;
a=sum(x);
b=sum(y);
c=sum(xy);
x2=x.^2;
d=sum(x2);
y2=y.^2;
e=sum(y2);
m=(n*c-a*b)/(n*d-a^2);
c=(b-m*a)/n;
Co=[m c];
end
%Function to calculate coefficients for cubic fit
%we used equation for cubic fit here
function Co=LR(x,y)
if (length(x)/3==0)
a=length(x)/3;
else
a=(length(x)-rem(length(x),3))/3;
end
Y=[y(1);y(a);y(2*a);y(3*a)];
term1=[x(1)^3;x(a)^3;x(2*a)^3;x(3*a)^3];
term2=[x(1)^2;x(a)^2;x(2*a)^2;x(3*a)^2];
term3=[x(1);x(a);x(2*a);x(3*a)];
term4=[1;1;1;1];
X=[term1 term2 term3 term4];
Xiv=inv(X);
Co=Xiv*Y;
end
This is the output we are getting from the code.