askvity

How to Read Files in MATLAB?

Published in MATLAB File I/O 5 mins read

Reading files in MATLAB is a common task, and a fundamental method involves opening the file, reading its contents, and then closing the file.

You can read files in MATLAB by following a standard procedure involving the fopen, fscanf, and fclose functions. This approach is particularly useful for reading formatted text data.

Essential Steps for Reading Files

The core process for reading a file in MATLAB typically involves these steps:

  1. Open the File: Establish a connection to the file on disk.
  2. Read Data: Extract the desired information from the file.
  3. Close the File: Release the connection to the file.

Step 1: Opening the File

To begin reading, you must first open the file using the fopen function.

  • Use fopen to open the file, specify the character encoding, and obtain the fileID value.
  • The fileID is a numerical identifier that MATLAB uses to refer to the opened file. It's crucial for subsequent read and close operations.
  • Specifying character encoding (like 'utf-8' or 'latin1') is important for correctly interpreting text data, especially when dealing with non-ASCII characters.

Syntax:

fileID = fopen(filename, permission, encoding);
  • filename: A string specifying the path to the file.
  • permission: A string indicating the mode for opening the file (e.g., 'r' for read, 'w' for write). Use 'r' for reading.
  • encoding: (Optional) A string specifying the character encoding.

Step 2: Reading Data with fscanf

Once the file is open and you have the fileID, you can read data using functions like fscanf.

  • A = fscanf(fileID, formatSpec, sizeA) reads file data into an array, A, with dimensions, sizeA, and positions the file pointer after the last value read.
  • fscanf is designed to read data from a file according to a specified format string.

Syntax:

A = fscanf(fileID, formatSpec, sizeA);
  • fileID: The file identifier obtained from fopen.
  • formatSpec: A string that describes the format of the data to be read (e.g., '%d' for integers, '%f' for floating-point numbers, '%s' for strings).
  • sizeA: (Optional) Specifies the dimensions of the output array A. If omitted, fscanf reads the entire file into a column vector. Common values include inf (read until end-of-file), or [rows, cols].

Step 3: Closing the File

After you have finished reading data from the file, it's essential to close it using the fclose function.

  • When you finish reading, close the file by calling fclose(fileID).
  • Closing the file frees up system resources and ensures that any buffered data is properly handled.

Syntax:

status = fclose(fileID);
  • fileID: The file identifier of the file to close.
  • status: (Optional) Returns 0 on success or -1 on error.

Putting it Together: A Simple Example

Let's say you have a text file named mydata.txt with the following content:

10 20 30
40 50 60

You can read this data into a MATLAB array using the following code:

% Specify the file name
filename = 'mydata.txt';

% Step 1: Open the file for reading
% 'r' is the permission for reading
% 'utf-8' is a common encoding, adjust if needed
fileID = fopen(filename, 'r', 'utf-8');

% Check if file opened successfully
if fileID == -1
    error('Failed to open file: %s', filename);
end

% Step 2: Read the data using fscanf
% '%f' reads floating-point numbers
% [2, 3] specifies the desired size of the output array (2 rows, 3 columns)
% Alternatively, use [3, inf] to read 3 elements per row until end of file
dataArray = fscanf(fileID, '%f', [2, 3]);

% fscanf reads data in column order, so transpose if needed
dataArray = dataArray'; % Transpose to get [10 20 30; 40 50 60]

% Step 3: Close the file
fclose(fileID);

% Display the read data
disp('Data read from file:');
disp(dataArray);

This example demonstrates the core process of opening, reading formatted data with fscanf, and closing the file.

Summary of Key Functions

Function Purpose Reference Information Included?
fopen Opens a file, specifies encoding, and returns a fileID. Yes
fscanf Reads formatted data from a file specified by fileID into an array based on formatSpec and sizeA. Yes
fclose Closes the file associated with fileID. Yes

Beyond fscanf: Other Reading Functions

While fscanf is excellent for reading formatted text, MATLAB offers other functions for different file types and reading needs:

  • fgetl and fgets: Read data one line at a time (useful for reading text line by line).
  • fread: Reads binary data.
  • readtable: Reads data from delimited text files (like CSV) or spreadsheet files into a table (often simpler for structured data).
  • readmatrix: Reads data from delimited text files or spreadsheet files directly into a matrix.
  • importdata: Attempts to load data from a file using functions appropriate for the file type.

Choosing the right function depends on the structure and type of the file you are trying to read. For formatted text files where you need control over the reading format, fopen, fscanf, and fclose provide a robust solution as described in the provided reference.

Remember to always pair fopen with fclose to manage file resources properly.

Related Articles