Project

Fit a linear and cubic polynomial for the Cp data

- 1. Aim: Write code to fit a linear and cubic polynomial for the Cp data.

- 2. Objective:

- Plot the linear and cubic fit curves along with the raw data points.

- Write a code to show splitwise method.

- To get best possible fit.

- 3. Method:

- Curve fitting is one of the most powerful and most widely used analysis tools in Origin. 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.

- Curve fit describes how data changes mathematically.

- The code shown below is used to get the output for linear, quadratic and cubic order expression.

- Initially, a general cp vs temperature plot for all the values is plotted.

- Then in order to understand how each expression captures the curve, a curve for 1st, 2nd, and 3rd order is plotted.

- In order to extract the data, make sure that the data file is in same path where code is saved.

clear all
close all
clc

% load command is used to read files
cp_data = load('data');
% preparing the data
temperature = cp_data(:,1);
cp = cp_data(:,2);
% plot curve with original values
plot(temperature,cp,'linewidth',3)

%cp = a*T + b, Plto for first order plunomial 
co_effs_1 = polyfit(temperature,cp,1);
predicted_cp_1 = polyval(co_effs_1,temperature)
hold on
plot(temperature,predicted_cp_1,'linewidth',3)
xlabel('Temperature [k]')
ylabel('Specific heat [kj/kmol-k')
title('Linear polynomial for Cp data')
legend('Original data','Fitted curve')

figure(2)
plot(temperature,cp,'linewidth',3)
%cp =a*T^2 + b*T + c, plot for quadratic polynomial
co_effs_2 = polyfit(temperature,cp,2);
predicted_cp_2 = polyval(co_effs_2,temperature)
hold on
plot(temperature,predicted_cp_2,'linewidth',3)
xlabel('Temperature [k]')
ylabel('Specific heat [kj/kmol-k')
title('2nd order polynomial for Cp data')
legend('Original data','Fitted curve')

figure(3)
plot(temperature,cp,'linewidth',3)
%cp = a*T^3 + b*T^2 + c*T + d, plot for cubical polynomial 
co_effs_3 = polyfit(temperature,cp,3);
predicted_cp_3 = polyval(co_effs_3,temperature)
hold on
plot(temperature,predicted_cp_3,'linewidth',3)
xlabel('Temperature [k]')
ylabel('Specific heat [kj/kmol-k')
title('Cubic polynomial for Cp data')
legend('Original data','Fitted curve')

Plot for 1st order polynomial

Plot for 2nd order polynomial. Here it tries to capture the original data set

Here MATLAB tries to capture the original data set, but it throws an error.

Warning from MATLAB : Polynomial is badly conditioned. Add points with distinct X values, reduce the degree of the polynomial, or try centering and scaling.

Going with higher-order polynomial the errors will be zero but the nature of graph may vary when we use it for prediction, that is due to a higher power if there is a small change in input values the output will vary drastically.

Curve Fitting toolbox is used for 1st order expression and here it gives the values of SSE, R^2, Adj R^2 & RMSE.

Curve Fitting toolbox is used for 2nd order expression and it gives the values of R^2, SSE, Ajd R^2, & RMSE

Curve fitting toolbox is used for 3rd order expression and here it gives the values of SSE, R^2, Adj R^2 & RMSE.

Calculating R^2 for linear plot

% R1 + R^2 for linear plot
mean = sum(cp)/length(cp)
ssr1 = (predicted_cp_1 - mean).^2;
sse1 = (cp - predicted_cp_1).^2;
SSR1 = sum(ssr1);
SSE1 = sum(sse1);

R1 = SSR1/(SSE1 + SSR1);

Calculating R^2 for the cubic plot.

% R3 + R^2 for cubic plot
mean = sum(cp)/length(cp)
ssr3 = (predicted_cp_3 - mean).^2;
sse3 = (cp - predicted_cp_3).^2;
SSR3 = sum(ssr3);
SSE3 = sum(sse3);

R3 = SSR3/(SSE3 + SSR3);

- Plot formed by the Split operation.

- While using a higher-order polynomial, MATLAB is giving an error showing the bad condition. As for a higher values of order, a small change in input value drastically changes the output.

- This results in bad condition of the plot and in order to overcome this error a somewhat advance method is used, which is called as "Splitwise method".

- In this method, we separate the data in n number of segments are try to plot these each segments in linear order, in order to capture the curve better.

- Here in this particular plot, all the 3200 values are divided into 10 segments of 320 each and for those a linear plot is generated.

- For this a for loop is used

clear all
close all
clc

% load command is used to read files
cp_data = load('data');
% preparing the data
temperature = cp_data(:,1);
cp = cp_data(:,2);
plot(temperature,cp,'linewidth',2);

