Open In App

Curve Fitting in MATLAB

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Curve fitting is the method of finding a suitable equation for a given data or one could say finding a pattern in some random data. The goal of this article is to learn curve fitting using MATLAB thus, it is expected that the reader has knowledge of curve fitting in mathematical terms. 

Step of Curve Fitting:

Step 1: Open a new script in MATLAB and save it with the desired name, to keep the program reusable.

Step 2: If you have a data file then, follow this step else move to step 4. Import the data file by going to the HOME section in the menu and then clicking on Import data.

 

A new window like the following will open up. First, choose the data type as a column vector, select the column you wish to add then, click on import data in the right corner.

 

Now the importing is done and we’d move to the fitting part.

Step 3: Create 2 variables and assign them to the two columns imported in the previous step. You can see the name of those column vectors in the workspace at the left bottom.

 

Step 4: For learning purposes, we would use two vectors x_data and y_data, created in the script and not imported from a data file. However, it has been shown in previous steps how to import data into the script file. Now use the polyfit command to get the coefficients of the equation obtained by fitting. 

Syntax:

coeffs=polyfit(<independent_data>, 

<dependent_data>, <degree_of_equations>)

Step 5: Now we have got a polynomial stored in coeffs. Next, we shall evaluate its value at every point in x_data. This could be done by the polyval command, which evaluates the polynomial at every given data point or range. 

plt=polyval(<polynomial>,<data/data_range>)

Step 6: Now, just plot the graphs with the new polynomial and original data. To plot them both in the same graph, the hold command could be used as follows.

Example:

Matlab




/* MATLAB code for curve fitting */
  
clear
  
/* Input the value of X and Y */
  
x_data=[1,3,5,7,9,11,13,15];
y_data=[4,9,23,37,73,103,133,179];
  
coeffs=polyfit(x_data,y_data,5);
  
plt=polyval(coeffs,x_data);
  
plot(x_data,plt,'r');
  
hold on
  
plot(x_data,y_data,'o');
xlabel('X_ data')
ylabel('Y_ data')
title('Polynomial fitting')
  
hold off


Output:

Example of polynomial fitting of degree 5

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads