Project

Curve Fittings for Cp to fit Linear and Cubic Polynomial in MATLAB

Curve fitting:


Curve fitting is the process of constructing a curve, or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. Curve fitting can involve either interpolation, where an exact fit to the data is required, or smoothing, in which a "smooth" function is constructed that approximately fits the data. A related topic is regression analysis, which focuses more on questions of statistical inference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables.Extrapolation refers to the use of a fitted curve beyond the range of the observed data, and is subject to a degree of uncertainty since it may reflect the method used to construct the curve as much as it reflects the observed data.

How to make curve fittings:

1. Fitting lines and polynomial functions to data points
2. Fitting other functions to data points

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.

A more general statement would be to say it will exactly fit four constraints. Each constraint can be a point, angle, or curvature (which is the reciprocal of the radius of an osculating circle). Angle and curvature constraints are most often added to the ends of a curve, and in such cases are called end conditions.

Algebraic fit versus geometric fit for curves:


For algebraic analysis of data, "fitting" usually means trying to find the curve that minimizes the vertical (y-axis) displacement of a point from the curve (e.g., ordinary least squares). However, for graphical and image applications geometric fitting seeks to provide the best visual fit; which usually means trying to minimize the orthogonal distance to the curve (e.g., total least squares), or to otherwise include both axes of displacement of a point from the curve. Geometric fits are not popular because they usually require non-linear and/or iterative calculations, although they have the advantage of a more aesthetic and geometrically accurate result.

Smoothing:

In statistics and image processing, to smooth a data set is to create an approximating function that attempts to capture important patterns in the data, while leaving out noise or other fine-scale structures/rapid phenomena. In smoothing, the data points of a signal are modified so individual points higher than the adjacent points (presumably because of noise) are reduced, and points that are lower than the adjacent points are increased leading to a smoother signal. Smoothing may be used in two important ways that can aid in data analysis by being able to extract more information from the data as long as the assumption of smoothing is reasonable and by being able to provide analyses that are both flexible and robust. Many different algorithms are used in smoothing.

Smoothing may be distinguished from the related and partially overlapping concept of curve fitting in the following ways:

1. Curve fitting often involves the use of an explicit function form for the result, whereas the immediate results from smoothing are the "smoothed" values with no later use made of a functional form if there is one;
2. The aim of smoothing is to give a general idea of relatively slow changes of value with little attention paid to the close matching of data values, while curve fitting concentrates on achieving as close a match as possible.
3. Smoothing methods often have an associated tuning parameter which is used to control the extent of smoothing. Curve fitting will adjust any number of parameters of the function to obtain the 'best' fit.
However, the terminology used across applications is mixed. For example, use of an interpolating spline fits a smooth curve exactly through the given data points and is sometimes called "smoothing".

How to make a curve fit perfectly?

A perfect fit will be a fit which follows the actual data, we can achieve such a fit either by reducing the errors to minimum or by breaking the data into small groups(spliting the existing data).And can reconfirm the things by calculating for how a good fit is by some methods.

How to get the best fit?

Best fit is something which fits very near to the actual data curve and have minimum error values for assumed data points lying along the curve. To achieve a best fit we should go first for geometric fitting and than should confirm the numerial values for same i.e. nurmerical values which shows how good a fit is.

