Project

CURVE FITTTING

AIM : To write a code to fit a linear and cubic polynomial for the Cp data

OBJECTIVE : To Plot the linear and cubic fit curves along with the raw data points and , calculate the goodness of fit using different parameters and different ways to improve the fit.

EXPLANATION : Curve fitting is the process of constructing a curve or mathematical function that best fits the data points, possibly subjected to constraints. It helps us in understanding the type of relationship between the set of data and helps in predicting the unknown values.

The goodness of fit of a statistical data determines how well it fits a set of observation. Measures of goodness of fit typically summarize the discrepancy between observed values and the values expected under the model in question. There are four methods to quantify the goodness of fit. They are

The sum of squares due to error (SSE)

  • R-square
  • Adjusted R-square
  • Root mean squared error (RMSE)

Answers to asked questions:

1. How to make curve fit perfectly?

1.There can be two ways through which we can minimize our error 1. By increasing the order of the polynomial until the error reduces.

2. Another way to reduce error was dividing the temperature values in smaller divisions

2.How to get the best fit?

Upon finding a curve which satisfies the data points there are 4 quantities which help us measure the goodness of fit criteria or how well the equation is a representing the datapoints. There are,

The sum of squares due to error (SSE)

  1. R-square
  2. Adjusted R-square
  3. Root mean squared error (RMSE)

3. What could be done to improve the cubic fit?

We can divide the temperature values into smaller intervals.

PROGRAM : It is the code for curve fitting and it shows comparison for linear , quadratic, cubic and fourth order curve fitting

%Code to perform curve fitting for the cp vs temp data file
clear all
close all
clc

%Loading Data from a saved file
cp_data=load ('data');
temperature=cp_data(:,1);%Allocating data to temp which is the first column of the data
cp=cp_data(:,2);%Allocating data to cp second column

% Linear Polynomial
coeff1=polyfit(temperature,cp,1);
newcp1=polyval(coeff1,temperature);

%Quadratic polynomial
coeff2=polyfit(temperature,cp,2);
newcp2=polyval(coeff2,temperature);


%Cubic polynomial
coeff3=polyfit(temperature,cp,3);
newcp3=polyval(coeff3,temperature);

%fourth order fit
coeff4=polyfit(temperature,cp,4);
newcp4=polyval(coeff4,temperature);

%plotting
%Linear fit curve plot
figure(1)
hold on
plot(temperature,cp,'linewidth',3)
plot(temperature,newcp1,'linewidth',3)
legend('Data values','Linear fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')


%Quadratic curve plot
figure(2)
hold on
plot(temperature,cp,'linewidth',3)
plot(temperature,newcp2,'linewidth',3,'color','r')
legend('Data values','quadratic fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')

%Cubic fit curve plot
figure(3)
hold on
plot(temperature,cp,'linewidth',3)
plot(temperature,newcp3,'linewidth',3,'color','g')
legend('Data values','Cubic fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')

%4th order curve plot
figure(4)
hold on
plot(temperature,cp,'linewidth',3)
plot(temperature,newcp4,'linewidth',3,'color','r')
legend('Data values','4th order fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')



%Comparison between linear fit ,quadratic fit, cubic fit ,4th order polynomial curves
figure(5)
hold on
plot(temperature,cp,'linewidth',3)
plot(temperature,newcp1,'linewidth',3)
plot(temperature,newcp2,'linewidth',3,'color','g')
plot(temperature,newcp3,'linewidth',3,'color','r')
plot(temperature,newcp4,'linewidth',3,'color','b')

legend('Data values','Linear fit','Cubic fit','quadratic fit','4th order','location','northwest')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')

PROCEDURE :

  1. Data file should be on the same registry as the matlab file registry.
  2. Load command is used to load these values.
  3. X values are stored in temperature variable, Y values are stored in cp variable.
  4. For linear fit, we need to find the co efficients. To find those, we use polyfit command and are stored in coeff1 variable.
  5. Using these co efficients, we find new cp values for linear fit using polyval command and are stored in newcp1 variable.
  6. The same procedure is followed for quadratic , cubic fit and fourth order.
  7. Plot is made between temperature and cp for all three cases using plot command.
  8. Appropriate title, legend, and axes label are given for graphs

