Main Content

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 frombasic_matrix.xlsinto a matrix.

M = readmatrix('basic_matrix.xls')
M =5×46 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 theandRangeparameters. For example, specify theparameter as'Sheet1'and theRangeparameter as'B1:D3'. Thereadmatrixfunction reads a3-by-3subset 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×38 3 1 4 7 3 6 7 10

Read Spreadsheet Data into Cell Array

Import the mixed tabular data fromairlinesmall_subset.xlsxinto a cell array.

C = readcell('airlinesmall_subset.xlsx'); whosC
Name Size Bytes Class Attributes C 1339x29 4277290 cell

You can also select the data to import from the spreadsheet by specifying theandRangeparameters. For example, specify theparameter as'2007'and theRangeparameter as'G2:I11'. Thereadcellfunction imports ten rows of data for variables in columns7,8, and9, 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 fromairlinesmall_subset.xlsxas separate workspace variables.

[Year,Month,DayOfMonth] = readvars('airlinesmall_subset.xlsx'); whosYearMonthDayOfMonth
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 theandRangeparameters. For example, import ten rows of the columnDayOfMonthfrom the worksheet named'2004'. Specify the column and number of rows using theRangeparameter.

DayOfMonth = readvars('airlinesmall_subset.xlsx','Sheet','2004','Range','C2:C11')
DayOfMonth =10×126 10 21 24 20 20 1 2 30 11

See Also

|||

相关的话题