To determine the best fit, you should examine both the graphical and numerical fit results.
Examine the Graphical Fit Results
Determine the best fit by examining the graphs of the fits and residuals. The graphical fit results indicate that:
• The fits and residuals for the polynomial equations are all similar, making it difficult to choose the best one.
• The fit and residuals for the single-term exponential equation indicate it is a poor fit overall. Therefore, it is a poor choice and you can remove the exponential fit from the candidates for best fit.
Evaluate the Numerical Fit Results
When you can no longer eliminate fits by examining them graphically, you should examine the numerical fit results. The Curve Fitting app displays two types of numerical fit results:
• Goodness-of-fit statistics
• Confidence bounds on the fitted coefficients
The goodness-of-fit statistics help you determine how well the curve fits the data. The confidence bounds on the coefficients determine their accuracy.
Examine the sum of squares due to error (SSE) and the adjusted R-square statistics to help determine the best fit. The SSE statistic is the least-squares error of the fit, with a value closer to zero indicating a better fit. The adjusted R-square statistic is generally the best indicator of the fit quality when you add additional coefficients to your model. The largest SSE for exp1 indicates it is a poor fit, which you already determined by examining the fit and residuals. The lowest SSE value is associated with poly6. However, the behavior of this fit beyond the data range makes it a poor choice for extrapolation, so you already rejected this fit by examining the plots with new axis limits. The next best SSE value is associated with the fifth-degree polynomial fit, poly5, suggesting it might be the best fit. However, the SSE and adjusted R-square values for the remaining polynomial fits are all very close to each other. Which one should you choose?
Resolve the best fit issue by examining the confidence bounds for the remaining fits in the Results pane. Double-click a fit in the Table of Fits to open (or focus if already open) the fit figure and view the Results pane. A fit figure displays the fit settings, results pane and plots for a single fit. Display the fifth-degree polynomial and the poly2 fit figures side by side. Examining results side by side can help you assess fits.
Compare the coefficients and bounds (p1, p2, and so on) in the Results pane for both fits, poly5 and poly2. The toolbox calculates 95% confidence bounds on coefficients. The confidence bounds on the coefficients determine their accuracy. Check the equations in the Results pane (f(x)=p1*x+p2*x...) to see the model terms for each coefficient. Note that p2 refers to the p2*x term in Poly2 and the p2*x^4 term in Poly5. Do not compare normalized coefficients directly with non-normalized coefficients.
The bounds cross zero on the p1, p2, and p3 coefficients for the fifth-degree polynomial. This means you cannot be sure that these coefficients differ from zero. If the higher order model terms may have coefficients of zero, they are not helping with the fit, which suggests that this model overfits the census data.
However, the small confidence bounds do not cross zero on p1, p2, and p3 for the quadratic fit, poly2 indicate that the fitted coefficients are known fairly accurately.
Therefore, after examining both the graphical and numerical fit results, you should select poly2 as the best fit to extrapolate the census data.
If R^2 value is greater than 0.95 than we can state curve is a good fit.
What could be done to improve the cubic fit?
To improve cubic fit we can either go for lower order of polynomial or use spli method to detrmine the goodness factor and calculate R^2 for splited data.
Coding Part :
We have coding into two part one for comparying the actual data with 1st, 2nd ,& 3rd order of polynomial.
And the other code was designed to overcome the warning coming from 1st code.
1) Code comparying R^2 values for 1st, 2nd, & 3rd order and also giving geometric representation for same. This code gives us both numerical and geometrical fit for all orders used.
clear all
close all
clc

% Curve fitting for linear and cubic polynomial from a Cp (Specific Heat) data

% Parameters to be calculate from data: data includes values of Cp and
% temperature

cp_data = load ('data'); % For calculation first we need to load the file 

temperature = cp_data(:,1); % copying only temperature vaues to the variable
specific_heat = cp_data(:,2); % copying only specific heat values to variable

%Curve fit
co_effs1 = polyfit(temperature,specific_heat,1); %it will calculate coefficients value for the given order
predicted_cp1=polyval(co_effs1,temperature); % after getting coefficients value we get our predicted specific heat from this
co_effs2 = polyfit(temperature,specific_heat,2);%it will calculate coefficients value for the given order
predicted_cp2=polyval(co_effs2,temperature); % after getting coefficients value we get our predicted specific heat from this
co_effs3 = polyfit(temperature,specific_heat,3);%it will calculate coefficients value for the given order
predicted_cp3=polyval(co_effs3,temperature); % after getting coefficients value we get our predicted specific heat from this


%Ploting of data
hold on

plot(temperature,specific_heat,'color','r','linewidth',2) %Actual Curve fit

plot(temperature, predicted_cp1,'color','b') % Curve fit for linear polynomial
plot(temperature, predicted_cp2,'color','c','linewidth',1)% Curve fit for quadratic polynomial
plot(temperature, predicted_cp3,'color','g','linewidth',1.5)% Curve fit for cubic polynomial

title('Curve fittings between Specific Heat (cp) and Temperature(t)')%Name for graph
xlabel('Temperature [K]')
ylabel('Specific Heat [KJ/Kmol.K')
legend({'Actual c_p','Predicted c_p1','Predicted c_p2','Predicted c_p3'},'location','northwest')% denoting a name for line curves
axis ([0 3600 900 1350])%specifying limits for temp. and specific heat 

%Calculating mean for actual data (mean = sum of all/no. of elements)
sum=0;
sum1=0;
for i=1:length(specific_heat)
    sum=sum+specific_heat(i);
    sum1=sum1+temperature(i);
end
mean1=sum/length(specific_heat);
mean2=sum1/length(temperature);

%Measure the fitness characteristics by calculating R-square value for 1st order

ssr1=0;
sse1=0;

for i=1:length(specific_heat)
     
    sse1=sse1+(specific_heat(i)-predicted_cp1(i))^2; % gives us a sum of all error values along curve
    
end

for i=1:length(specific_heat)
     
    ssr1=ssr1+(predicted_cp1(i)-mean1)^2; % sum of regression for curve
    
end

sst1=ssr1+sse1;

