Project

Curve Fitting with splitwise method in MATLAB

AIM – To perform curve fitting in MatLab

OBJECTIVES–

  • To perform curve fit for linear and cubic polynomial
  • To perform splitwise method of curve fitting
  • To evaluate the goodness of curve
  • To find maximum error of the curve

THEORY –

Curve fitting is the method of constructing a best curve for the provided data. It is used for associating a range of data to a function which is highly used in mathematical and engineering field. The process can have involvement of interpolation or smoothing technique. Interpolation is the method of producing new data point between given set of data points. Smoothing is the process of making an approximate curve for data points while leaving the noises.

How to make a curve fit perfect?

Perfect fit can be defined as a fit which shows no corresponding errors when compared to original curve. The curve fit can be made perfect by

  • By generating fit to error function- In this method, the error function is formed to interpolate results. Further they are compared to original one
  • By using centering and scaling- centering is the method of eliminating values with high variances using a mean value and standard deviation. Scaling is the method of adjusting the scale (find a common suitable unit) of different variables.

A perfect fit can be a best fit but vice versa is not true.

How to make the best fit?

The intention to make the best fit is to eliminate the error. The best fit has R square value as 1 and SSE as 0. However, best fit doesn’t claim to pass through every provided data point. To make the fit to be best, following methods are used-

  • Increasing the value of ‘n’ – the increase in degree of polynomial provides a good trace of data points, hence, reducing the error. The higher the degree, better is the fit.
  • Applying splitwise method to the provided data- The splitting of data in various subsections and then applying linear regression gives a better curve fit. The methodology will be explained later in project.

What can be done to improve the cubic curve?

The cubic curve can be improved by following methods-

  • By using centering and scaling
  • By using splitwise method

Explain the parameters used to measure the fitness characteristics for both the curves.

The fitness of curve is the measure to know how well the polynomial traces the data points. It can be done by following method or parameters-

  • Sum of squares of errors

As it says, it is the total sum of errors at every data point. The error is the deviation of response values from the fit to the actual response value. The closer the result to 0(zero), the better is the fit.

  • R- square

