Project

Code for Curve Fitting using MATLAB

AIM

To perform a curve fitting for the given dataset file and to find the best and perfect fit for the particular dataset using MATLAB.

OBJECTIVE

  1. to write a code to fit a linear and cubic polynomial for the Specific Heat data.
  2. To plot the linear and cubic fir curves along the raw data points.
  3. to study the parameters that are used to measure the fitness characteristics of both curves.

Curve fitting

It is a process of constructing a curve or a mathematical function that possesses close proximity to the original or the real series of the data. By doing curve fitting we can mathematically construct a functional relationship between observed data and parameter values.

It is a statistical technique used for coefficient values of equations that express the value of one (dependent) variable as a function of another (independent variable). It is highly effective in the mathematical modeling of some natural processes. By curve fitting, we can actually study and manipulate the data for different problems and different conditions.

How to fit a curve?

To fit a curve the parameter of the real dataset is a function of undefined constants of ‘nth’ order polynomial.

  • The first-degree polynomial equation,

y=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 coordinates. It is also called an equation for the linear fit.

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

y=ax^2+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=ax^3+bx^2+cx+d

This is also called cubic fit and it will fit the curve in exactly four points.

PARAMETERS USED TO MEASURE THE FITNESS CHARACTERISTICS

After finding the curve that satisfies the given data, we need to check the fitness of the curve or how well the equation satisfies the data points.

This can be done in 4 quantities which help us measure the goodness of fit criteria. They are,

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

MATLAB CODE FOR LINEAR AND CUBIC FIT

%Code for Linear and Cubic curve fit
clear all
close all
clc

%Data Preparation
cp_data = load('data');
temperature  = cp_data(:,1);
cp = cp_data(:,2);

%Curve fit

%Linear Curve Fitting 
%cp = a*T + b
[co_eff1,S,mu] = polyfit(temperature,cp,1);
predicted_cp1 = polyval(co_eff1,temperature,[],mu);

%Cubic Curve Fitting
%cp = a*T^3 + b*T^2 + c*T + d
[co_eff3,S,mu] = polyfit(temperature,cp,3);
predicted_cp3 = polyval(co_eff3,temperature,[],mu);

%Compare curve fit with the original data and plot
figure(1)
plot(temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp1,'linewidth',3,'color','r')
axis([0 4000 900 1400])
xlabel('Temperature [K]')
ylabel('Specific Heat [KJ/Kmol-K]')
legend('Original Data','Linear Curvefit','Location','Southeast')
title('Linear Curve Fit')
grid on

figure(2)
plot(temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp3,'linewidth',3,'color','r')
axis([0 4000 900 1400])
xlabel('Temperature [K]')
ylabel('Specific Heat [KJ/Kmol-K]')
legend('Original Data','Cubic Curvefit','Location','Southeast')
title('Cubic Curve Fit')
grid on

%R^2 method to find the Fitness Characteristics of the curve
M = mean(cp);

for i = 1:length(cp)
    SSR1 = sum((predicted_cp1(i)-M)^2);
    SSE1 = sum((cp(i)-predicted_cp1(i))^2);
end
SST1 = SSR1 + SSE1;
R1 = SSR1/SST1

for i = 1:length(cp)
    SSR3 = sum((predicted_cp3(i)-M)^2);
    SSE3 = sum((cp(i)-predicted_cp3(i))^2);
end
SST3 = SSR3 + SSE3;
R3 = SSR3/SST3

Here in this code,

  1. The code starts with clear all, close all, and clc where
  • the ‘clear all’ command is used to clear the data stored in the workspace.
  • The ‘close all’ command is used to close all plots and figures.
  • ‘clc’ command is used to clear the command window.
  1. Then the data of specific heat is loaded with the ‘load’ command and the ‘Temperature’ as well as the ‘Cp’ array is defined.
  2. Then curve fitting is performed by using two functions,
  • polyfit – p = polyfit (x,y,n)returns the coefficients for a polynomial p(x) of degree ‘n’ that is the best fit (in a least-squares sense) for the data in y. The coefficients in p are in descending powers, and the length of p is n+1. Here, the value on ‘n’ is 1 for linear and 3 for cubic, ‘x’ is ‘temperature’, and ‘y’ is 'cp' data. So [co_eff,S,mu] = polyfit (x,y,n) also returns mu, which is a two-element vector with centering and scaling values. mu(1) is mean(x), and mu(2) is std(x). Using these values, polyfit centers ‘x’ at zero and scales it to have a unit standard deviation. This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.
  • polyval – polyval (co_eff, temperature) returns the value of a polynomial of degree ‘n’ evaluated at ‘temperature’. The input argument ‘co_eff’ is a vector whose elements are the coefficients in descending powers of the polynomial to be evaluated. ‘polyval’ evaluates ‘co_eff’ at each element of ‘temperature’. Here polyval (co_eff, temperature,[ ], mu) is used for centering and scaling parameters of ‘mu’ which is computed by polyfit.
  1. Then the curve fit data is compared with the original data by plotting the curves to get linear and cubic curve fitting. The axis is shifted by using the ‘axis’ command and the legend is provided for the plot.
  2. Here we are using the R-square method to evaluate the Fitness characteristics of linear and cubic curves respectively, as mentioned above.
  3. M = mean(cp)returns the mean of the elements of ‘cp’ along the first array dimension.
  4. The values of SSR, SSE, SST, and R-square for linear and cubic polynomial is calculated in a ‘for’ loop and the values of R-square are to be displayed on the command window.

