Matlab

How to Read Excel File in MATLAB Using readmatrix() Function

Reading and writing data from a file are widely used tasks performed by all programming languages. Like the others, MATLAB also supports the functionality of reading and writing files having different formats such as Text files, CSV files, Excel files, and many others. It includes a built-in readmatrix() function that makes it easy to read Excel files in MATLAB.

This article is going to present how to read data from the Excel file in MATLAB using the readmatrix() function.

How to Read Data from an Excel File Using readmatrix()

IN MATLAB, we can read data from an Excel file to an array using the readmatrix() function. This function accepts the file name as a necessary input and provides an array that stores data read from the given Excel file.

Syntax
We can implement the readmatrix() function in MATLAB IN the following ways:

A = readmatrix(filename)
A = readmatrix(filename,opts)
A = readmatrix(___,Name,Value)

Here,

  • The function A = readmatrix(filename) is responsible for reading data from an Excel file in the column-oriented form to an array A. If the file contains a mixture of numeric and text data, this function by default reads numeric data and stores it in the array A.
  • The function A = readmatrix(filename,opts) is responsible for reading data from the Excel file by using import options opt.
  • The function A = readmatrix(___,Name,Value) is responsible for reading data from the Excel file into an array by using additional one or more Name,Value pair arguments using any of the previous syntaxes.

Example 1: How to Read Data from the Excel File Using readmatrix() Function?

This MATLAB code reads an Excel file and stores numeric data in the array A.

A = readmatrix("myfile.xlsx")

Example 2: How to Read Data from the Excel File Using Import Options?

In this example, we use the readmatrix() function to read data from the Excel file using the import options by specifying the range for rows and columns.

opts = detectImportOptions('myfile.xlsx');
opts.SelectedVariableNames = [1:4];
opts.DataRange = '1:3';
A = readmatrix('myfile.xlsx',opts)

Example 3: How to Read Data in the Specified Range from the Excel File?

The given example uses the readmatrix() function to read data from the Excel file specifying the given range.

A = readmatrix('myfile.xlsx','Range',[2,4])

Conclusion

MATLAB provides us with many built-in functions like readtable(), readmatrix(), and xlsread(). These functions read data from an excel file according to their functionality. This article has discussed the functionality of the readmatrix() function to read data from an Excel file in MATLAB using different syntaxes and examples.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.