%split the cp values in 10 segments
a = 1;
b = 3200/10;
for i = 1:10
    for j = a:b
        % co_eff(i,:) is used to store all the values and to avoid
        % overwrite of the data.
      co_eff(i,:) =  polyfit(temperature(a:b),cp(a:b),1);
      new_cp(a:b) = polyval(co_eff(i,:),temperature(a:b));  
     
    end
    hold on
    plot(temperature(a:b),new_cp(a:b),'linewidth',2);
    a = 1+b;
    b = b+320;
end

title('split curve');
xlabel('Temperature [k])');
ylabel('Specific heat [kj/kmol-k]');
legend('original');

Another way to do split operation:

- In the code shown below, raw data is taken in 'cp' variable and in the for loop 'cp' and 'temperature' values of each segment from 1 to 320 is given to 'new_cp' and 'new_temp' variables.

- As i ranges from 1 to 10, as we are going to divide the data in 10 segments, each time the loop run, for each values of 'i' a segment get generated and all the coefficient values of 1st order expression are assigned to 'corff'.

- Once the values of 1st segment are taken, it is necessary to do increment of a and b in order to take the 2nd segment and perform the same operations again. For this reason, values of a and b are increamented.

clear all
close all
clc

% load command is used to read files
cp = load('data');

%split the cp values in 10 segments
a = 1;
b = 3200/10;
for i = 1:10
    new_cp = cp(a:b,2);
    new_temp = cp(a:b,1);
    plot(new_temp,new_cp,'linewidth',2,'color','r');
    hold on
    coeff = polyfit(new_temp,new_cp,1);
    pred = polyval(coeff,new_temp);
    plot(new_temp,pred,'linewidth',2,'color','g'); 
     
    a = 1+b;
    b = b+320;
end

title('split curve');
xlabel('Temperature [k])');
ylabel('Specific heat [kj/kmol-k]');
legend('original','predicted');

Output from Split method.

Plot obtained after splitting the data into the segment and taking 1st order plots, as the 1st order gives the more robust output.

- Scaling and Centering the plot.

- As the MATLAB has given the warning of the curve in a bad condition, in order to remove that warning and use higher-order polynomial to fit the curve with original values another method can be used.

- Here a third parameter is introduced which is used to do the centering and scaling of the plot.

- [p,S,mu] = polyfit(x,y,n) also returns, which is a two-element vector with centring and scaling values. mu(1) is mean(x), and mu(2) is std(x). Using these values, polyfit centres x at zero and scales it to have a unit(1) standard deviation.

- This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.

- Plotting the curve with this method enables us to use higher-order polynomial to capture the curve much better.

clear all
close all
clc

% load command is used to read files
cp_data = load('data');
% preparing the data
temperature = cp_data(:,1);
cp = cp_data(:,2);
plot(temperature,cp,'linewidth',2,'color','g');

% mu is a two element vector with centering and scaling values. mu(1) is
% mean(x) and mu(2) is standard deviation. This is done for centering and
% scaling the data.

[coef,~,mu] = polyfit(temperature,cp,10);
new_cp = polyval(coef,temperature,[],mu);
hold on
plot(temperature,new_cp,'color','r','linewidth',2);
hold off

xlabel('temperature');
ylabel('Cp');
legend('Original data','fitted curve');

Here can be seen that the curve obtained matches with the original data. Although the order is taken 10th, still there is no warning or error as the scaling and centering is done.

- Perfect fit: perfect fit means the curve should fit the original curve without showing any error in that particular polynomial.

- Best fit: Best fit can be achieved either by splitting the data into several segments and forming these by using linear regression, which captures the curve in a more robust manner or to increase the degree of polynomial. We can also get the best fit by centering and scaling the data which is shown above.

- How to choose best fit:

- There are 4 quantities which help us to measure the goodness of fit criteria or how well the equation is representing the data point.

1. R square - is the square of the correlation between response values and the predicted response values. In a simple way, the higher the value of R better the fit. It values ranges from 0 to 1. 0 is worst possible fit and 1 is best possible fit.

2. Adjusted R square - it disregards infinitesimally small increments to R square, and only considers the variable which contributes to the output of the system.

3. Root mean square error

4. SSE

- However, all the calculation can be done in the criteria toolbox and those are mentioned above.

4. Learning outcome:

- Understanding the splitting method.

- What is curve fitting and how it aid in predicting the outcome of one independent variable form some dependant variable.

- Use of Curve fitting toolbox.

- 5. Conclusion:

- In order to get best fit, higher order to expression is used, however it results in bad condition of plot, in order to remove it either splitting can be used or scaling and centering has to be done.

- Reference:

- https://skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860

- https://in.mathworks.com/help/matlab/ref/polyfit.html#bufcrts

- https://skill-lync.com/knowledgebase/curve-fit-toolbox-an-overview

- https://skill-lync.com/knowledgebase/the-basic-concept-of-curve-fit

- https://in.mathworks.com/matlabcentral/answers/229518-how-to-use-a-loop-to-find-a-sum-and-average

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.