Values from Workspace :

Linear Curve fit

RESULTS for Linear and Cubic fit :

The value of R-square for Linear fit is found to be 0.9592 and that of Cubic fit is found to be 0.9907. As we know that the higher the value of R-square, the better the fitness characteristics. Here the value of Cubic fit is higher than the value of Linear fit. So cubic curve fit has better fitness characteristics than linear curve fit. Also from both the graphs, we can see that cubic curve fit has a better resemblance to the original curve compared to linear curve fit.

Best fit and Perfect fit:

Best fit – Best fit simply means that the differences between the actual measured values and the values predicted by the model equation are minimized. It does not mean the ‘Perfect Fit'. In most cases, a least squares best fit does not go through all the points in the data set.

Perfect fit – Perfect fit means the curve should fit the original curve without showing any errors or residual values. In other words, if the R-square value of the curve is exactly 1.0000, then the curve is said to be a Perfect fit. A perfect fit can be the best fit but the best fit cannot be a Perfect fit. This is the basic difference between Best fit and Perfect fit.

How to get the Best fit?

  • To get the best fit, we should increase the degree of a polynomial of the equation and reduce the residual errors.
  • By doing so, we can get values of R-square close to 1.
  • As stated in the results, the best curve fit from the above program is the Cubic curve fit as its value of R-square = 0.9907

Program to split the data and plot curve fitting-

%Program to Split the data and plot the curve.
clear all
close all
clc

%Data Preparation
cp_data = load('data');
temperature  = cp_data(:,1);
cp = cp_data(:,2);

%Data Splitting
temperature1  = cp_data(1:400,1);
cp1 = cp_data(1:400,2);

temperature2  = cp_data(401:800,1);
cp2 = cp_data(401:800,2);

temperature3  = cp_data(801:1200,1);
cp3 = cp_data(801:1200,2);

temperature4  = cp_data(1201:1600,1);
cp4 = cp_data(1201:1600,2);

temperature5  = cp_data(1601:2000,1);
cp5 = cp_data(1601:2000,2);

temperature6  = cp_data(2001:2400,1);
cp6 = cp_data(2001:2400,2);

temperature7  = cp_data(2401:2800,1);
cp7 = cp_data(2401:2800,2);

temperature8  = cp_data(2801:3200,1);
cp8 = cp_data(2801:3200,2);

%Cubic Fit with Centering and Scaling
[co_eff1,S,mu] = polyfit(temperature1,cp1,3);
predicted_cp1 = polyval(co_eff1,temperature1,[],mu);

[co_eff2,S,mu] = polyfit(temperature2,cp2,3);
predicted_cp2 = polyval(co_eff2,temperature2,[],mu);

[co_eff3,S,mu] = polyfit(temperature3,cp3,3);
predicted_cp3 = polyval(co_eff3,temperature3,[],mu);

[co_eff4,S,mu] = polyfit(temperature4,cp4,3);
predicted_cp4 = polyval(co_eff4,temperature4,[],mu);

[co_eff5,S,mu] = polyfit(temperature5,cp5,3);
predicted_cp5 = polyval(co_eff5,temperature5,[],mu);

[co_eff6,S,mu] = polyfit(temperature6,cp6,3);
predicted_cp6 = polyval(co_eff6,temperature6,[],mu);

[co_eff7,S,mu] = polyfit(temperature7,cp7,3);
predicted_cp7 = polyval(co_eff7,temperature7,[],mu);

[co_eff8,S,mu] = polyfit(temperature8,cp8,3);
predicted_cp8 = polyval(co_eff8,temperature8,[],mu);

%Compare curve fit with the original data
plot(temperature,cp,'linewidth',3,'color','b')
hold on
plot(temperature1,predicted_cp1,'linewidth',3,'color','r')
hold on
plot(temperature2,predicted_cp2,'linewidth',3,'color','r')
hold on
plot(temperature3,predicted_cp3,'linewidth',3,'color','r')
hold on
plot(temperature4,predicted_cp4,'linewidth',3,'color','r')
hold on
plot(temperature5,predicted_cp5,'linewidth',3,'color','r')
hold on
plot(temperature6,predicted_cp6,'linewidth',3,'color','r')
hold on
plot(temperature7,predicted_cp7,'linewidth',3,'color','r')
hold on
plot(temperature8,predicted_cp8,'linewidth',3,'color','r')
axis([0 4000 900 1400])
xlabel('Temperature [K]')
ylabel('Specific Heat [KJ/Kmol-K]')
legend('Original Data','Splitwise data Curvefit','Location','Southeast')
title('Cubic Curve Fit with Splitted Data')
grid on

RESULT

From the above curve plot, we can say that the curve for ‘Original data’ is not visible as the ‘Splitwise data Curvefit’ has perfectly fitted the original curve.

CONCLUSION :

  • From this report, we can state that there are different ways to perform Curve Fitting.
  • We need to have high-order polynomial equations to achieve the best fit. The higher the order of the polynomial, the better is the curve.
  • The splitwise method helps in getting a perfect fit for the original curve. The main factor in splitting the data is the “number of splits’. More the number of splits, the better the output curve.
  • With the help of these methods, we can predict and manipulate the different problems and conditions for future study.

*No major errors were thrown in the command window while coding.

REFERENCES :

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.