Project

Curve Fitting using MATLAB - Projects - Skill-Lync

  • AIM: To determine the code to fit a linear and cubic polynomial for the Cp data.

The link for the Cp vs Temperature data file is given below.

Click here to get the Cp vs Temperature data file

  • THEORY : Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc.

The accuracy of the curve fit can be improved by increasing the degree of the polynomial. So, a 'Best fit' can be obtained by increasing the degree of the polynomial.

PERFECT FIT : The perfect fit is achieved when the geometric distances from the given points to the fitting curve are zero . This means that the curve fits perfectly on the points . To get a perfect fit we can increase to a order of the polynomials , this method increases the accuracy and reduces errors .

BEST FIt :The best fit is achieved when the geometric distances from the given points to the fitting curve are minimized, in the least squares sense. Finding the best fit reduces to the minimization of the objective function where denotes the fitting curve.

This will exactly fit four points.

Polynomial curves fitting points generated with a sine function. Red line is a first degree polynomial, green line is second degree, orange line is third degree and blue is fourth degree.

Fitting functions to data points

Most commonly, one fits a function of the form y=f(x).

  • Most commonly, one fits a function of the form y=f(x).
  • The first degree polynomial equation

`y=ax+by=ax+b`

is a line with slope a. A line will connect any two points, so a first degree polynomial equation is an exact fit through any two points with distinct x coordinates.

  • If the order of the equation is increased to a second degree polynomial, the following results:

`y=ax2+bx+cy=ax2+bx+c`

This will exactly fit a simple curve to three points.

  • If the order of the equation is increased to a third degree polynomial, the following is obtained:

`y=ax3+bx2+cx+dy=ax3+bx2+cx+d`

This will exactly fit four points.

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.

  • The sum of squares due to error (SSE)
  • R-square
  • Adjusted R-square
  • Root mean squared error (RMSE)

Sum of Squares Due to Error

This statistic measures the total deviation of the response values from the fit to the response values. It is also called the summed square of residuals and is usually labeled as SSE.

`SSE=∑ni=1wi(yi−ŷi)2SSE=∑i=1nwi(yi-ŷi)2`

A value closer to 0 indicates that the model has a smaller random error component, and that the fit will be more useful for prediction.

R- Square

This statistic measures how successful the fit is in explaining the variation of the data. Put another way, R-square is the square of the correlation between the response values and the predicted response values. It is also called the square of the multiple correlation coefficient and the coefficient of multiple determination.

R-square is defined as the ratio of the sum of squares of the regression (SSR) and the total sum of squares (SST).

`R2=SSRSST=1−SSESSTR2=SSRSST=1-SSESST`

R-square can take on any value between 0 and 1, with a value closer to 1 indicating that a greater proportion of variance is accounted for by the model. For example, an R-square value of 0.8234 means that the fit explains 82.34% of the total variation in the data about the average.

Adjusted R-Square

The adjusted R-square statistic is generally the best indicator of the fit quality when you compare two models that are nested — that is, a series of models each of which adds additional coefficients to the previous model.

`adjusted R-square= 1−SSE(n−1)SST(v)1-SSE(n-1)SST(v)`

The adjusted R-square statistic can take on any value less than or equal to 1, with a value closer to 1 indicating a better fit. Negative values can occur when the model contains terms that do not help to predict the response.

Root Mean Squared Error

This statistic is also known as the fit standard error and the standard error of the regression. It is an estimate of the standard deviation of the random component in the data, and is defined as

`RMSE=s=√MSERMSE=s=MSE`

where MSE is the mean square error or the residual mean square

`MSE=SSEvMSE=SSEv`

Just as with SSE, an MSE value closer to 0 indicates a fit that is more useful for prediction.

matlab code

clear all
close all
clc
%preparing the data
cp_data = load('data');
temperature = cp_data(:,1);
cp = cp_data(:,2);
%Linear fit calculation
%cp = a*t + b
co_effs1 = polyfit(temperature,cp,1);
predicted_cp1 = polyval(co_effs1,temperature);
%Linear fit curve plot
figure(1)
plot (temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp1,'linewidth',3,'color','r')
xlabel('temperature [k]')
ylabel('specific heat [kj/kmol-k]')
legend('original dataset','temperature & predicted_cp1')
title('Linear fit');

