CURVE FITTING USING MATLAB
AIM : To curve fit the given temperature and specific heat data
OBJECTIVES :
- To plot the given data and its curve fit
- To evaluate the errors of curve fit
- To measure the goodness of fit
CODE :
close all
clc
%Loading the data
input_data=load('data');
%Dividing the data into two sets of varaibles
temp1 = input_data(1:1700,1);
cp1 = input_data(1:1700,2);
temp2 = input_data(1701:3200,1);
cp2 = input_data(1701:3200,2);
%Using one set of variables for whole data
temp = input_data(:,1);
cp = input_data(:,2);
%Curve fitting
%Fitting the divided data
coeff1 = polyfit(temp1,cp1,1);
fitted_cp1 = polyval(coeff1,temp1);
coeff2 = polyfit(temp2,cp2,1);
fitted_cp2 = polyval(coeff2,temp2);
%Fitting the whole data
coeff3 = polyfit(temp,cp,3);
fitted_cp3 = polyval(coeff3,temp);
%Compare original curve to fitted curve
%comparing by divided data
figure(1)
hold all
plot(temp1,cp1,"linewidth",3,'color','r')
plot(temp2,cp2,"linewidth",3,'color','b')
plot(temp1,fitted_cp1,"linewidth",3,'color','k')
plot(temp2,fitted_cp2,"linewidth",3,'color','m')
title("Comparing the divided data");
xlabel("Temparature");
ylabel("Specific heat(Cp)");
legend("first data set","second data set","first fitted set","second fitted set");
hold off
%Comparing the whole data
figure(2)
plot(temp,cp,"linewidth",3)
hold on
plot(temp,fitted_cp3,"linewidth",3)
title("Comparing the Whole data using cubic polynomial");
xlabel("Temparature");
ylabel("Specific heat(Cp)");
legend("Original","Fitted");
%Goodness of fit for cubic polynomial
M=mean(cp);
%r^2 of cubic fit
for i=1:length(cp)
%sum of squared errors
E_cubic=sum((cp(i)-fitted_cp3(i))^2);
%sum of squares of regression
R_cubic = sum((fitted_cp3(i)-M)^2);
end
%Total sum of squares
T_cubic=E_cubic+R_cubic;
%square calculator
sq_cubic=R_cubic/T_cubic
%Goodness of fit for square polynomial
M1=mean(cp1);
M2=mean(cp2);
%r^2 of square fit of first set
for i=1:length(cp1)
%sum of squared errors
E_sq1=sum((cp1(i)-fitted_cp1(i))^2);
%sum of squares of regression
R_sq1 = sum((fitted_cp1(i)-M1)^2);
end
%r^2 of square fit of second set
for i=1:length(cp2)
%sum of squared errors
E_sq2=sum((cp2(i)-fitted_cp2(i))^2);
%sum of squares of regression
R_sq2 = sum((fitted_cp2(i)-M2)^2);
end
%Total sum of squares
T_cubic=E_cubic+R_cubic;
%square calculator
sq_cubic=R_cubic/T_cubic
%Total sum of squares
T_sq1=E_sq1+R_sq1;
%square calculator
sq_sq1=R_sq1/T_sq1
%Total sum of squares
T_sq2=E_sq2+R_sq2;
%square calculator
sq_sq2=R_sq2/T_sq2
cftool(temp,cp)
OUTPUT :






ANSWERS FOR QUESTIONS :
- To get a perfect curve fit increase the polynomial order
- To get the best fit polynomial of order 8 can be used as we get R_square=1
- We can improve the quality of cubic fit by normalizing the cdate data