Project

CURVE FITTING using MATLAB

AIM: To perform the curve fitting for the given CP data using MATLAB

CURVE FITTING: Curve fitting the process of construction the curve or a mathematical functions, which process the closest proximity to the real series of data.

GOVERNING EQUATIONS:

OBJECTIVE OF THE PROJECT: The main objective of this project is to determine the best fit for the cp data provided.

The programming language used MATLAB

MATLAB FUNCTIONS:

  • `y=f(x)`
  • `f(x) =3x^2 -2x+1`
  • To create this polynomial in Matlab
  • p=[3 -2 1] this is a row vector of coefficients of the polynomial.
  • `f(1)=3(1)^2 - 2(1)+1`
  • `f(1)=2`
  • This value of a function at any point can be found out by using polyval function
  • y=polyval(p,1) will return the value of the function at x=1.

1.POLYFIT

Fit polynomial to data:

P = POLYFIT(X,Y,N)

finds the coefficients of a polynomial P(X) of degree N that fits the data Y best in a least-squares sense.

2.POLYVAL

Evaluate polynomial:

Y = POLYVAL(P, X) returns the value of a polynomial P evaluated at X.

P is a vector whose elements are the coefficients of the polynomial in descending powers.

The polynomial P is evaluated at all points in X

  1. PLOT

Linear plot.

PLOT(X, Y) plots vector Y versus vector X.

Make sure that lengths of the X and Y vectors are equal.

The programming language used MATLAB

CODE:

The code for the curve fit for the given Temperature vs Specific Heat

clear all
close all
clc

%load the  data to access it

cp_data=load ('data');

%   CURVE FIT
 
 % % Fit a polynomial p of degree 1 to the (temperature,cp) data LINEAR FIT
        temperature = cp_data(:,1);
        cp = cp_data(:,2);
        %polynomial coefficients (p)
        p = polyfit(temperature,cp,1);
 
      % Evaluate the fitted polynomial p and plot CUBIC FIT
        predicted_cp = polyval(p,temperature);
        figure(1)
        plot(temperature,cp,'go',temperature,predicted_cp,'ro')
            xlabel('temperature in K')
            ylabel('cp in kJ/Kg*K')
            title('Temperature vs Specific Heat')
            legend('data','linear fit')
            
            
% Fit a polynomial p of degree 3 to the (temperature,cp) data
 
        %polynomial coefficients (p_1)
        p_1 = polyfit(temperature,cp,3);
         % Evaluate the fitted polynomial p and plot
         predicted_CP =polyval(p_1,temperature);
         figure(2)
           plot(temperature,cp,'ko',temperature,predicted_CP,'yo')
               xlabel('temperature in K')
               ylabel('cp in kJ/Kg*K')
               title(' Temperature vs Specific Heat ')
               legend('data','cubic fit')
               
% comparing the linear and cubic polynomial for data fitting
         figure(3)
         plot(temperature,cp,'ko',temperature,predicted_cp,'ro',temperature,predicted_CP,'go')
         legend('original data','linear fit','cubic fit')
         title('Temperature vs Specific Heat')
           xlabel('temperature in K')
           ylabel('cp in kJ/Kg*K')
         

output:

figure(1)

linear fit

figure(2)

cubic fit

figure(3)

comparison of the data, linear fit and cubic fit.

Splitwise polynomial function for different values of temperature

parameters used to measure the fitness

temperature (it stores all the temperature values >>temperature(1:end))

cp (it stores all the specific heat values >>cp(1:end) )

temperatures(it stores the values >>temp(1:end/2))

temperatures(it stores the values >>temperature(end/2+1:end) )

cp_1(it stores all the specific heat values from>>cp(1:end/2) )

cp_2(it stores all the specific heat values from>>cp(end/2+1:end) )

clear all 
close all
clc
 
