Curve Fitting
Introduction
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.
Best Fit is the best possible way to represent a set of values by curve fitting. It is not necessary the polynomial represents all values.
Perfect fit is a way to represent a set of values such that all values could be found by this polynomial.
Formulas Used
`SSE = Σ"Error"(i)^2`
`SSR = Σ(f(x(i))-Mean)^2`
`SST = SSR + SSE`
`R^2 = "SSR"/"SST"`
`R^2adj = 1-[((1-R^2)*(n-1))/(n-k-1)]`
`RSME = ("SSE"/n)^0.5`
Code
- Firstly the given data is uploaded in a matrix.
- Using that matrix, cp and temperature are stored in column vectors.
- A polynomial of order `1` and `3` is created using the polyfit function which takes input some parameters (cp, temperature matrix, and order of polynomial).
- Then the predicted values of cp using polyval function are found out.
- The original and predicted curve is plotted.
- `SSR, SSE, and SST` are calculated.
- Using these values `R^2`, `R^2adj` and `RSME` are calculated.
- Using these values we can determine the goodness of fit criteria.
% A program to Curve fit to given set of parameters
close all
clear all
clc
% Loading the data to which curve fit is to be done
cp_data = load('data');
temprature = cp_data(:,1);
cp = cp_data(:,2);
% Performing curve fit using polyfit and polyval
co_effs = polyfit(temprature,cp,1);
predicted_cp = polyval(co_effs,temprature);
%constant =
% Plotting original and predicted curve
plot(temprature, cp,'linewidth', 3);
hold on;
plot(temprature, predicted_cp,'linewidth', 3);
xlabel('Temperature[K]');
ylabel('Specific Heat [KJ/Kmol-K]');
legend('Original Curve','Predicted Curve');
grid on;
title('Curve Fit (1st degree polynomial)');
hold on;
Error = cp-predicted_cp;
% Calculating SSE
SSE = 0;
sum = 0;
for i=1:length(cp)
SSE = SSE+Error(i)^2;
sum = sum+cp(i);
endfor
SSE
n = length(cp)
k = 2
mean = sum/n
%Calculating SSR
SSR = 0;
for j=1:length(predicted_cp)
SSR = SSR+(predicted_cp(i)-mean)^2;
endfor
SSR
SST = SSR+SSE
% Calculating R^2
R_sq = SSR/SST
% Calculating Radj^2
R_sq_adj = 1-((1-R_sq)*(n-1)/(n-k-1))
RMSE = (SSE/n)^0.5
% Saving the plot
file_text=sprintf('plot1.png',n);
saveas (gca, file_text);
Output
For 1st degree polynomial :
For 2nd degree polynomial :