Project

Curve fitting using matlab

Aim:-

To see what curve fitting means, what are the different types of curve fittings, and what can be done to get a best curve fit.

Background:-

A curve fitting is a technique to predict a given curve in an equation form and predict a curve for that equation. The increase in accuracy of the equation increases the predicted curves closeness to the actual curve. By the help of predicted curves one can predict the upcoming trends of the curves and define the values according to them.

In the above graph we can see the blue dots represinting the values gatthered while the red line defines the predicted cuve.

Curve fitting can be with polynomial range of equations, such as:

1)Linear 2)Quadratic 3)Cubic etc.....

Each n th will give n+1 coefficients upon which a equation is created.

Problem defination:-

1) We will make two curve fittings with a linear and cubic polynomial for a data consisting of values of specific heat for each value of temperature.

You can get data here Credits:- Skill-lync.com

https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view

2) We will use 'polyfit' (matlab inbuilt function) to get values of constants

3) We will use 'polyval' (matlab inbuilt function) to get values of predicted cp for eact temperature.

4) We will create a plotting animation with a plot graph for better visualizing.

Program:-

%Program to create curve fits

%load the values of temperature and cp
data=load('data');                           %The data file should be in current folder 

%Assign temperature values to variable temp
temp=data(:,1);

%Assign cp values to variable cp
cp=data(:,2);

%Assigning linear curve fit constant values to const1
const1=polyfit(temp,cp,1);
%Getting cp values for each temperature of linear curve fit
cp1=polyval(const1,temp);

%Assigning cubic curve fit constant values to const3
const3=polyfit(temp,cp,3);
%Getting cp values for each temperature for cubic curved fit
cp3=polyval(const3,temp);

a=1;                                  %Variable to count frame number

%Creating animation of orignal, first order and third order curves
for i=1:99:3100                                         %loop for orignal curve
plot(temp(i:i+99),cp(i:i+99),'r','linewidth',1);        %plot orignal cirve
axis([0 3500 900 1350]);                                %define axis limit
xlabel('Temperature(K)');                               %define x axis label
ylabel('Specific heat(kJ/kmole-K)')                     %define y axis label
title('Curve fitting')                                  %define title of plot
hold on;                                                %holds figure for next argument
Frame(a)=getframe(gcf);                                 %Stores each frame in Frame
a=a+1;                                                  %Assign the next frame
end                                                     %terminate the loop

for i=1:49:3100                                         %loop for linear curve
plot(temp(i:i+49),cp1(i:i+49),'b','linewidth',1);       %plots linear curve
Frame(a)=getframe(gcf);                                 %Stores frames
a=a+1;                                                  %Assigns next frame
end                                                     %terminate the loop

for i=1:49:3100                                         %loop for cubic curve
plot(temp(i:i+49),cp3(i:i+49),'k','linewidth',1);       %plots cubic curve
Frame(a)=getframe(gcf);                                 %stores frames
a=a+1;                                                  %assigns next frame
end                                                     %terminate the loop

%Creating plot of orignal, first order and third order curve fit
figure(2)                                               %active the figure(2)
plot(temp,cp,'r','linewidth',2);                        %plots orignal curve
axis([0 3500 900 1350]);                                %limits the axis
xlabel('Temperature(K)');                               %x axis label
ylabel('Specific heat(kJ/kmole-K)')                     %y axis label
title('Curve fitting')                                  %title of plot
hold on                                                 %holds figure for next argument
plot(temp,cp1,'b','linewidth',2);                       %plots linear curve
plot(temp,cp3,'k','linewidth',2);                       %plots cubic curve

%gives legend to the plot
legend('orignal','first order curve','third order curve','Location','northwest');

%Creating and saving the animation file                             
videofile=VideoWriter('curve_fitting.avi','Uncompressed AVI');      %creating file
open(videofile);                                                    %opening file
writeVideo(videofile,Frame);                                        %writing frames
close(videofile);                                                   %closing file
        

Output:-

NOTICE:- The program runs perfectly fine, but matlab says, 'Polynomial is badly conditioned. Add points with distinct X values, reduce the degree of the polynomial, or try
centering and scaling as described in HELP POLYFIT.'