OUTPUT :

PROGRAM 2 : This code shows reduction of error in each case

%Code to perform curve fitting for the cp vs temp data file
clear all
close all
clc

%Loading Data from a saved file 
cp_data = load('data');
temp = cp_data(:,1); %Allocating data to temp which is the first column of the data
cp = cp_data(:,2); %Allocating data to cp second column

%Linear Polynomial
co_eff1 = polyfit(temp,cp,1);
predicted_cp1 = polyval(co_eff1,temp);

%Quadratic Polynomial  
co_eff2 = polyfit(temp,cp,2);
predicted_cp2 = polyval(co_eff2,temp);

%cp = Cubic Polynomial
co_eff3 = polyfit(temp,cp,3);
predicted_cp3 = polyval(co_eff3,temp);

%cp =Polynomial of 4th order
co_eff4 = polyfit(temp,cp,4);
predicted_cp4 = polyval(co_eff4,temp);


%Error in data
Error_linear = cp - predicted_cp1;
Error_quadratic = cp - predicted_cp2;
Error_cubic = cp - predicted_cp3;
Error_fourth =cp - predicted_cp4
%Percentage Error
per_errorlin =abs(Error_linear./cp)*100;
per_errorquad = abs(Error_quadratic./cp)*100;
per_errorcub = abs(Error_cubic./cp)*100;
per_errorfour = abs(Error_fourth./cp)*100;

% Plotting
figure(1)
plot(temp,cp,'linewidth',3);
hold on
plot(temp,predicted_cp1,'linewidth',3,'color','r');
xlabel('Temperature in [K]');
ylabel('Specific Heat in [KJ/Kmol-K]');
legend('Original Dataset','Linear Curvefit');

figure(2)
plot(temp,cp,'linewidth',3);
hold on
plot(temp,predicted_cp2,'linewidth',3,'color','r');
xlabel('Temperature [K]');
ylabel('Specific Heat [KJ/Kmol-K]');
legend('Original Dataset','Quadratic Curvefit');

figure(3)
plot(temp,cp,'linewidth',3);
hold on
plot(temp,predicted_cp3,'linewidth',3,'color','r');
xlabel('Temperature [K]');
ylabel('Specific Heat [KJ/Kmol-K]');
legend('Original Dataset','Cubic Curvefit')

figure(4)
plot(temp,cp,'linewidth',3);
hold on
plot(temp,predicted_cp4,'linewidth',3,'color','r');
xlabel('Temperature [K]');
ylabel('Specific Heat  [KJ/Kmol-K]');
legend('Original Dataset','Fourth order Curvefit')
% Table
T1 = table(cp,predicted_cp1,Error_linear,per_errorlin);
T2 = table(cp,predicted_cp2,Error_quadratic,per_errorquad);
T3 = table(cp,predicted_cp3,Error_cubic,per_errorcub);
T4 = table(cp,predicted_cp4,Error_cubic,per_errorfour);

%to reduce the error further more, dividing the data into 6 divisions

%dividion 1 (300-900)

cp2=cp(1:600);
temp2=temp(1:600);

co_eff2=polyfit(temp2,cp2,1);
pred_cp2=polyval(co_eff2,temp2);

figure(5)
hold on
plot(temp2,cp2,'linewidth',3)
plot(temp2,pred_cp2,'linewidth',3,'color','r')
xlabel('TEMPERATURE') 
ylabel('SPECIFIC HEAT')
legend('orginal value2','predicted value 2')

error1=(cp-predicted_cp1);
err1=max(error1);
disp("The error corresponding to no division of data")
disp(err1)

error2=(cp2-pred_cp2);
err2=max(error2);
disp("The error corresponding to division of data")
disp(err2)