cp_data=load('data');
  
        temperature = cp_data(:,1);
        cp = cp_data(:,2);
 
        %splitting the data
 
        % temperature_1=temperature(1:end/2);
        %temperature_2=temperature((end/2 -1):end);
         %cp_1 = cp(1:end/2);
         %cp_2=cp((end/2 -1):end);

  
  %simple linear regression with polyfit

     %part 1
    % Fit a polynomial p of degree 1 to the (temperature,cp) data:
        temperature_1=temperature(1:end/2);
        cp_1 = cp(1:end/2);
        p_1 = polyfit(temperature_1,cp_1,1);
    
        
     %part 2
      % Fit a polynomial p of degree 1 to the (temperature,cp) data:
        temperature_2=temperature((end/2+1):end);
        cp_2 = cp((end/2+1):end);
        p_2 = polyfit(temperature_2,cp_2,1);
        
 
      % Evaluate the fitted polynomial p and plot:
      predicted_cp_1= polyval(p_1,temperature_1);               
         predicted_cp_2= polyval(p_2,temperature_2);
        figure(1)
        plot(temperature_1,cp_1,'go',temperature_1,predicted_cp_1,'bo')
        hold on
        plot(temperature_2,cp_2,'go',temperature_2,predicted_cp_2,'ro')
        legend('data','linear fit','data', 'linear fit')
        xlabel('temperature in K')
        ylabel('specific heat in kJ/Kg*K')
          title('Temperature vs Specific Heat')
        
        
         %simple cubic regression with polyfit

         p_3 = polyfit(temperature_1,cp_1,3);
         p_4= polyfit(temperature_2,cp_2,3);
         
           % Evaluate the fitted polynomial p and plot:
        predicted_cp_3= polyval(p_3,temperature_1);
         predicted_cp_4= polyval(p_4,temperature_2);
        figure(2)
        plot(temperature_1,cp_1,'go',temperature_1,predicted_cp_3,'bo')
        hold on
        plot(temperature_2,cp_2,'go',temperature_2,predicted_cp_4,'ro')
        legend('data','cubic fit','data','cubic fit')
        xlabel('temperature in K')
        ylabel('specific heat in kJ/Kg*K')
          title('Temperature vs Specific Heat')
 
      

output:

figure(1)

linear fit

figure(2)

cubic fit(polynomial fit)

USING cftool interface :

code:

function [fitresult, gof] = createFit(temperature, cp)
    %CREATEFIT(TEMPERATURE,CP)
    %  Create a fit.
    %
    %  Data for 'cftool_interface' fit:
    %      X Input : temperature
    %      Y Output: cp
    %  Output:
    %      fitresult : a fit object representing the fit.
    %      gof : structure with goodness-of fit info.
    %
    %  See also FIT, CFIT, SFIT.
    
    %  Auto-generated by MATLAB on 21-Jun-2020 13:36:30
    
    
    %% Fit: 'cftool_interface'.
    [xData, yData] = prepareCurveData( temperature, cp );
    
    % Set up fittype and options.
    ft = fittype( 'poly3' );
    
    % Fit model to data.
    [fitresult, gof] = fit( xData, yData, ft, 'Normalize', 'on' );
    
    % Plot fit with data.
    figure( 'Name', 'cftool_interface' );
    h = plot( fitresult, xData, yData );
    legend( h, 'cp vs. temperature', 'cftool_interface', 'Location', 'NorthEast', 'Interpreter', 'none' );
    % Label axes
    xlabel( 'temperature', 'Interpreter', 'none' );
    ylabel( 'cp', 'Interpreter', 'none' );
    grid on
    
    

output:

this curve is obtained after normalizing(using centre and scale)

RESULT:

EXPLANATION TO THE CODE:

  1. To use the data file upload it in case of MATLAB online, and to access it using command load filename >>( in this case) load data
  2. Extract the required data from the data file and store it in the desired variables.
  3. Use the polyfit function to create a vector which is basically a vector of polynomial coefficients.
  4. With the help of polyval function calculate the values of function bypassing the input arguments.
  5. Use the range operator ’ : ‘ to pass continuous and large values stored in a variable.
  6. Use the plot function for plotting the data and for comparing the fit
  7. Access the GUI of curve fitting toolbox using the command >>cftool
  8. Manage the degree of a polynomial for good fit and load the data to the command window.
  9. Use generate code option to generate .m file and use it for further.

ERRORS:

1. I did minor errors like typing mistakes.

2. Make sure that while using plot function lengths of the vectors are the same.

HOW TO OVERCOME ERRORS:

  1. Use the debugging tool.
  2. Read the code carefully to avoid spelling mistakes and minor errors.
  3. Understand the errors and go through the line of error as it displays in the command window, that makes work easier.

CONCLUSION:

1. How to make a curve fit perfectly?

The curve fit can be made perfectly by eliminating errors. interpolation and smoothing are one of the examples.

2. How to get the best fit?

the best fit can be chosen by the following methods

  • SSE is the sum of squares due to error of the fit.
  • A value closer to zero indicates a fit that is more useful for prediction
  • R-square is the square of the correlation between the response values and the predicted response values.
  • A value closer to 1 indicates that a greater proportion of variance is accounted for by the model.
  • Adj R-sq is the degrees of freedom adjusted R-square.
  • A value closer to 1 indicates a better fit
  • RMSE is the root mean squared error or standard error.
  • A value closer to 0 indicates a fit that is more useful for prediction.

3. What could be done to improve the cubic fit?

The spread of the temperature values results in scaling problems. To address this problem, you can normalize the temperature data.

Normalization is a process of scaling the predictor data to improve the accuracy of the subsequent numeric computations. A way to normalize temperature is to centre it at zero means and scale it to unit standard deviation.

(temperature - mean(temperature))./std(temperature)

REFERENCES:

MATLAB DOCUMENTATION:https://in.mathworks.com/help/curvefit/curve-fitting.html

skill-Lync article

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.