%Cubic fit calculation
%cp = a*t^3 + b*t^2 + ct + d
co_effs3 = polyfit(temperature,cp,3);
predicted_cp3 = polyval(co_effs3,temperature);
%compare my curve fit for 3 degree polynomial with the orignal data
%Cubic fit curve plot
figure(2)
plot (temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp3,'linewidth',3,'color','r')
xlabel('temperature [k]')
ylabel('specific heat [kj/kmol-k]')
legend('original dataset','temperature & predicted_cp3')
title('Cubic fit')
%Comparison between linear fit and cubic fit curves
figure(3)
hold on
plot(temperature,cp,'--')
plot(temperature,predicted_cp1,'linewidth',2)
plot(temperature,predicted_cp3,'linewidth',2,'color','g')
legend('Data values','Linear fit','Cubic fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')
%split wise curve fitting
co_effs1 = polyfit(temperature(1:1600),cp(1:1600),2)
predicted_cp1 = polyval(co_effs1,temperature(1:1600));
co_effs3 = polyfit(temperature(1600:3200),cp(1600:3200),3)
predicted_cp3 = polyval(co_effs3,temperature(1600:3200));
%plotting and comparing the original curve and split wise curve 
figure(4)
plot(temperature,cp,'linewidth',3,'color','b')
hold on 
plot(temperature(1:1600),predicted_cp1,'linewidth',3,'color','r')
plot(temperature(1600:3200),predicted_cp3,'linewidth',3,'color','g') 
legend('Data values','Linear fit','Cubic split curve')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp') 
grid on
hold off

code explanation

Data file should be on the same registry as the matlab file registry. The file containing the data(contain temperature and cp values ) is copied to a variable in the Matlab program using 'load' function .then We have the equation for quadratic polynomial or 1 degree polynomial, and cubic polynomial or 3 degree polynomical, which is

%cp = a*t + b

%cp = a*t^3 + b*t^2 + ct + d

then A curve is to fit for 'cp' and 'Temperature' values, so a function 'polyfit' is called and assigned to a new variable. The inputs for the function are (X parameter, Y parameter, Degree of the polynomial) in the same order.The function 'polyfit' returns the coefficients in descending order of power of the polynomial. Another function 'polyval' is called and assigned to a new variable. This function takes (return values of 'polyfit', X parameter) as input in the same order and returns respective 'Y axis' values i.e., cp values.

The curve fit data is compared with original data by plotting the curves to get linear and cubic curve fitting.

Plots are plotted between original data and respective curve fit, Comparision among all the curves are plotted in other figure. Finally,we are labeling the Xasis as Temperature and Y axis as the Specific heat by using MATLAB.And legends are assigned to respective graphs.

A graph is plotted to compare the original data set, linear curve and cubic curve.

Since cubic curve is badly conditioned, it is overcome by using split wise function and making one half of the data quadratic and the other half of the data cubic.

A comparision is made between the original data set and the split wise curve by plotting a graph

plot/output

  • Curve fitting with a linear polynomial:
  • Curve fitting with a cubic polynomial:
  • comparison between linear and cubic polynomial:
  • split wise curve fitting

matlab code for finding the SSR, SST, R_sq, R_sq_adj for linear and cubic Polynomial

clear all
close all
clc
%preparing the data
cp_data = load('data');
temperature = cp_data(:,1);
cp = cp_data(:,2);
%Linear fit calculation
%cp = a*t + b
co_effs1 = polyfit(temperature,cp,1);
predicted_cp1 = polyval(co_effs1,temperature);
%Linear fit curve plot
figure(1)
plot (temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp1,'linewidth',3,'color','r')
xlabel('temperature [k]')
ylabel('specific heat [kj/kmol-k]')
legend('original dataset','temperature & predicted_cp1')
title('Linear fit');

