Read Spreadsheet Data into Array or Individual Variables
The best way to represent spreadsheet data in MATLAB® is in a table, which can store a mix of numeric and text data. However, sometimes you need to import spreadsheet data as a matrix, a cell array, or separate variables. Based on your data and the data type you need in the MATLAB® workspace, use one of these functions:
readmatrix
— Import homogeneous numeric or text data as a matrix.readcell
— Import mixed numeric and text data as a cell array.readvars
— Import spreadsheet columns as separate variables.
Read Spreadsheet Data into Matrix
Import numeric data from basic_matrix.xls
into a matrix.
M = readmatrix('basic_matrix.xls')
M = 5×4
6 8 3 1
5 4 7 3
1 6 7 10
4 2 8 2
2 7 5 9
You can also select the data to import from the spreadsheet by specifying the Sheet
and Range
parameters. For example, specify the Sheet
parameter as 'Sheet1'
and the Range
parameter as 'B1:D3'
. The readmatrix
function reads a 3
-by-3
subset of the data, starting at the element in the first row and second column of the sheet named 'Sheet1'
.
M = readmatrix('basic_matrix.xls','Sheet','Sheet1','Range','B1:D3')
M = 3×3
8 3 1
4 7 3
6 7 10
Read Spreadsheet Data into Cell Array
Import the mixed tabular data from airlinesmall_subset.xlsx
into a cell array.
C = readcell('airlinesmall_subset.xlsx'); whos C
Name Size Bytes Class Attributes C 1339x29 4898586 cell
You can also select the data to import from the spreadsheet by specifying the Sheet
and Range
parameters. For example, specify the Sheet
parameter as '2007'
and the Range
parameter as 'G2:I11'
. The readcell
function imports ten rows of data for variables in columns 7
, 8
, and 9
, from the worksheet named '2007'
.
subC = readcell('airlinesmall_subset.xlsx','Sheet','2007','Range','G2:I11')
subC=10×3 cell array
{[ 935]} {[ 935]} {'WN'}
{[1041]} {[1040]} {'WN'}
{[1430]} {[1500]} {'WN'}
{[ 940]} {[ 950]} {'WN'}
{[1515]} {[1515]} {'WN'}
{[2042]} {[2035]} {'WN'}
{[2116]} {[2130]} {'WN'}
{[1604]} {[1605]} {'WN'}
{[1258]} {[1230]} {'WN'}
{[1134]} {[1145]} {'WN'}
Read Spreadsheet Data Columns as Separate Variables
Import the first three columns from airlinesmall_subset.xlsx
as separate workspace variables.
[Year,Month,DayOfMonth] = readvars('airlinesmall_subset.xlsx'); whos Year Month DayOfMonth
Name Size Bytes Class Attributes DayOfMonth 1338x1 10704 double Month 1338x1 10704 double Year 1338x1 10704 double
You can also select which subset to import from the spreadsheet by specifying the Sheet
and Range
parameters. For example, import ten rows of the column DayOfMonth
from the worksheet named '2004'
. Specify the column and number of rows using the Range
parameter.
DayOfMonth = readvars('airlinesmall_subset.xlsx','Sheet','2004','Range','C2:C11')
DayOfMonth = 10×1
26
10
21
24
20
20
1
2
30
11
See Also
readtable
| readmatrix
| readcell
| readvars