` R-square is the square of the correlation between the response values and the response values of fit. It can be shown as the ratio of the sum of squares of the regression (SSR) and the total sum of squares (SST).

Its range lies between [0,1] and the closer value to 1, the better is the curve as it shows that greater number of variances are accounted in the data

  • Adjusted R-square

Adjusted R-square value is adjusted value of R-square based on the residual degrees of freedom (v).

v = n - m

n is the total number of residual values

m is the total number of coefficients in the fit curve

The formula used is as follows: -

The adjusted R-square values are less than or equal to 1. A value closer to 1 indicating a better fit. Negative values can occur when the model contains terms that do not help to predict the response.

  • Root Mean Square 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

The mean square error is given by the formula

An MSE value closer to 0 indicates a fit that is more useful for prediction.

POLYFIT

The command is used provide coefficient for the polynomial which is formed by the given data points. It can be provided by following code –

y= polyfit(x,y,n)

where x is the x component data

y is the y component data

n is the degree of polynomial

POLYVAL

The command is the provide values of polynomial which is provided

coeff= polyval(fn,x)

where fn is the function

x is the provided ‘x’ component

y is the calculated y component

LINEAR AND CUBIC FUNCTION

The functions are provided and solution has been attached

close all
clear all
clc

%data
cp_data=load('data1');
temp = cp_data(:,1);
cp = cp_data(:,2);

%linear curve fit
coeff_1 = polyfit(temp,cp,1);     %for polynomial's coefficient
pred1_cp =polyval(coeff_1,temp);  %for polynomial value

figure(1)
hold on
plot(temp,cp)                    %graph for present data
plot(temp,pred1_cp)              %graph for predicted data
xlabel('temperature(K)');
ylabel('cp(KJ/Kmol-K)')
legend('OG data','curfit')
title('linear curve')

%cubic curve fit
[coeffi3] = polyfit(temp,cp,3);
pred3icp =polyval(coeffi3,temp);

hold off
figure(4)
hold on
plot(temp,cp)
plot(temp,pred3icp)
xlabel('temperature(K)');
ylabel('cp(KJ/Kmol-K)')
legend('OG data','curfit')
title('without mu and s cubic curve')

linear function and cubic fit reults.

The graph shows that curve fitting can be improved by centering and scaling. This method defines a mean value and standard deviation along with scaling all the data points to a single unit. This decreases the variance and hence the curvefit increases.The code is as follows -

%cubic curve fit with centering and scaling
%'~' is for scaling and 'mu' is for centering
%mu1 defines the mean and mu2 defines standard deviation

[coeff_3,~,mu] = polyfit(temp,cp,3); 
pred3_cp =polyval(coeff_3,temp,[],mu);   
hold off
figure(2)
hold on
plot(temp,cp)
plot(temp,pred3_cp)
xlabel('temperature(K)');
ylabel('cp(KJ/Kmol-K)')
legend('OG data','curfit')
title('cubic curve with centering and scaling')

result does not show significant change but goodness of fit has been increased

SPLITWISE METHOD-

Further to improve the fit, splitwise method is used in which the provided data is splitted into multiple domains and hence provided with a fit for each domain. This improves the goodness of fit. The code and results for it are shown below-

%splitwise method
%split1 - 1 to 400 data points

    cp_data=load('data1');
    temp1 = cp_data((1:400),1);
    cp1 = cp_data((1:400),2);

    [coeff1,s1,mu1] = polyfit(temp1,cp1,3);
    predicted_cp1 =polyval(coeff1,temp1,[],mu1);

%split2 - 400 to 700 data points

    cp_data=load('data1');
    temp2 = cp_data((401:700),1);
    cp2 = cp_data((401:700),2);

    [coeff2,s2,mu2] = polyfit(temp2,cp2,3);
    predicted_cp2 =polyval(coeff2,temp2,[],mu2);

%split3 - 700 to 1000 data points

    cp_data=load('data1');
    temp3 = cp_data((701:1000),1);
    cp3 = cp_data((701:1000),2);

    [coeff3,s3,mu3] = polyfit(temp3,cp3,3);
    predicted_cp3 =polyval(coeff3,temp3,[],mu3);
    
    
%split4 - 1001 to 1500 data points

    cp_data=load('data1');
    temp4 = cp_data((1001:1500),1);
    cp4 = cp_data((1001:1500),2);

    [coeff4,s4,mu4] = polyfit(temp4,cp4,3);
    predicted_cp4 =polyval(coeff4,temp4,[],mu4);

%split5 - 1501 to 2500 data points

    cp_data=load('data1');
    temp5 = cp_data((1501:2500),1);
    cp5 = cp_data((1501:2500),2);

    [coeff5,s5,mu5] = polyfit(temp5,cp5,3);
    predicted_cp5 =polyval(coeff5,temp5,[],mu5);

%split6 - 2501 to 3200 data points  
  
    cp_data=load('data1');
    temp6 = cp_data((2501:3200),1);
    cp6 = cp_data((2501:3200),2);

    [coeff6,s6,mu6] = polyfit(temp6,cp6,3);
    predicted_cp6 =polyval(coeff6,temp6,[],mu6);

%graph for splits

hold off
figure(4)
hold on
plot(temp1,cp1,'color','b','linewidth',3);
plot(temp1 ,predicted_cp1,'color','r','linewidth',1.5);
plot(temp2,cp2,'color','b','linewidth',3);
plot(temp2 ,predicted_cp2,'color','r','linewidth',1.5);
plot(temp3,cp3,'color','b','linewidth',3);
plot(temp3 ,predicted_cp3,'color','r','linewidth',1.5);
plot(temp4,cp4,'color','b','linewidth',3);
plot(temp4 ,predicted_cp4,'color','r','linewidth',1.5);
plot(temp5,cp5,'color','b','linewidth',3);
plot(temp5 ,predicted_cp5,'color','r','linewidth',1.5);
plot(temp6,cp6,'color','b','linewidth',3);
plot(temp6, predicted_cp6,'color','r','linewidth',1.5);
xlabel('temperature(K)');
ylabel('cp(KJ/Kmol-K)')
legend('OG data','curfit')
title('splitwise method curve fitting')
hold off

%parameters for error

predicted_cp = [predicted_cp1; predicted_cp2; predicted_cp3; predicted_cp4;predicted_cp5;predicted_cp6];
cp = [cp1; cp2; cp3; cp4; cp5; cp6];

%error
%maximum error
err= ((cp - predicted_cp)/cp)*100 ;
m_err = max(err)

The fit is great now and also the error percentage is calculated for it, which is 0.0235. the formula for error percentage is

Error percent = {(predicted value)- (original value)} *100/ (original value)

PROCEDURE-

  • The whole data is splitted into 6 domains containing range which has been set by hit and trail method.
  • Further, similar to earlier phases, polyfit and polyval command is used with keeping the degree of polynomial as 3
  • The graphs were plotted seperatedly for each domain using plot command and kept in one frame using "hold on" command.
  • A matrix for predicted cp and cp was created by merging all 6 domains in one. This was done to find the error in the curve fit.
  • Finally , calculation for error percentage is done and error was found to be 0.0235 or 2.35% .

RESULT

GOODNESS OF FIT

The goodness of fit has been calculated using the predefined formulae. The various commands used are polyfit, polyval, for loop, plot, hold on and algebraic

%goodness of fit

clc
close all
clear

cp_data=load('data1');
temp = cp_data(:,1);
cp = cp_data(:,2);

[coeff,s,mu] = polyfit(temp,cp,3);
pred_cp =polyval(coeff,temp,[],mu);


hold on
plot(temp,cp,'color','b');
plot(temp,pred_cp,'color','r');
xlabel('temperature(K)');
ylabel('cp(KJ/Kmol-K)');
legend('OG data','curfit');


%goodness of fit

%sumof squares of error

SSE=0;
for i=1:length(cp_data)
    
    y(i) = (cp(i) - pred_cp(i))^2;
    SSE = SSE + y(i);
    
end

%(Sum of cp) = c

c=0;
for j= 1:length(cp)
    
    c=c+ cp(j);
end

mean = c/(length(cp));


%sum of squares of regression

ssr=0;
for k=1:length(cp_data)
    
    z(k)=(pred_cp(k)-mean)^2;
    
    ssr= ssr+ z(k);
end

%Total sum of squares

 sst = SSE+ssr

%R-square

 R_square = ssr/sst

%Adjusted R-square

 asdj_rsq =1-((SSE*(length(cp)- 1))/(sst*(length(cp)-length(coeff))))

%Root Mean Square Error

 RSME = (SSE/(length(cp)-length(coeff)))^0.5
  • The sum were calculated using a for loop
  • a dummy vector was produced with initial value as 0
  • as the loop repeates, the dummy is filled with new value which has addition of 'i'th/'j'th/'k'th value of the provided equation
  • the loop ends when value reaches till length of the provided data

RESULT

The values are calculated and goodness is fit is good.

CONCLUSION-

  • The curve fit is an essential tool in finding a function to provided data points
  • Curve fitting can be improved by centring or scaling and splitwise method.
  • Goodness of helps us to know the quality of fit

ERRORS -

No major error was there during the progress of coding.

SOURCES OF DATA-

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

https://in.mathworks.com/help/curvefit/evaluating-goodness-of-fit.html#d120e12463

https://www.youtube.com/watch?v=Vv69uhUiGU4

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.