%Cubic fit calculation
%cp = a*t^3 + b*t^2 + ct + d
co_effs3 = polyfit(temperature,cp,3);
predicted_cp3 = polyval(co_effs3,temperature);
%compare my curve fit for 3 degree polynomial with the orignal data
%Cubic fit curve plot
figure(2)
plot (temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp3,'linewidth',3,'color','r')
xlabel('temperature [k]')
ylabel('specific heat [kj/kmol-k]')
legend('original dataset','temperature & predicted_cp3')
title('Cubic fit')
%Comparison between linear fit and cubic fit curves
figure(3)
hold on
plot(temperature,cp,'--')
plot(temperature,predicted_cp1,'linewidth',2)
plot(temperature,predicted_cp3,'linewidth',2,'color','g')
legend('Data values','Linear fit','Cubic fit')
xlabel('Teperature [K]')
ylabel('Cp [kJ/kmol-K]')
title('Temperature vs Cp')
%finding the SSR, SST, R_sq, R_sq_adj for linear Polynomial
Error1 = cp-predicted_cp1;

% Calculating SSE1
sse = 0;
sum1 = 0;
for i=1:length(cp)
  SSE1 = sse+Error1(i)^2;
  SUM1 = sum1+cp(i);
end

n = length(cp)
k = 2

mean = SUM1/n

%Calculating SSR1
ssr= 0;
for j=1:length(predicted_cp1)
  SSR1 = ssr+(predicted_cp1(i)-mean)^2;
end
%Calculating SST1
SST1 = SSR1+SSE1

% Calculating R^2 1
R_sq1 = SSR1/SST1

% Calculating Radj^2 1
R_sq_adj1 = 1-((1-R_sq1)*(n-1)/(n-k-1))
RMSE1 = (SSE1/n)^0.5

%finding the SSR, SST, R_sq, R_sq_adj for cubic Polynomial
Error3 = cp-predicted_cp3;

% Calculating SSE3
sse = 0;
sum3 = 0;
for i=1:length(cp)
  SSE3 = sse+Error3(i)^2;
  SUM3 = sum3+cp(i);
end

n = length(cp)
k = 2

mean = SUM3/n

%Calculating SSR3
ssr = 0;
for j=1:length(predicted_cp1)
  SSR3 = ssr+(predicted_cp1(i)-mean)^2;
end
%Calculating SST3
SST3 = SSR3+SSE3

% Calculating R^2 3
R_sq3 = SSR3/SST3

% Calculating Radj^2 3
R_sq_adj3 = 1-((1-R_sq3)*(n-1)/(n-k-1))
RMSE1 = (SSE3/n)^0.5
Finding SSE, R-Square, RMSE form Cubic Curve
Now we have to calculate mean specific heat value by using SSE (Sum of Squares due to error), R-square, Root Mean Squared Error (RMSE) which is an inbuilt MATLAB Command. Also, to fine the error from cubic curve.
In the given code we have the following details
SSR = sum of squares of regression,
SSE = sum of squares due to error,
SST = sum of squares of the total,
R_sq = R-square is the square of the correlation between the response values and the predicted response values.
R_sq_adj = Adjusted R-square.
RMSE = Root mean squared error.
Using loop command, we calculated the error of cubic polynomial.
Now we have to evaluate the code by using sum and sqrt command which is an inbuilt command in MATLAB. The code will be in the form of

output/reesult:

RESULTS: Higher the value of R square fit better the fit. As the R square value for cubic fit is greater than linear fit, cubic fit has better fittness characteristics. Also, from the graphs we can see that, cubic fit has better resemblance with the original curve.

Question :

1. How to make a curve fit perfectly ?

Curve fit can be made perfect by interpolating the datasets. By interpolation the errors can be minimized and it is also possible to reduce the errors to zero.

2. How to get the best fit ?

The best fit can be obtained by increasing the order of polynomial and also by splitting the curve fits into multiple number of polynomials for different sets of temperature and specific heat values. The best fit can also be chosen by using 4 different types. They are,

  • The sum of squares due to error (SSE).
  • R-square.
  • Adjusted R-square.
  • Root mean squared error (RMSE).

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

The cubic fit can be improved by splitting the curve fits into multiple number of polynomials for different sets of temperature values. It can also be improved by reducing the error between the original dataset and curve fit value.

REFERENCE:

https://in.mathworks.com/help/curvefit/evaluating-goodness-of-fit.html

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.