R1=ssr1/sst1; % R^2 value for curve

%Measure the fitness characteristics by calculating R-square value for 2nd order

ssr2=0;
sse2=0;

for i=1:length(specific_heat)
     
    sse2=sse2+(specific_heat(i)-predicted_cp2(i))^2;% gives us a sum of all error values along curve
    
end

for i=1:length(specific_heat)
     
    ssr2=ssr2+(predicted_cp2(i)-mean1)^2;% sum of regression for curve
    
end

sst2=ssr2+sse2;

R2=(ssr2/sst2);%R^2 value for curve


%Measure the fitness characteristics by calculating R-square value for 3rd order

ssr3=0;
sse3=0;

for i=1:length(specific_heat)
     
    sse3=sse3+(specific_heat(i)-predicted_cp3(i))^2;% gives us a sum of all error values along curve
    
end

for i=1:length(specific_heat)
     
    ssr3=ssr3+(predicted_cp3(i)-mean1)^2; % sum of regression for curve
    
end

sst3=ssr3+sse3;

R3=(ssr3/sst3); %R^2 value for curve

% Statement for declaration of curve with best fit 
if ( R3 > R1 && R2 ) && ( R3 > 0.95)
    disp(" Curve with cubic polynomial has better curve fitting")
    
elseif ( R2 > R1) && (R2>0.95)
    disp("Curve with Quadratic polynomial has better curve fitting")
elseif (R1>0.95)
    disp("Curve with Linear polynomial has better curve fitting")
else 
    disp("No Curve has better curve fitting we need to split curves in increasing polynomial order")
end




Output cum Error Coming for same:
As, we can see here we have some warning sign coming for cubic polynomial which states Polynomial is badly conditioned and if we see the geometric fit for same so cubic has very minimum error and have shows best fit out of 3 fits we created, when compared to actual curve. And also for quadratic warning is not coming but geometric representation for quadratic is not very good and it has r^2 value as a good value.
So, to overcome the error we have tried to use splitwise polynomial method. In which 1st i tried for cubic but warning was not going for given data till 8 splits also. Than i lowered my order to quadratic and done split on it for 8 times than we were able to achieve a good fit in terms of numerical values also and even geometric representaion was very smooth.
2) Code for splitwise polynomial for quadratic.
clear all
close all
clc

% Curve fitting for linear and cubic polynomial from a Cp (Specific Heat) data

% Parameters to be calculate from data: data includes values of Cp and
% temperature

cp_data = load ('data'); % For calculation first we need to load the file

temperature = cp_data(:,1); % copying only temperature vaues to the variable
specific_heat = cp_data(:,2); % copying only specific heat values to variable

%No split quadratic
co_effs_ns2 = polyfit(temperature,specific_heat,2);
predicted_cp_ns2=polyval(co_effs_ns2,temperature);

%Split quadratic
temperature1 = cp_data(1:400,1); % copying only temperature vaues to the variable
specific_heat1 = cp_data(1:400,2); % copying only specific heat values to variable

temperature2 = cp_data(401:800,1); % copying only temperature vaues to the variable
specific_heat2 = cp_data(401:800,2); % copying only specific heat values to variable

temperature3 = cp_data(801:1200,1); % copying only temperature vaues to the variable
specific_heat3 = cp_data(801:1200,2); % copying only specific heat values to variable

temperature4 = cp_data(1201:1600,1); % copying only temperature vaues to the variable
specific_heat4 = cp_data(1201:1600,2); % copying only specific heat values to variable

temperature5 = cp_data(1601:2000,1); % copying only temperature vaues to the variable
specific_heat5 = cp_data(1601:2000,2); % copying only specific heat values to variable

temperature6 = cp_data(2001:2400,1); % copying only temperature vaues to the variable
specific_heat6 = cp_data(2001:2400,2); % copying only specific heat values to variable

temperature7 = cp_data(2401:2800,1); % copying only temperature vaues to the variable
specific_heat7 = cp_data(2401:2800,2); % copying only specific heat values to variable

temperature8 = cp_data(2801:3200,1); % copying only temperature vaues to the variable
specific_heat8 = cp_data(2801:3200,2); % copying only specific heat values to variable

%Curve fit
co_effs1 = polyfit(temperature1,specific_heat1,2); %Calculating coefficient for a curve for given range
predicted_cp1=polyval(co_effs1,temperature1); % Finding predicted specific heat for data
predicted_cp(1:400) = predicted_cp1; %copying predicted cp for given range

co_effs2 = polyfit(temperature2,specific_heat2,2); %Calculating coefficient for a curve for given range
predicted_cp2 = polyval(co_effs2,temperature2);% Finding predicted specific heat for data
predicted_cp(401:800) = predicted_cp2;%copying predicted cp for given range


