Polynomial Curve Fitting Using MATLAB Program
Objective: To program and plot the curve fitting for cp data of Oxygen and also measure the fitness for the curves and obtain the Perfect Fit using MATLAB.
Curve Fitting
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. It is highly effective in the mathematical modeling of some natural processes.
The first-degree polynomial equation
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:
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:
This will exactly fit four points.
Curve fitting examines the relationship between one or more predictors (independent variables) and a response variable (dependent variable), with the goal of defining a "best fit" model of the relationship.
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 higher order of the polynomials, this method increases the precession 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 the minimization of the objective function
Upon finding a curve that satisfies the data points there are 4 quantities that help us measure the goodness of fit criteria or how well the equation is representing the data points. There are,
- 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 = sum_(i=1)^n(Y(i)-f(x(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 quantity that 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.
What that means in layman's terms is that the higher the value of R-square the better the fit, the lower it is the lousier the fit, R-square ranges from a value of 0 to 1
- 0 for the worst possible fit for the data set
- 1 for the best possible fit for the data set
The value of R-square can be calculated using the following formula,
`R^2=(SSR)/(SST)`
where
`SSR = sum_(i=1)^n(f(x(i))-Mean)^2`
in Simple Terms SSR = sum((Predicted value-mean(original value)).^2
`SSE = sum_(i=1)^n(Y(i)-f(x(i)))^2`
in Simple Terms SSE = sum((Original value-Predicted Value).^2)
`SST=SSR+SSE`
- Adjusted R-square
Adjusted R-square is a normalizing variation of R-square which neglects the variation of R-square due to insignificant independent variables. for, y=f(x1,x2,x3,...,xn)y=f(x1,x2,x3,...,xn), here, x1,x2,...,xnx1,x2,...,xn are the independent variables and yy is the dependent variable.
- If value of x(i)x(i) contributes to the output yy, then x(i)x(i) is a significant dependent variable
- If the value of x(i)x(i) does not contribute to the output yy, then x(i)x(i) is an insignificant dependent variable
Adjusted R-square disregards these infinitesimally small increments to R-square, and only considers the variables which actually contribute to the output of the system in a drastic way.
where,
n - the number of datapoints
k - the number of independent variables
- RMSE (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 = sqrt((SSE)/n)`
where n is the total number of data points available.
typically if R-square is greater than 0.95 the fit is assumed to be Best. And if R-square is 1 the Fir is assumed to be perfect.
MATLAB CODE : CURVE FITTING USING LINEAR PLOYNOMINAL METHOD
clear all ;
close all ;
clc;
%Loading Data File
Cp_data = load('data');
Temp = Cp_data(:,1);
Cp = Cp_data(:,2);
%Linear Polynomial Curve Fitting
Coefficient_L = polyfit(Temp,Cp,1);
Predicted_Cp_L = polyval(Coefficient_L,Temp);
%Error Calcualtion
Error = (Cp-Predicted_Cp_L);
SSE = sum(Error.^2);
SSR = sum((Predicted_Cp_L-mean(Cp)).^2);
SST = SSR+SSE
R_square = SSR/SST;
%Plotting
plot(Temp,Cp,'linewidth',3,'color','g');
hold on
plot(Temp,Predicted_Cp_L,'linewidth',3,'color','r');
hold off
xlabel('Temp[K]');
ylabel('Specific_heat[KJ/Kmol_K]');
legend('Original data','Linear Curvefit data');
%printing R square in the graph
str = {'R sqaure =' R_square };
text(500,1300,str,'Fontsize',10,'color','b');
Explanation:
First clear all, close all, clc command is used to clear all the data from the workspace and command window and close all this figure which is open its always good to start with these three commands before starting a code
The percent sign is most commonly used to indicate non-executable text within the body of a program. those non-executable texts are for better understanding the code
Using load Command Data file is imported in the matrix form Temperature, Specific Heat (Cp)
polyfit Given two vectors x and y, the command a = polyfit(x,y,n) used to get output coefficients using input as (x-temp, y-Specific_heat, n-degree of polynomial). The degree of the polynomial is set to 1 to get a linear polynomial.
polyval Given a data vector x and the coefficients of a polynomial in a row vector a the command y = polyval(a,x)
To measure the goodness of fit, the R-square statistical method is Used
The Predicted values and actual values are plotted against temperature
R square value is printed on the plot
The obtained R-square value is 0.9248 showing that its a good fit but not a perfect fit.
Graph
MATLAB CODE : CURVE FITTING USING CUBIC PLOYNOMINAL METHOD
clear all ;
close all ;
clc;
%Loading Data File
Cp_data = load('data');
Temp = Cp_data(:,1);
Cp = Cp_data(:,2);
%Cubic Polynomial Curve Fitting
Coefficient_C = polyfit(Temp,Cp,3);
Predicted_Cp_C = polyval(Coefficient_C,Temp);
%Error Calcualtion(R-sqaure method)
Error = (Cp-Predicted_Cp_C);
SSE = sum(Error.^2);
SSR = sum((Predicted_Cp_C-mean(Cp)).^2);
SST = SSR+SSE
R_square = SSR/SST;
%Plotting
plot(Temp,Cp,'linewidth',3,'color','g');
hold on
plot(Temp,Predicted_Cp_C,'linewidth',3,'color','r');
hold off
xlabel('Temp[K]');
ylabel('Specific_heat[KJ/Kmol_K]');
legend('Original data','Cubic Curvefit data');
%printing thermal efficiency in the graph
str = {'R sqaure =' R_square };
text(500,1300,str,'Fontsize',10,'color','b');
polyfit Given two vectors x and y, the command a = polyfit(x,y,n) used to get output coefficients using input as (x-temp, y-Specific_heat, n-degree of the polynomial). The degree of the polynomial is set to 3 to get a Cubic polynomial.
polyval Given a data vector x and the coefficients of a polynomial in a row vector a the command y = polyval(a,x)
To measure the goodness of fit, the R-square statistical method is Used
The Predicted values and actual values are plotted against temperature
R square value is printed on the plot
The obtained R-square value is 0.9967 this shows the curve is the best fit but not the perfect fit, Which is far better than the Linear Polynomial method but, the program shows a warning - 'Polynomial is badly conditioned'. "Badly conditioned" means that the solution of the system of linear equations critically depends on rounding errors due to the limited precision.
Graph
MATLAB CODE : CURVE FITTING USING SPLITWISE LINEAR PLOYNOMINAL METHOD
Even though the previous method closely represents the original dataset it is now however not perfect, hence we are now using the method of splitting the plot into 10 equal portions and then combine them together by using the Splitwise method.
clear all ;
close all ;
clc;
%Loading Data File
Cp_data = load('data');
Temp = Cp_data(:,1);
Cp = Cp_data(:,2);
%splitwise method:
x=10; % no.of splits in the data point
for i = 1:x
if i==1
a = 1;
b = (3200/x);
b = round(b);
Cp_split = Cp(a:b);
Temp_split = Temp(a:b);
else
a = (3200/x)*(i-1) + 1;
a=round(a);
b = a + (3200/x) - 1;
b=round(b);
Cp_split = Cp(a:b);
Temp_split = Temp(a:b);
end
Coefficient_Split = polyfit(Temp_split,Cp_split,1);
Predicted_Cp_Split(a:b) = polyval(Coefficient_Split,Temp_split);
end
%converting row to the column matrix
Predicted_Cp = Predicted_Cp_Split' ;
%Error Calcualtion(R-sqaure method)
Error = (Cp-Predicted_Cp);
SSE = sum(Error.^2);
SSR = sum((Predicted_Cp-mean(Cp)).^2);
SST = SSR+SSE
R_square = SSR/SST;
plot(Temp,Cp,'lineWidth',2,'color','b');
hold on
plot(Temp,Predicted_Cp,'lineWidth',2,'color','r');
hold off
xlabel('Temp[K]');
ylabel('Specific_heat[KJ/Kmol_K]');
legend('Original data','Cubic Splitwise curvefit data');
%printing thermal efficiency in the graph
str = {'R sqaure =' R_square };
text(500,1300,str,'Fontsize',10,'color','b');
Explanation:
First clear all, close all, clc command is used to clear all the data from the workspace and command window and close all this figure which is open its always good to start with these three commands before starting a code
The percent sign is most commonly used to indicate non-executable text within the body of a program. those non-executable texts are for better understanding the code
Using load Command Data file is imported in the matrix form Temperature, Specific Heat (Cp)
polyfit Given two vectors x and y, the command a = polyfit(x,y,n) used to get output coefficients using input as (x-temp, y-Specific_heat, n-degree of the polynomial). The degree of the polynomial is set to 1 to get a linear polynomial.
polyval Given a data vector x and the coefficients of a polynomial in a row vector a, the command y = polyval(a,x)
x is no of the split point in the dataset, so the loop runs for 10times with different range of datapoint from 0 to 3200
eg for i= 1: 10 for the first-run i=1 which satisfies the 'if' condition so a=1: b= 3200/10=320 so polyfit creates a new set of coefficients for the datapoint from 1:320 for both Temperature and Cp.
In second-run i =2 which doesn't satisfy the if condition so else condition will be executed i.e a=((3200/10)2-1)+1 = 321 b= 321+(3200/10)-1= 640 so polyfit creates a other set of coefficients for the datapoint from 321:6240for both Temperature and Cp.
This iteration takes places 10 times they simply divide the datapoint in 10 equal portions and creates 10 set of values for 10 portions and combine them together
To measure the goodness of fit, the R-square statistical method is Used
The predicted values and actual values are plotted against temperature
The obtained R-square value is 0.9993 , the curve is assumed to be a perfect fit but still, there is a slight deviation since we used Linear polynomial method .
Graph
MATLAB CODE: CURVE FITTING USING SPLITWISE CUBIC PLOYNOMINAL METHOD
The Splitwise Linear Polynomial method has the r-square very close to 1 But there was a slight deviation in the initial stage So, we are going to use Splitwise Cubic Ploynominal method, The process the same but we are going change the degree of the polynomial from 1 to 3.
clear all ;
close all ;
clc;
%Loading Data File
Cp_data = load('data');
Temp = Cp_data(:,1);
Cp = Cp_data(:,2);
%splitwise method:
x=10; % no.of splits in the data point
for i = 1:x
if i==1
a = 1;
b = (3200/x);
b = round(b);
Cp_split = Cp(a:b);
Temp_split = Temp(a:b);
else
a = (3200/x)*(i-1) + 1;
a=round(a);
b = a + (3200/x) - 1;
b=round(b);
Cp_split = Cp(a:b);
Temp_split = Temp(a:b);
end
Coefficient_Split = polyfit(Temp_split,Cp_split,3);
Predicted_Cp_Split(a:b) = polyval(Coefficient_Split,Temp_split);
end
%converting row to column matrix
Predicted_Cp = Predicted_Cp_Split' ;
%Error Calcualtion(R-sqaure method)
Error = (Cp-Predicted_Cp);
SSE = sum(Error.^2);
SSR = sum((Predicted_Cp-mean(Cp)).^2);
SST = SSR+SSE
R_square = SSR/SST;
plot(Temp,Cp,'lineWidth',2,'color','b');
hold on
plot(Temp,Predicted_Cp,'lineWidth',2,'color','r');
hold off
xlabel('Temp[K]');
ylabel('Specific_heat[KJ/Kmol_K]');
legend('Original data','Cubic Splitwise curvefit data');
%printing thermal efficiency in the graph
str = {'R sqaure =' R_square };
text(500,1300,str,'Fontsize',10,'color','b');
polyfit Given two vectors x and y, the command a = polyfit(x,y,n) used to get output coefficients using input as (x-temp, y-Specific_heat, n-degree of the polynomial). The degree of the polynomial is set to 3 to get a Cubic polynomial.
polyval Given a data vector x and the coefficients of a polynomial in a row vector a, the command y = polyval(a,x)
x is no of the split point in the dataset, so the loop runs for 10times with different range of datapoint from 0 to 3200
This iteration takes places 10 times they simply divide the datapoint in 10 equal portions and creates 10 set of values for 10 portions and combine them together
To measure the goodness of fit, the R-square statistical method is Used
The predicted values and actual values are plotted against temperature
The obtained R-square value is 1 This is the 'Perfect Fit'
Graph
Conclusion:
By Just Increasing the degree of Polynomial we cant get the accurate fit of the curve. But the physical data of the curve might go wrong so, that is not recommended.
Splitwise method is an efficient way to obtain the perfect fit without increasing the degree of the polynomial.
The method like R-square can be used to measure and evaluate the goodness of fit.
Reference ;
https://skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860
https://en.wikipedia.org/wiki/Polynomial_and_rational_function_modeling
https://en.wikipedia.org/wiki/Curve_fitting
https://in.mathworks.com/help/curvefit/evaluate-a-curve-fit.html