Matlab is given us the suggestion to use centering and scaling the curve.

How does centering and scaling works:

Use polyfit with three outputs to fit the polynomial using centering and scaling, which improves the numerical properties of the problem.

'polyfit' centers the data at temperature to 0 and scales it to have a standard deviation of 1, which avoids an ill-conditioned Vandermonde matrix in the fit calculation.

Three outputs taken(p,~,mu)

Use polyval with four inputs to evaluate p with the scaled temperature,

(temperature-mu(1))/mu(2). Plot the results against the original temperatures.

Program using the centering and scaling:

%Program to make a linear and cubic curve fit

%load the values of temperature and cp
data=load('data');

%Assign temperature values to variable temp
temp=data(:,1);

%Assign cp values to variable cp
cp=data(:,2);

%Making a curve fit of first order
const1=polyfit(temp,cp,1);
%Getting cp values for each temperature of linear curve fit
cp1=polyval(const1,temp);

%Making a curve fit of third order
[p,~,mu]=polyfit(temp,cp,3);
%Getting cp values for each temperature of cubic curved fit
cp3=polyval(p,temp,[],mu);

a=1;                                                 %variable to count frame number

%Creating animation of orignal, first order and third order curves
for i=1:99:3100                                            %loop for orignal curve
plot(temp(i:i+99),cp(i:i+99),'r','linewidth',1);           %plot orignal curve
axis([0 3500 900 1350]);                                   %limit the axis
xlabel('Temperature(K)');                                  %x axis label
ylabel('Specific heat(kJ/kmole-K)')                        %y axis label
title('Curve fitting')                                     %title of plot
hold on;                                                   %holds the figure
Frame(a)=getframe(gcf);                                    %capture frames into Frame
a=a+1;                                                     %assigns next frame
end                                                        %terminate the loop

for i=1:49:3100                                            %loop for linear curve
plot(temp(i:i+49),cp1(i:i+49),'b','linewidth',1);          %plot linear curve
Frame(a)=getframe(gcf);                                    %capture frame in Frame
a=a+1;                                                     %assign next frame
end                                                        %terminate the loop

for i=1:49:3100                                            %loop for cubic curve
plot(temp(i:i+49),cp3(i:i+49),'k','linewidth',1);          %plot cubic curve
Frame(a)=getframe(gcf);                                    %capture frame into Frame
a=a+1;                                                     %assign next frame
end                                                        %terminate the loop

%Creating plot of orignal, first order and third order curve fit
figure(2)                                                  %activates the figure 2
plot(temp,cp,'r','linewidth',2);                           %plot orignal curve
axis([0 3500 900 1350]);                                   %limit the axis
xlabel('Temperature(K)');                                  %x axis label
ylabel('Specific heat(kJ/kmole-K)')                        %y axis label
title('Curve fitting')                                     %title of plot
hold on                                                    %holds the figure
plot(temp,cp1,'b','linewidth',2);                          %plot linear curve
plot(temp,cp3,'k','linewidth',2);                          %plot cubic curve

%create legend at top of plot
legend('orignal','first order curve','third order curve','Location','northwest');

%Creating and saving the animation file
videofile=VideoWriter('curve_fitting.avi','Uncompressed AVI');     %create file
open(videofile);                                                   %open file
writeVideo(videofile,Frame);                                       %write frames
close(videofile);                                                  %close file
        

Corrected Output:-

1) We get a plot contaning the three curves (orignal, linear and cubic)

2) We can see the animation for the plotting below

Curve_animation

How to know if the fitted curve is good enough:-

1) There are mainly 4 properties to a fitted curve:

a) Sum of squared roots(SSE):

Let the equation of the fitted curve be y=f(x) Here x are independent points

So for each point x there is an error in lets say y-axis between the orignal value y(i) and the

fitted curve value f(i). Here i is the point number

Sum of this errors squared is called SSR

SSE=`sum`[y(i)-x(i)]^2

The value is squared to make all negative values of error to positive.

b) R-square:

R-square=SSR/SST

Here SST=SSR+SSE

SSR=`sum`[f(i)-mean]^2