co_effs3 = polyfit(temperature3,specific_heat3,2); %Calculating coefficient for a curve for given range
predicted_cp3=polyval(co_effs3,temperature3);% Finding predicted specific heat for data
predicted_cp(801:1200) = predicted_cp3;%copying predicted cp for given range


co_effs4 = polyfit(temperature4,specific_heat4,2); %Calculating coefficient for a curve for given range
predicted_cp4=polyval(co_effs4,temperature4);% Finding predicted specific heat for data
predicted_cp(1201:1600) = predicted_cp4;%copying predicted cp for given range


co_effs5 = polyfit(temperature5,specific_heat5,2); %Calculating coefficient for a curve for given range
predicted_cp5=polyval(co_effs5,temperature5);% Finding predicted specific heat for data
predicted_cp(1601:2000) = predicted_cp5;%copying predicted cp for given range


co_effs6 = polyfit(temperature6,specific_heat6,2); %Calculating coefficient for a curve for given range
predicted_cp6=polyval(co_effs6,temperature6);% Finding predicted specific heat for data
predicted_cp(2001:2400) = predicted_cp6;%copying predicted cp for given range


co_effs7 = polyfit(temperature7,specific_heat7,2); %Calculating coefficient for a curve for given range
predicted_cp7=polyval(co_effs7,temperature7);% Finding predicted specific heat for data
predicted_cp(2401:2800) = predicted_cp7;%copying predicted cp for given range


co_effs8 = polyfit(temperature8,specific_heat8,2); %Calculating coefficient for a curve for given range
predicted_cp8=polyval(co_effs8,temperature8);% Finding predicted specific heat for data
predicted_cp(2801:3200) = predicted_cp8;%copying predicted cp for given range

%Spliting can be done via loop also like this 
% a=1;
%     b=400;
%     for i=1:8
%         co_eff(i,:)=polyfit(temperature(a:b),specific_heat(a:b),2);
%         predicted(i,:)=polyval(co_eff(i,:),temperature(a:b));
%         predicted1(a:b)=predicted(i,:);
%         plot(temperature(a:b),predicted1(a:b))
%         hold on
%         a=b+1;
%         b=b+400;
%     end
        



%Measure the fitness characteristics by calculating R-square value for 2nd
%order after spliting

sum=0;
sum1=0;
for i=1:length(specific_heat)
    sum=sum+specific_heat(i);
    sum1=sum1+temperature(i);
end
mean1=sum/length(specific_heat);
mean2=sum1/length(temperature);

ssr3=0;
sse3=0;

for i=1:length(specific_heat)
     
    sse3=sse3+(specific_heat(i)-predicted_cp(i))^2;
    
end

for i=1:length(specific_heat)
     
    ssr3=ssr3+(predicted_cp(i)-mean1)^2;
    
end

sst3=ssr3+sse3;

R3=(ssr3/sst3);




%Ploting of data
hold on

plot(temperature,specific_heat,'color','r','linewidth',2) %Actual Curve fit

plot(temperature, predicted_cp_ns2,'color','g')% Curve fit for quadratic polynomial with no split


plot(temperature1, predicted_cp1,'color','b')% Curve fit for quadratic polynomial
plot(temperature2, predicted_cp2,'color','y')% Curve fit for quadratic polynomial
plot(temperature3, predicted_cp3,'color','b')% Curve fit for quadratic polynomial
plot(temperature4, predicted_cp4,'color','y')% Curve fit for quadratic polynomial
plot(temperature5, predicted_cp5,'color','b')% Curve fit for quadratic polynomial
plot(temperature6, predicted_cp6,'color','y')% Curve fit for quadratic polynomial
plot(temperature7, predicted_cp7,'color','b')% Curve fit for quadratic polynomial
plot(temperature8, predicted_cp8,'color','y')% Curve fit for quadratic polynomial

title('Curve fittings between Specific Heat (cp) and Temperature(t)')
xlabel('Temperature [K]')
ylabel('Specific Heat [KJ/Kmol.K')
legend({'Actual c_p','No Split Quadratic C_p','Spli Predicted c_p2'},'location','northwest')
axis ([0 3600 900 1350])

if (R3 > 0.98 )
    disp("Curve with Quadratic polynomial has better curve fitting after spliting")
else 
    disp("Curve with Quadratic polynomial still shows same behaviour even after spliting")
end
Output for code:
Results:
spliting quadratic polynomial equation has shown the characteristics of best fit as the r^2 value was found as 1 which means minimum error values or we can even say perfect fit.
But because we have done 8 splits we dont know it will be feasable for given data or not.
Graphs:
1)
2)
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.