PROEDURE :

  1. To reduce the error firstly i tried to fit in linear polynomial on the Specific heat and Temperature data and in this case the least squared error was quite high.
  2. To reduce the error i subsquently tried with Quadratic and Cubic interpolation curves and observed that the error in case of cubic interpolation was in the acceptable range and it provided a good approximation of the relationship between Specific heat and temperature.
  3. Just to understand how increasing the Order of polynomial effects the error value i tried with Fourth order polynomial and in this case the error was even lesser than cubic interpolation.
  4. Furthermore i divided the data into 6 divisions to understand how it effects the error and fitted in linear polynomial curve . On doing this i observed that if we divide the data into smaller divisions then the error value for each polynomial fit reduces significantly. (figure5)

OUTPUT :

figure : 5

Using Curve Fitting Tool box :

Value for the R-square came to be 0.9249 which is not a good fit. A good fit has an R-square value of more than 0.95.

Value of R-square is 0.9812 which indicates it as a bit good fit.

Value of R-square is 0.9967 which indicates it as a good fit than quadratic fit

Value of R-square is 0.9996 which indicates it as a good fit.

But in the results column, it mentions that the equation is badly conditioned.

Now that the equation is not proper we can divide the data set into four parts and fit a curve using Matlab code:

% Curve fitting by breaking the given data set to multiple dataset
clear all
close all
clc

%loading of Cp vs Temperature data
cp_data = load('data'); 
temperature = cp_data(:,1);%Allocating data to temp which is the first column of the data
cp = cp_data(:,2);%Allocating data to cp second column

%seperation of dataset into four equal parts
cp01 = cp([1:800]);%Cp values for temps from 0 to 800
temperature01 = temperature([1:800]);
cp02 = cp([801:1600]);%Cp values for temps from 801 to 1600
temperature02 = temperature([801:1600]);
cp03 = cp([1601:2400]);%Cp values for temps from 1601 to 2400
temperature03 = temperature([1601:2400]);
cp04 = cp([2401:3200]);%Cp values for temps from 2401 to 3200
temperature04 = temperature([2401:3200]);

plot(temperature,cp,'linewidth',3,'color','r')
hold on
%predicting CP values using fit function for first half
[predict_cp1,GOF1] = fit(temperature01,cp01,'poly2')
plot(predict_cp1,'b')
%predicting CP values using fit function for second half
[predict_cp2,GOF2] = fit(temperature02,cp02,'poly2')
plot(predict_cp2,'r')
%predicting CP values using fit function for third half
[predict_cp3,GOF3] = fit(temperature03,cp03,'poly3')
plot(predict_cp3,'g')
%predicting CP values using fit function for fourth half
[predict_cp4,GOF4] = fit(temperature04,cp04,'poly4')
plot(predict_cp4,'g')



hold off
title('Curvefitting of Temperature vs Specific heat')
xlabel('Temperature (Kelvin)')
ylabel('Specific heat [KJ/KMOL-K]')
legend('original Specific heat data','Trend of CP for temp 1-800' , 'Trend of CP for temp for 801-1600 ','Trend of CP for temp 1601-2400','Trend of CP for temp 2401-3200','location','northwest')

PROCEDURE :

1) Data set has been divided into four equal halves from 1 to 800 and 801 to 1600 and 1601 to 2400 and 2401 to 3200

2) Using fit function CP values and goodness of fit has been found out for four equal halves

3) Curves have been plotted for four sets

OUTPUT :

GOF1 = 

  struct with fields:

           sse: 4.7121e+03
       rsquare: 0.9983
           dfe: 797
    adjrsquare: 0.9983
          rmse: 2.4315


GOF2 = 

  struct with fields:

           sse: 33.5926
       rsquare: 0.9999
           dfe: 797
    adjrsquare: 0.9999
          rmse: 0.2053


GOF3 = 

  struct with fields:

           sse: 0.1012
       rsquare: 1.0000
           dfe: 796
    adjrsquare: 1.0000
          rmse: 0.0113


GOF4 = 

  struct with fields:

           sse: 1.3881e-22
       rsquare: 1
           dfe: 795
    adjrsquare: 1
          rmse: 4.1786e-13

All the values are greater than 0.95 indicates that it is a good fit.

CONCLUSION :Therefore we can say that we can achieve a good fit either by increasing the degree of polynomial or by dividing the total data set into subsets.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.