Open In App

Importing Data in MATLAB

Last Updated : 19 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB provides a simple way of importing data into a script using the importdata() function. This function takes various inputs and can be used in following forms.

Method 1:

This simply takes the data file and creates a suitable struct for the same within the script. 

Example 1:

Matlab




% MATLAB Code for import data
    a = importdata('logo.jpg');
 
% Verifying the data
    image(a)


Output:

This would first load the logo.jpg file as a struct and then, the second statement would display that data as an image to verify the data.

 

Method 2:

Now let us import a file with delimiters and headers. Our data file has the following dummy data with headers and delimiter ‘ ‘.

col1 col2 col3
10.1 12.3 13.7
14.2 13.6 11.9
0.13 1.13 13.1

Example 2: 

Matlab




% Importing this into MATLAB script
% delimiter
    delimiterIn = ' ';   
 
% of header lines
    headerlinesIn = 1;   
 
% Importing the data
    a = importdata('data.txt',delimiterIn, headerlinesIn);
 
% Display the data with headers
  disp(a.colheaders)
  disp(a.data(:,:))


Output:

 

Method 3:

Another method of using the importdata() function is when you do not know the delimiter in the data file. MATLAB does the job for you by determining the delimiter and saving it as a variable for you. See the following snippet.

Data File:

10.1 12.3 13.7
14.2 13.6 11.9
0.13 1.13 13.1

Example 3:

Matlab




% MATLAB Code for import data
[a, delimiterOut] = importdata('data.txt')


Output:

This would store the data in a and the found delimiter in the delimiterOut variable.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads