PERFECT CURVE FITTING FOR GIVEN DATA
AIM : To fit given data in linear and cubic function
MATLAB CODE -
clear all
close all
clc
%preparing inputs
input=load('data');
temperature=input(:,1);
cp=input(:,2);
%curve fitting
%splitting data into four part
temp1=input(1:450,1);
cp1=input(1:450,2);
temp2=input(451:1100,1);
cp2=input(451:1100,2);
temp3=input(1101:2200,1);
cp3=input(1101:2200,2);
temp4=input(2201:3200,1);
cp4=input(2201:3200,2);
%find coefficient splitwise fit
%linear fit
[coeff1,s1,mu1]=polyfit(temperature,cp,1);
predicted_cp1=polyval(coeff1,temperature,s1,mu1);
%cubic fit
[coeff5,s5,mu5]=polyfit(temp1,cp1,3);
predicted_cp5=polyval(coeff5,temp1,s5,mu5);
[coeff6,s6,mu6]=polyfit(temp2,cp2,3);
predicted_cp6=polyval(coeff6,temp2,s6,mu6);
[coeff7,s7,mu7]=polyfit(temp3,cp3,3);
predicted_cp7=polyval(coeff7,temp3,s7,mu7);
[coeff8,s8,mu8]=polyfit(temp4,cp4,3);
predicted_cp8=polyval(coeff8,temp4,s8,mu8);
%plotting and comparison
plot(temperature,cp,'linewidth',4,'color','b');
hold on
%linear function
plot(temperature,predicted_cp1,'linewidth',2,'color','g');
%cubic function
plot(temp1,predicted_cp5,'linewidth',2,'color','r');
plot(temp2,predicted_cp6,'linewidth',2,'color','r');
plot(temp3,predicted_cp7,'linewidth',2,'color','r');
plot(temp4,predicted_cp8,'linewidth',2,'color','r');
hold off
xlabel('Temperature[k]');
ylabel('specific heat[KJ/Kmol-K]');
title('splitwise curve fit');
legend('original data','linear fit','cubic fit')
axis([250 3600 900 1400])
Explanation of code -
First we have to import the required data file ,for that purpose inbuilt load function is used.After that we created two variables for temperature and specific heat.Given data is then divided into these two variables.now for plotting the linear function to fit data we used polyfit command.it will give us coefficients for linear polynomial. then predicted cp is calculated based on function .error structure and scaling values are also taken to avoid center and scaling error while plotting.For plotting cubic fit data is divided into four suitable sections. and separate functions are fitted for these sections. combining all will give us required fit.curve can be fitted perfectly either by increasing degree of polynomial or split wise polynomial approach will give us best cubic fit
output-