c) Adjusted R-square:

It mainly depends on number of independent variables.

adjusted R-square= 1-[((1-R^2)*(n-1))/(n-k-1)]

Here n= number of points

k= number of independent variables

d) Root mean squared errors(RSME):

RSME=`square root`[SSE/n]

2) Any curve having a R-square value above 0.95 is called as a good curve.

0<=R-square<=1

0= poor curve

1= perfect curve

Perfect curve:-

It is a fitted curve whoes each point of the curve matches exactly to the given data values. If a plot of orignal perfect curve are created on same figure, then both the curves will overlap.

Best curve:-

A best curve is the fitted curve having the higest R-square value possible. The curve having R-square value =1 is called a perfect curve while a curve having mainly R-square value between 0.95 to 1 is considered to be a best curve. Each point of the best curve will not surely match the orignal curve points.

Methods to improve the fitted curve:-

There are many methods which can be used to improve the curve, some of which are:

1) Split the curve into different sections and then try to make a fitted curve.

2) Use higher degree polynomial (should be used till a certain limit).

3) Transforming variables with log function in a linear regression, and many more.....

Using split method to improve above cubic curve:-

We split the cubic curve equation into 32 different cubic curves and plot the grap.

--> improved curve program:-

%Program to make a best curve fit

%load the values of temperature and cp
data=load('data');

%Assign temperature values to variable temp
temper=data(:,1);

%Assign cp values to variable cp
cp=data(:,2);

a=1;                                        %variable to count frame number

%Making a curve fit of third order
for i=1:200:3200                                   %loop to divide curve into 32 parts 
[p,~,mu]=polyfit(temper(i:i+199),cp(i:i+199),3);

%Getting cp values for each temperature of third order curved fit
cp3(i:i+199)=polyval(p,temper(i:i+199),[],mu);
end                                                %terminate the loop

for i=1:100:3200                                         %loop to animate orignal curve
plot(temper(i:i+99),cp(i:i+99),'r','linewidth',2);       %plot orignal curve
axis([0 3500 900 1350]);                                 %limit axis
xlabel('Temperature(K)');                                %x axis label
ylabel('Specific heat(kJ/kmole-K)');                     %y axis label
title('Curve fitting');                                  %title name
hold on                                                  %hold the figure
Frame(a)=getframe(gcf)                                   %capture frame into Frame
a=a+1;                                                   %assign next frame
end                                                      %terminate loop

for i=1:50:3200                                          %loop to animate cubic curve
plot(temper(i:i+49),cp3(i:i+49),'k:','linewidth',2);     %plot cubic curve
Frame(a)=getframe(gcf);                                  %capture frame
a=a+1;                                                   %assign next frame
end                                                      %terminate loop

figure(2)                                                %activate figure 2
plot(temper,cp,'r','linewidth',2);                       %plot orignal curve
hold on                                                  %hold figure
plot(temper,cp3,':k','linewidth',2);                     %plot cubic curve
legend('orignal curve','cubic curve','Location','northwest');     %enter a legend

videofile=VideoWriter('fiitted_curve_corrected.avi','Uncompressed AVI')  %create file
open(videofile)                                                          %open file
writeVideo(videofile,Frame)                                              %write file
close(videofile)                                                         %close file
        

Outputs:-

1) Graph of orignal and cubic fitted curve. The cubic curve has nearly all the points matching to the orignal curve points so it overlaps it. It can be treated as a best curve as it has R-square value ~~1.

2) The cubic curve is overlaping the orignal so not visible neatly. Use the below animation to see how the cubic curve is plot.

cubic_curve_plot

Conclusion:-

1) We saw the fitted curves can be used to determine the trends in a dataset.

2) We saw how the properties of the curve define their goodness.

3) We saw the way a curve can be improved to get more accurate results.

4) Matlab makes all of this a easy task to deal with.

Reference:-

1) Skill-lync (https://courses.skill-lync.com/)

2) The minitab blog (https://blog.minitab.com/blog/adventures-in-statistics-2/curve-fitting-with-linear-and-nonlinear-regression)

3) Matlab (https://www.mathworks.com/help/curvefit/curve-fitting.html)

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.