zaro

How to read string file in MATLAB?

Published in MATLAB File Reading 3 mins read

To read the entire contents of a file into a single character vector (often called a string) in MATLAB, you can use the fileread function.

Understanding fileread

The fileread function is the most direct way to read the complete content of a text file and store it as one continuous string in MATLAB. It's simple, efficient for this specific task, and is based on the information from the reference.

Syntax and Usage

Based on the provided reference, the core syntax for fileread is:

text = fileread( filename )

  • filename: A character vector (string) specifying the path to the file you want to read. This can be a full path or a path relative to the current working directory.
  • text: The output is a character vector containing the entire content of the specified file.

This function reads the file from beginning to end, including any newline characters, and returns everything as a single string.

Example 1: Basic File Reading

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

Hello, world!
This is a test file.

You can read its entire content into a MATLAB string using fileread like this:

file_name = 'my_document.txt'; % Specify the file name
file_content = fileread(file_name); % Read the file content

% Display the content (optional)
disp(file_content);

The variable file_content will now hold the string 'Hello, world!\nThis is a test file.', where \n represents a newline character.

Handling File Encoding

Text files can be saved using different character encodings (like UTF-8, Latin-1, etc.). If your file uses a specific encoding that is different from your system's default, characters might not display correctly when read.

The reference indicates that fileread allows you to specify the encoding:

text = fileread( filename ,Encoding= encoding )

  • Encoding= encoding: This is a name-value pair argument where encoding is a character vector (string) specifying the character encoding to use when reading the file. Common encodings include 'UTF-8', 'windows-1252' (often used for Latin-1), 'Shift_JIS', etc.

Example 2: Specifying Encoding

If your my_document.txt file was saved with UTF-8 encoding, you can ensure it's read correctly by specifying the encoding:

file_name = 'my_document.txt'; % Specify the file name
encoding_type = 'UTF-8';     % Specify the encoding

% Read the file content with specified encoding
file_content_utf8 = fileread(file_name, Encoding= encoding_type);

% Display the content (optional)
disp(file_content_utf8);

Using the Encoding option is particularly important when dealing with files created on different operating systems or those containing special characters from various languages.

By utilizing the fileread function, with or without the Encoding option, you can effectively read the entire contents of a string file into a single variable in MATLAB.