Read matrix matlab ошибка

Asked
3 years, 11 months ago

Viewed
9k times

I have a file which is a data set and I want to make a matrix with this :

A = readmatrix(filename)

why I get this error:

  Undefined function or variable 'readmatrix'.

  Error in untitled13 (line 3)
  A = readmatrix('t2.csv')

Notice than the spell of everything has been checked many times!

Cris Luengo's user avatar

Cris Luengo

54.6k9 gold badges61 silver badges119 bronze badges

asked Jun 10, 2019 at 18:28

sherek_66's user avatar

1

Use dlmread instead. You can read more about this function here: dlmread. My guess is that you are using the older version of Matlab (2018 and prior).

The function readmatrix is only available in version 2019 (and later).

answered Jan 5, 2020 at 18:26

Alex Jax's user avatar

Read matrix from file

Since R2019a

Syntax

Description

example

A = readmatrix(filename) creates an array by
reading column-oriented data from a file. The readmatrix function
performs automatic detection of import parameters for your file.

readmatrix determines the file format from the file extension:

  • .txt, .dat, or .csv for
    delimited text files

  • .xls, .xlsb, .xlsm,
    .xlsx, .xltm, .xltx, or
    .ods for spreadsheet files

For files containing mixed numeric and text data, readmatrix imports
the data as a numeric array by default.

example

A = readmatrix(filename,opts)
additionally uses the import options opts.

example

A = readmatrix(___,Name,Value)
creates an array from a file with additional options specified by one or more name-value
pair arguments. Use any of the input arguments from the previous syntaxes before specifying
the name-value pairs.

To set specific import options for your data, you can either use the
opts object or you can specify name-value pairs. When you specify
name-value pairs in addition to opts, then readmatrix
supports only these name-value pairs:

  • Text Files — DateLocale, Encoding

  • Spreadsheet Files — Sheet, UseExcel

Examples

collapse all

Read Matrix from Text File

Display the contents of basic_matrix.txt and then import the data into a matrix.

6,8,3,1
5,4,7,3
1,6,7,10
4,2,8,2
2,7,5,9
M = readmatrix('basic_matrix.txt')
M = 5×4

     6     8     3     1
     5     4     7     3
     1     6     7    10
     4     2     8     2
     2     7     5     9

Read Matrix from Spreadsheet File

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

Read Matrix from Specified Sheet and Range Using Import Options

Preview the data from a spreadsheet file and import numerical data as a matrix from a specified sheet and range.

The spreadsheet file airlinesmall_subset.xlsx contains data in multiple worksheets for years between 1996 and 2008. Each worksheet has data for a given year. Preview the data from file airlinesmall_subset.xlsx. The preview function shows data from the first worksheet by default. The first eight variables in the file contain numerical data.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Configure the values in the opts object to import 10 rows for the first five variables from the worksheet named '2007'.

opts.Sheet = '2007';
opts.SelectedVariableNames = [1:5]; 
opts.DataRange = '2:11';
M = readmatrix('airlinesmall_subset.xlsx',opts)
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Read Matrix from Specified Sheet and Range

Preview the data from a spreadsheet file and import numerical data, as a matrix, from a specified sheet and range.

The spreadsheet file airlinesmall_subset.xlsx contains data in multiple worksheets for years between 1996 and 2008. Each worksheet has data for a given year. Preview the data from file airlinesmall_subset.xlsx. The preview function shows data from the first worksheet by default. The first eight variables in the file contain numerical data.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Import 10 rows of the first 5 variables from the worksheet named '2007'.

M = readmatrix('airlinesmall_subset.xlsx','Sheet','2007','Range','A2:E11')
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Input Arguments

collapse all

filenameName of file to read
character vector | string scalar

Name of the file to read, specified as a character vector or a string scalar.

Depending on the location of your file, filename can take on one of
these forms.

Location

Form

Current folder or folder on the MATLAB® path

Specify the name of the file in
filename.

Example:
'myFile.txt'

File in a folder

If the file is not in the current folder or in a folder on the
MATLAB path, then specify the full or relative path name in
filename.

Example:
'C:myFoldermyFile.xlsx'

Example:
'dataDirmyFile.txt'

Internet URL

If the file is specified as an internet uniform resource locator (URL),
then filename must contain the protocol type
'http://' or
'https://'.

Example:
'http://hostname/path_to_file/my_data.csv'

Remote Location

If the file is stored at a remote location, then
filename must contain the full path of the file specified
with the
form:

scheme_name://path_to_file/my_file.ext

Based on the remote location,
scheme_name can be one of the values in this table.

Remote Location scheme_name
Amazon S3™ s3
Windows Azure® Blob Storage wasb, wasbs
HDFS™ hdfs

For more information, see Work with Remote Data.

Example:
's3://bucketname/path_to_file/my_file.csv'

  • If filename includes the file extension, then the importing
    function determines the file format from the extension. Otherwise, you must specify the
    'FileType' name-value pair arguments to indicate the type of file.

  • On Windows® systems with Microsoft®
    Excel® software, the importing function reads any Excel spreadsheet file format recognized by your version of Excel.

  • If your system does not have Excel for Windows or if you are using MATLAB
    Online™
    , the importing function operates with the UseExcel
    property set to false, and reads only .xls, .xlsx, .xlsm,
    .xltx, and .xltm
    files.

  • For delimited text files, the importing function converts empty fields in the file
    to either NaN (for a numeric variable) or an empty character vector
    (for a text variable). All lines in the text file must have the same number of
    delimiters. The importing function ignores insignificant white space in the file.

Data Types: char | string

optsFile import options
SpreadsheetImportOptions | DelimitedtextImportOptions | FixedWidthImportOptions | XMLImportOptions

File import options, specified as an SpreadsheetImportOptions,
DelimitedTextImportOptions,
FixedWidthImportOptions, or XMLImportOptions
object created by the detectImportOptions function. The
opts object contains properties that control the data import
process. For more information on the properties of each object, see the appropriate
object page.

Name-Value Arguments

Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN, where Name is
the argument name and Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.


Before R2021a, use commas to separate each name and value, and enclose

Name in quotes.

Example: 'NumHeaderLines',5 indicates that the first five lines that
precede the tabular data are header lines.

All Supported File Types

collapse all

WebOptionsHTTP or HTTPS request options
weboptions object

HTTP or HTTPS request options, specified as
a weboptions object. The
weboptions object determines how to import data when the
specified filename is an internet URL containing the protocol type
"http://" or "https://".

Text and Spreadsheet Files

collapse all

FileTypeType of file
'text' | 'spreadsheet'

Type of file, specified as the comma-separated pair consisting of
'FileType' and 'text' or
'spreadsheet'.

Specify the 'FileType' name-value pair argument when the
filename does not include the file extension or if the extension
is other than one of the following:

  • .txt, .dat, or
    .csv for delimited text files

  • .xls, .xlsb,
    .xlsm, .xlsx,
    .xltm, .xltx, or
    .ods for spreadsheet files

Example: 'FileType','text'

Data Types: char | string

Number of header lines in the file, specified as the comma-separated pair consisting of 'NumHeaderLines' and a positive integer. If unspecified, the importing function automatically detects the number of header lines in the file.

Example: 'NumHeaderLines',7

Data Types: single | double

ExpectedNumVariablesExpected number of variables
positive integer

Expected number of variables, specified as the comma-separated pair consisting of
'ExpectedNumVariables' and a positive integer. If unspecified,
the importing function automatically detects the number of variables.

Data Types: single | double

RangePortion of data to read
character vector | string scalar | numeric vector

Portion of the data to read from text or spreadsheet files, specified as the comma
separated pair consisting of 'Range' and a character vector, string
scalar, or numeric vector in one of these forms.

Ways to specify Range Description

Starting Cell

'Cell' or
[row col]

Specify the starting cell for the data as a character vector or
string scalar or a two element numeric vector.

  • Character vector or string scalar containing a column
    letter and row number using Excel
    A1 notation. For example,
    A5 is the identifier for the cell
    at the intersection of column A and
    row 5.

  • Two element numeric vector of the form [row
    col]
    indicating the starting row and
    column.

Using the starting cell, the importing function
automatically detects the extent of the data by beginning the import
at the start cell and ending at the last empty row or footer
range.

Example:
'A5' or [5 1]

Rectangular
Range

'Corner1:Corner2' or
[r1 c1 r2 c2]

Specify the exact range to read using the rectangular range in
one of these forms.

  • 'Corner1:Corner2' — Specify the
    range using Corner1 and
    Corner2 which are the two
    opposing corners that define the region to read in
    Excel
    A1 notation. For example,
    'C2:N15'.

  • [r1 c1 r2 c2] — Specify the range
    using a four element numeric vector containing
    start-row, start-column, end-row, and end-column. For
    example, [2 3 15 13].

The importing function only reads the
data contained in the specified range. Any empty fields within the
specified range are imported as missing cells.

Row Range or Column
Range

'Row1:Row2' or
'Column1:Column2'

Specify the range by identifying the beginning and ending rows
using Excel row numbers.

Using the specified row
range, the importing function automatically detects the column
extent by reading from the first nonempty column to the end of the
data, and creates one variable per column.

Example:
'5:500'

Alternatively, specify the
range by identifying the beginning and ending columns using
Excel column letters or numbers.

Using the
specified column range, the import function automatically detects
the row extent by reading from the first nonempty row to the end of
the data or the footer range.

The number of columns in
the specified range must match the number specified in the
ExpectedNumVariables
property.

Example:
'A:K'

Starting Row
Number

n

Specify the first row containing the data using the positive
scalar row index.

Using the specified row index, the
importing function automatically detects the extent of the data by
reading from the specified first row to the end of the data or the
footer range.

Example:5

Excel’s Named
Range

'NamedRange'

In Excel, you can create names to identify ranges in the
spreadsheet. For instance, you can select a rectangular portion of
the spreadsheet and call it 'myTable'. If such
named ranges exist in a spreadsheet, then the importing function can
read that range using its name.

Example:
'Range','myTable'

Unspecified or
Empty

''

If unspecified, the importing function automatically detects
the used range.

Example:
'Range',''

Note:
Used Range refers to the rectangular portion of
the spreadsheet that actually contains data. The importing function
automatically detects the used range by trimming any leading and
trailing rows and columns that do not contain data. Text that is
only white space is considered data and is captured within the used
range.

Data Types: char | string | double

TreatAsMissing Text to interpret as missing data
character vector | string scalar | cell array of character vectors | string array

Text to interpret as missing data, specified as a character vector, string scalar, cell array
of character vectors, or string array.

Example: 'TreatAsMissing',{'NA','TBD'} instructs the importing function to treat any occurrence of NA or TBD as a missing fields.

Data Types: char | string | cell

OutputTypeOutput data type
character vector | string scalar

Output data type, specified as the comma-separated pair consisting of
'OutputType' and a character vector or string scalar containing
name of any of the data types in this table.

Type of Data Output data type
Numeric 'uint8', 'int8',
'int16', 'int32',
'int64', 'uint16',
'uint32', 'uint64',
'single', or 'double'
Text 'char' or 'string'
Other types 'datetime', 'duration', or
'categorical'

Example: 'OutputType','uint8'

Data Types: char | string

Text Files Only

collapse all

Field delimiter characters in a delimited text file, specified as a string array,
character vector, or cell array of character vectors.

Example: "Delimiter","|"

Example: "Delimiter",[";","*"]

Characters to treat as white space, specified as a character vector or string scalar
containing one or more characters.

Example: 'Whitespace',' _'

Example: 'Whitespace','?!.,'

End-of-line characters, specified as a string array, character vector, or cell array of
character vectors.

Example: "LineEnding","n"

Example: "LineEnding","rn"

Example: "LineEnding",["b",":"]

Style of comments, specified as a string array, character vector, or cell array of
character vectors. For single- and multi-line comments, the starting identifier must be
the first non-white-space character. For single-line comments, specify a single
identifier to treat lines starting with the identifier as comments. For multi-line
comments, lines from the starting (first) identifier to the ending (second) identifier
are treated as comments. No more than two character vectors of identifiers can be
specified.

For example, to ignore the line following a percent symbol as the first
non-white-space character, specify CommentStyle as
"%".

Example: "CommentStyle",["/*"]

Example: "CommentStyle",["/*","*/"]

EncodingCharacter encoding scheme
'UTF-8' | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | …

Character encoding scheme associated with the file, specified as the
comma-separated pair consisting of 'Encoding' and
'system' or a standard character encoding scheme name. When you
do not specify any encoding, the readmatrix function uses
automatic character set detection to determine the encoding when reading the
file.

If you specify the 'Encoding' argument in addition to the
import options, then the readmatrix function uses the specified
value for 'Encoding', overriding the encoding defined in the import
options.

Example: 'Encoding','UTF-8' uses UTF-8 as the
encoding.

Example: 'Encoding','system' uses the system default
encoding.

Data Types: char | string

DateLocaleLocale for reading dates
character vector | string scalar

Locale for reading dates, specified as the comma-separated pair consisting of
'DateLocale' and a character vector or a string scalar of the
form xx_YY, where:

  • YY is an uppercase ISO 3166-1 alpha-2 code
    indicating a country.

  • xx is a lowercase ISO 639-1 two-letter code
    indicating a language.

This table lists some common values for the locale.

Locale Language Country
'de_DE' German Germany
'en_GB' English United Kingdom
'en_US' English United States
'es_ES' Spanish Spain
'fr_FR' French France
'it_IT' Italian Italy
'ja_JP' Japanese Japan
'ko_KR' Korean Korea
'nl_NL' Dutch Netherlands
'zh_CN' Chinese (simplified) China

When using the %D format specifier to read text as
datetime values, use DateLocale to specify the
locale in which the importing function should interpret month and day-of-week names and
abbreviations.

If you specify the DateLocale argument in addition to
opts the import options, then the importing function uses the
specified value for the DateLocale argument, overriding the locale
defined in the import options.

Example: 'DateLocale','ja_JP'

Characters indicating the decimal separator in numeric variables, specified as a character
vector or string scalar. The importing function uses the characters specified in the
DecimalSeparator name-value pair to distinguish the integer part
of a number from the decimal part.

When converting to integer data types, numbers with a decimal
part are rounded to the nearest integer.

Example: If name-value pair is specified as 'DecimalSeparator',',', then the
importing function imports the text "3,14159" as the number
3.14159.

Data Types: char | string

Characters that indicate the thousands grouping in numeric variables, specified as a
character vector or string scalar. The thousands grouping characters act as visual
separators, grouping the number at every three place values. The importing function uses
the characters specified in the ThousandsSeparator name-value pair to
interpret the numbers being imported.

Example: If name-value pair is specified as
'ThousandsSeparator',',', then the importing function imports the
text "1,234,000" as 1234000.

Data Types: char | string

TrimNonNumericRemove nonnumeric characters
false (default) | true

Remove nonnumeric characters from a numeric variable, specified as a logical true or false.

Example: If name-value pair is specified as 'TrimNonNumeric',true, then the
importing function reads '$500/-' as
500.

Data Types: logical

Procedure to manage consecutive delimiters in a delimited text file,
specified as one of the values in this table.

Value Behavior
"split" Split the consecutive delimiters into
multiple fields.
"join" Join the delimiters into one
delimiter.
"error" Return an error and cancel the import
operation.

Procedure to manage leading delimiters in a delimited text file, specified as one of the
values in this table.

Value Behavior
"keep" Keep the delimiter.
"ignore" Ignore the delimiter.
"error" Return an error and cancel the import operation.

TrailingDelimitersRuleProcedure to manage trailing delimiters
'keep' | 'ignore' | 'error'

Procedure to manage trailing delimiters in a delimited text file, specified as one
of the values in this table.

Leading Delimiters Rule Behavior
'keep' Keep the delimiter.
'ignore' Ignore the delimiter.
'error' Return an error and abort the import operation.

Spreadsheet Files Only

collapse all

Sheet to read from, specified as an empty character array, a character vector or string scalar
containing the sheet name, or a positive scalar integer denoting the sheet
index. Based on the value specified for the Sheet
property, the import function behaves as described in the table.

Specification Behavior
'' (default) Import data from the first sheet.
Name Import data from the matching sheet name,
regardless of order of sheets in the spreadsheet file.
Integer Import data from sheet in the position denoted by the integer,
regardless of the sheet names in the spreadsheet file.

Data Types: char | string | single | double

UseExcelFlag to start instance of Microsoft Excel for Windows
false (default) | true

Flag to start an instance of Microsoft
Excel
for Windows when reading spreadsheet data, specified as the comma-separated pair consisting of 'UseExcel' and either true, or false.

You can set the 'UseExcel' parameter to one of these values:

  • true — The importing function starts an instance of
    Microsoft
    Excel when reading the
    file.

  • false — The importing function does not start an
    instance of Microsoft
    Excel when reading the file. When
    operating in this mode, the importing function functionality differs in the
    support of file formats and interactive features, such as formulas and
    macros.

UseExcel

true

false

Supported file formats

.xls, .xlsx, .xlsm, .xltx, .xltm, .xlsb, .ods

.xls, .xlsx, .xlsm, .xltx, .xltm

Support for interactive features, such as formulas and macros

Yes

No

When reading from spreadsheet files on Windows platforms, if you want to start an instance of Microsoft
Excel
, then set the 'UseExcel' parameter to
true.

Version History

Introduced in R2019a

In this Insight, I’ll go over 5 common MATLAB error messages, what they mean, and how to fix them. Hopefully, after reading this post you’ll find yourself being more productive, and maybe even help your friends with their code.

Most forums online where people post MATLAB questions generate quite a bit of duplicates, and PhysicsForums is no exception. The fact is, there are just certain situations that come up constantly in MATLAB, and if you’re a newer user, don’t consider yourself a programmer, or haven’t used the software in a while, then you’re likely to get tripped up and receive one of those red error messages. It can be especially frustrating when the message doesn’t make sense to you, or your best efforts to fix it come up dry.

Table of Contents

1

1. Error using * Inner matrix dimensions must agree.

By far the most common error message I see posted about by new users is this one. They create a few matrices or vectors and just go to multiply them with A*B, and this message is returned. Some example code that produces this message is:

A = [1 2 3];
B = [4 5 6];
A*B
Error using * 
Inner matrix dimensions must agree.

The key to this error message is usually that people are not aware of the elementwise operators in MATLAB. The * operator performs matrix multiplication, where an NxM matrix is multiplied by an MxP matrix, resulting in an NxP matrix. Notice how those matrices have the common dimension “M”? That’s where this message comes from; it’s a common inner dimension.

Most often, you simply need to use .* instead of * to perform the elementwise multiplication, where corresponding elements are multiplied and the result is the same size as the inputs.

A.*B

ans =

     4    10    18

For more information about the different MATLAB operators, see Array vs. Matrix Operations. Note that even though this error message is the most common in this situation (since, well, multiplication is pretty popular) there are similar messages for the misuse of ^,   /, and     as opposed to .^, ./, and   ..

2. Index exceeds matrix dimensions.

Quite simply, this error arises when you try to reference an element that doesn’t exist. For example, if the matrix has N elements, and you try to index into the N+1 element:

A = magic(5)
A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

A(26)
Index exceeds matrix dimensions.

To fix this error, double-check that the matrix is the size you were expecting it to be and that the index you’re using is also what you expect. For example, if the index is the result of a calculation or is part of a loop, then you might need to adjust the calculation of the number of loop iterations. Some useful functions to check sizes and number of elements are numel(), size(), and length().

3. Subscript indices must either be real positive integers or logicals.

The most common reason this message arises is that people come to MATLAB from other programming languages and can’t get used to the fact that MATLAB indexing begins at 1. A(1) is the first element in a vector or matrix (or equivalently A(1,1)), not A(0) like in other programming languages!

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(0)
Subscript indices must either be real positive integers or logicals.

There are a number of theories for why MATLAB uses 1-based indexing, but ultimately the answer is pretty simple. 1-based indexing is the language of Mathematics, as confirmed by Cleve Moler himself in a comment on this April Fools blog post.

We have always had BOTH 0-based indexing and 1-based indexing. In order to distinguish between the two, 0-based indices are followed by “+1″. The 1-based indices are preferred becaused they are the language of mathematics. — Cleve

I won’t expound on this anymore, but suffice it to say if you’re interested in this, a quick google search will turn up bountiful results, as it has a long and contentious history!

This error message can also arise if you use a noninteger (or negative) value to index. What is MATLAB supposed to do with A(1.5) or A(-3)? In this context, it’s again likely that you’ll want to check the bounds of any loop statements in your code to make sure they aren’t producing decimal or negative values for indexing.

4. The expression to the left of the equals sign is not a valid target for an assignment.

This error message arises because of misuse of the = and == operators. The = operator does an assignment, and the == operator does a logical test for equality. In the context of an if statement, for example, the if operator is expecting to see a logical condition to determine whether to continue executing code. So the following example code produces this error:

n = 5;
if n = 4
    n = n.^2;
end
 if n = 4
      |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

To fix this all you need to do is use == instead:

n = 5;
if n == 4
    n = n.^2;
end

This code outlines the differences between the two operators more clearly:

A = 1:5
A =

     1     2     3     4     5

B = 5;
A == B
ans =

     0     0     0     0     1

C = A == B
C =

     0     0     0     0     1

In short: when you need to compare values, use ==. When you want to assign a value, use =.

5. Subscripted assignment dimension mismatch.

This error message arises because of an attempt to assign a vector or matrix into a compartment that it does not fit in. The dimension of the subscripted elements does not match the dimension of the assignment. For example, you cannot assign the first element in a matrix to be a vector, because there is only room for 1 element:

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(1) = [4 5 6]
Subscripted assignment dimension mismatch.

This error can be much more subtle when you’re working with large matrices or loops, and it can occur because of a mismatch on either side of the equals sign. Sometimes the size of a vector or matrix can grow in an unexpected way in a loop, and you’ll receive this message and wonder what went wrong. The best way to debug this error is to double-check that all of your assignments are the sizes you expect them to be and that your matrices are growing (or not) as you expect them to.

If you don’t have any loops, just break the statement apart and check the size of each side. You won’t get this error if the sizes match exactly:

size(A(1:3))
ans =

     1     3

size([4 5 6])
ans =

     1     3

A(1:3) = [4 5 6]
A =

     4     1     6
     5     5     7
     6     9     2

Feedback

Obviously, I could go on with another 25 error messages, but I think these are the most common ones I see people posting about. If you’re interested in reading about some others, check out this link:

http://en.wikibooks.org/wiki/MATLAB_Programming/Error_Messages

Post about your favorite or least favorite MATLAB error messages in the comments, and let me know what you think!

Disclaimer: All views and/or opinions expressed in this post are my own, and should not be interpreted in any other way.

Josh received a BA in Physics from Clark University in 2009, and an MS in Physics from SUNY Albany in 2012. He currently works as a technical writer for MathWorks, where he writes documentation for MATLAB.

Не называйте переменную с именем существующей функции

Уже существует функция sum() . В результате, если мы будем называть переменную с тем же именем

sum = 1+3;

и если мы попытаемся использовать эту функцию, пока переменная все еще существует в рабочей области

A = rand(2);
sum(A,1)

мы получим загадочную ошибку :

Subscript indices must either be real positive integers or logicals.

сначала clear() переменную, а затем используйте функцию

clear sum

sum(A,1)
ans =
       1.0826       1.0279

Как мы можем проверить, существует ли функция, чтобы избежать этого конфликта?

Используйте which() с флагом -all :

which sum -all
sum is a variable.
built-in (C:Program FilesMATLABR2016atoolboxmatlabdatafun@doublesum)   % Shadowed double method
...

Этот вывод говорит нам, что sum является первой переменной и что следующие методы (функции) затенены ею, то есть MATLAB сначала попытается применить наш синтаксис к переменной, а не использовать этот метод.

То, что вы видите, НЕ является тем, что вы получаете: char vs cellstring в окне команд

Это основной пример, нацеленный на новых пользователей. Он не фокусируется на объяснении разницы между char и cellstring .


Может случиться так, что вы хотите избавиться от ' в ваших строках», хотя вы никогда их не добавляли. Фактически, это артефакты, которые используется в командном окне для различения некоторых типов.

Строка будет печатать

s = 'dsadasd'
s =
dsadasd

Ячейка будет печатать

c = {'dsadasd'};
c = 
    'dsadasd'

Обратите внимание, что одиночные кавычки и отступы являются артефактами, чтобы уведомить нас о том, что c — это cellstring а не char . Строка фактически содержится в ячейке, т. Е.

c{1}
ans =
dsadasd

Операторы транспонирования

  • .' является правильным способом транспонировать вектор или матрицу в MATLAB.
  • ' — правильный способ взять комплексно-сопряженную транспозицию (ака эрмитово сопряженную) вектора или матрицы в MATLAB.

Обратите внимание, что для транспонирования .' , перед апострофом существует период . Это согласуется с синтаксисом для других элементарных операций в MATLAB: * умножает матрицы , .* умножает элементы матриц вместе. Обе команды очень похожи, но концептуально очень разные. Как и другие команды MATLAB, эти операторы являются «синтаксическим сахаром», который во время выполнения превращается в «правильный» вызов функции. Подобно тому, как == становится оценкой функции eq , подумайте .' как сокращенное обозначение для transpose . Если бы вы только пишете ' (без точки), вы фактически используете команду ctranspose , которая вычисляет сложную сопряженную транспозицию , которая также известна как эрмитова сопряженная , часто используемая в физике. Пока транспонированный вектор или матрица вещественны, оба оператора производят одинаковый результат. Но как только мы будем заниматься сложными числами , мы неизбежно столкнемся с проблемами, если не будем использовать «правильную» стенографию. Что «правильно» зависит от вашего приложения.

Рассмотрим следующий пример матрицы C содержащей комплексные числа:

>> C = [1i, 2; 3*1i, 4]
C =
   0.0000 + 1.0000i   2.0000 + 0.0000i
   0.0000 + 3.0000i   4.0000 + 0.0000i

Возьмем транспонирование, используя сокращенное выражение .' (с периодом). Выход такой, как ожидалось, транспонированная форма C

>> C.'
ans =
   0.0000 + 1.0000i   0.0000 + 3.0000i
   2.0000 + 0.0000i   4.0000 + 0.0000i

Теперь давайте использовать ' (без периода). Мы видим, что в дополнение к транспозиции комплексные значения также трансформируются в их комплексные сопряжения .

>> C'
ans =
   0.0000 - 1.0000i   0.0000 - 3.0000i
   2.0000 + 0.0000i   4.0000 + 0.0000i

Подводя итог, если вы намереваетесь рассчитать эрмитовское сопряженное, комплексно-сопряженное транспонирование, то используйте ' (без периода). Если вы просто хотите вычислить транспонирование без комплексного сопряжения значений, используйте .' (с периодом).

Неопределенная функция или метод X для входных аргументов типа Y

Это длинный способ MATLAB сказать, что он не может найти функцию, которую вы пытаетесь вызвать. Существует несколько причин, по которым вы можете получить эту ошибку:

Онлайн-документация MATLAB обеспечивает очень приятную функцию, которая позволяет вам определить, в какой версии была введена данная функция. Он расположен в левом нижнем углу каждой страницы документации:

введите описание изображения здесь

Сравните эту версию с вашей текущей версией ( ver ), чтобы определить, доступна ли эта функция в вашей конкретной версии. Если это не так, попробуйте найти архивные версии документации, чтобы найти подходящую альтернативу в своей версии.

У вас нет этого инструментария!

Базовая установка MATLAB имеет большое количество функций; однако более специализированные функциональные возможности упакованы в панели инструментов и продаются отдельно Mathworks. Документация для всех панелей инструментов видна, есть ли у вас панель инструментов или нет, поэтому обязательно проверьте и посмотрите, есть ли у вас соответствующий набор инструментов.

Чтобы проверить, к какой панели инструментов принадлежит данная функция, посмотрите в левом верхнем углу интерактивной документации, чтобы узнать, указан ли конкретный набор инструментов.

введите описание изображения здесь

Затем вы можете определить, какие панели инструментов установлены вашей версией MATLAB, выпустив команду ver которая выведет список всех установленных наборов инструментов.

Если у вас нет установленного набора инструментов и вы хотите использовать эту функцию, вам нужно будет приобрести лицензию для этого конкретного инструментария из The Mathworks.

Если MATLAB все еще не может найти вашу функцию, то она должна быть определяемой пользователем. Возможно, что он живет в другом каталоге и этот каталог должен быть добавлен в путь поиска для запуска вашего кода. Вы можете проверить , может ли MATLAB найти вашу функцию с помощью which , которая должна возвращать путь к исходному файлу.

Помните о неточности с плавающей запятой

Числа с плавающей запятой не могут представлять все действительные числа. Это известно как неточность с плавающей запятой.

Существует бесконечно много чисел с плавающей запятой, и они могут быть бесконечно длинными (например, π ), поэтому возможность их представления идеально потребует бесконечного количества памяти. Увидев это, возникла проблема, было разработано специальное представление для хранения «реального числа» в компьютере, стандарт IEEE 754 . Короче говоря, он описывает, как компьютеры хранят этот тип чисел с показателем и мантиссой,

floatnum = sign * 2^exponent * mantissa

При ограниченном количестве бит для каждого из них может быть достигнута только конечная точность. Чем меньше число, тем меньше разрыв между возможными числами (и наоборот!). Вы можете попробовать свои реальные цифры в этом онлайн-демо .

Помните об этом и старайтесь избегать сравнения с плавающей точкой и их использования в качестве условий остановки в циклах. Ниже приведены два примера:

Примеры: сравнение плавающих точек WRONG:

>> 0.1 + 0.1 + 0.1  == 0.3

ans =

  logical

   0

Плохая практика заключается в использовании сравнения с плавающей запятой, как показано в примере с прецедентом. Вы можете преодолеть это, взяв абсолютную величину их разницы и сравнив ее с (малым) уровнем допуска.

Ниже приведен еще один пример, где число с плавающей запятой используется как условие остановки в цикле while: **

k = 0.1;
while k <= 0.3 
  disp(num2str(k));
  k = k + 0.1;
end

% --- Output: ---
0.1
0.2

Он пропускает последний ожидаемый цикл ( 0.3 <= 0.3 ).

Пример: Выполнено сравнение с плавающей запятой. RIGHT:

x = 0.1 + 0.1 + 0.1;
y = 0.3;
tolerance = 1e-10; % A "good enough" tolerance for this case.

if ( abs( x - y ) <= tolerance )
  disp('x == y');
else
  disp('x ~= y');
end

% --- Output: ---
x == y

Несколько замечаний:

  • Как и ожидалось, теперь x и y рассматриваются как эквивалентные.
  • В приведенном выше примере выбор допуска выполнялся произвольно. Таким образом, выбранное значение может не подходить для всех случаев (особенно при работе с гораздо меньшими номерами). Выбор метода разумно может быть выполнен с использованием функции eps , т. N*eps(max(x,y)) , где N — некоторое конкретное заданное число. Разумным выбором для N , который также является достаточно разрешительным, является 1E2 (хотя в приведенной выше проблеме N=1 также будет достаточно).

Дальнейшее чтение:

См. Эти вопросы для получения дополнительной информации о неточности с плавающей запятой:

  • Почему 24.0000 не равно 24.0000 в MATLAB?
  • Сбита ли математика с плавающей запятой?

Недостаточно входных аргументов

Часто начинающие разработчики MATLAB будут использовать редактор MATLAB для написания и редактирования кода, в частности пользовательских функций с входами и выходами. В верхней части есть кнопка « Выполнить» , которая доступна в последних версиях MATLAB:

введите описание изображения здесь

Как только разработчик заканчивается кодом, они часто испытывают желание нажать кнопку « Запустить» . Для некоторых функций это будет работать нормально, но для других они получат ошибку Недопустимые Not enough input arguments и будут озадачены тем, почему возникает ошибка.

Причина, по которой эта ошибка может не произойти, заключается в том, что вы написали сценарий MATLAB или функцию, которая не принимает входных аргументов. С помощью кнопки Run запускается тестовый скрипт или запускается функция, не принимающая входных аргументов. Если для вашей функции требуются входные аргументы, ошибка « Not enough input arguments будет возникать, поскольку вы написали функции, которые ожидают ввода входных данных внутри функции. Поэтому вы не можете ожидать, что функция будет работать, просто нажав кнопку « Выполнить» .

Чтобы продемонстрировать эту проблему, предположим, что у нас есть функция mult которая просто умножает две матрицы вместе:

function C = mult(A, B)
    C = A * B;
end

В последних версиях MATLAB, если вы написали эту функцию и нажали кнопку « Запустить» , она даст вам ожидаемую ошибку:

>> mult
Not enough input arguments.

Error in mult (line 2)
    C = A * B;

Существует два способа решить эту проблему:

Метод №1 — с помощью командной строки

Просто создайте нужные вам данные в командной строке, затем запустите функцию, используя созданные вами входы:

A = rand(5,5);
B = rand(5,5);
C = mult(A,B);

Метод № 2 — Интерактивно через редактор

Под кнопкой « Выполнить» находится темная черная стрелка. Если вы нажмете на эту стрелку, вы можете указать переменные, которые хотите получить из рабочего пространства MATLAB, набрав способ, которым вы хотите вызвать функцию, точно так же, как вы видели в методе # 1. Убедитесь, что переменные, которые вы указываете внутри функции, существуют в рабочей области MATLAB:

Следите за изменениями размера массива

Некоторые общие операции в MATLAB, такие как дифференциация или интеграция , выводят результаты, которые имеют различное количество элементов, чем входные данные. Этот факт можно легко упускать из виду, что, как правило, вызывает ошибки, такие как Matrix dimensions must agree . Рассмотрим следующий пример:

t = 0:0.1:10;        % Declaring a time vector
y = sin(t);          % Declaring a function

dy_dt = diff(y);     % calculates dy/dt for y = sin(t)

Предположим, мы хотим построить эти результаты. Мы рассмотрим размеры массива и посмотрим:

size(y) is 1x101
size(t) is 1x101

Но:

size(dy_dt) is 1x100

Массив на один элемент короче!

Теперь представьте, что у вас есть данные измерений позиций с течением времени и вы хотите вычислить jerk (t) , вы получите массив на 3 элемента меньше, чем временный массив (потому что рывок является дифференцированным положением 3 раза).

vel = diff(y);       % calculates velocity vel=dy/dt for y = sin(t)  size(vel)=1x100
acc = diff(vel);     % calculates acceleration acc=d(vel)/dt         size(acc)=1x99
jerk = diff(acc);    % calculates jerk jerk=d(acc)/dt                size(jerk)=1x98   

И тогда операции вроде:

x = jerk .* t;          % multiplies jerk and t element wise

возвращают ошибки, поскольку размеры матрицы не согласуются.

Чтобы вычислить такие операции, как описано выше, вам необходимо настроить размер массива большего размера, чтобы он соответствовал меньшему. Вы также можете запустить регрессию ( polyfit ) с вашими данными, чтобы получить многочлен для ваших данных.

Ошибки несоответствия размеров

Ошибки несоответствия размеров обычно появляются, когда:

  • Не обращая внимания на форму возвращаемых переменных из вызовов функций / методов. Во многих встроенных функциях MATLAB матрицы преобразуются в векторы для ускорения вычислений, а возвращаемая переменная может быть вектором, а не ожидаемой матрицей. Это также распространенный сценарий, когда задействована логическая маскировка .
  • Использование несовместимых размеров массива при вызове неявного расширения массива .

Использование «i» или «j» в качестве мнимой единицы, индексов цикла или общей переменной.

Рекомендация

Поскольку символы i и j могут представлять существенно разные вещи в MATLAB, их использование в качестве индексов цикла разделило сообщество пользователей MATLAB с возрастом. Хотя некоторые исторические соображения производительности могут помочь балансу опираться на одну сторону, это уже не так, и теперь выбор полностью зависит от вас и методов кодирования, которые вы выбираете.

В настоящее время официальными рекомендациями Mathworks являются:

  • Поскольку i является функцией, ее можно переопределить и использовать в качестве переменной. Однако лучше избегать использования i и j для имен переменных, если вы собираетесь использовать их в сложной арифметике.
  • Для скорости и улучшенной устойчивости в сложной арифметике используйте 1i и 1j вместо i и j .

По умолчанию

В MATLAB по умолчанию буквы i и j являются встроенными именами function , которые оба относятся к мнимой единице в сложном домене.

Таким образом, по умолчанию i = j = sqrt(-1) .

>> i
ans =
   0.0000 + 1.0000i
>> j
ans =
   0.0000 + 1.0000i

и как и следовало ожидать:

>> i^2
ans =
    -1

Используя их как переменную (для индексов цикла или другой переменной)

MATLAB позволяет использовать встроенное имя функции в качестве стандартной переменной. В этом случае используемый символ больше не будет указывать на встроенную функцию, а на вашу собственную пользовательскую переменную. Однако эта практика обычно не рекомендуется, так как это может привести к путанице, сложной отладке и обслуживанию ( см. Другой пример do-not-name-a-variable-with-an-existing-function-name ).

Если вы глубоко педантичны относительно соблюдения конвенций и лучших практик, вы избежите использовать их в качестве индексов цикла на этом языке. Тем не менее, это разрешено компилятором и совершенно функционально, поэтому вы также можете сохранить старые привычки и использовать их в качестве итераторов цикла.

>> A = nan(2,3);
>> for i=1:2        % perfectly legal loop construction
       for j = 1:3
        A(i, j) = 10 * i + j;
       end
   end

Обратите внимание, что индексы цикла не заканчиваются в конце цикла, поэтому они сохраняют новое значение.

>> [ i ; j ]
ans =
     2
     3

Если вы используете их как переменную, убедитесь, что они инициализированы до их использования. В цикле над MATLAB они автоматически инициализируют их при подготовке цикла, но если они не инициализированы правильно, вы можете быстро увидеть, что вы можете непреднамеренно ввести в свой результат complex числа.

Если позже, вам нужно отменить затенение встроенной функции (=, например, вы хотите, чтобы i и j отображали мнимую единицу снова), вы можете clear переменные:

>> clear i j

Теперь вы понимаете, что резервирование Mathworks позволяет использовать их в качестве индексов цикла, если вы собираетесь использовать их в сложной арифметике . Ваш код будет пронизан переменными инициализациями и clear командами, лучшим способом сбить с толку самого серьезного программиста ( да, вы там! … ) и аварийных программ, ожидающих своего появления.

Если ожидаемая сложная арифметика не ожидается, использование i и j вполне функционально, и нет штрафа за производительность.


Используя их как мнимую единицу:

Если ваш код должен иметь дело со complex числами, то i и j , безусловно, пригодится. Однако для устранения неоднозначности и даже для выступлений рекомендуется использовать полную форму вместо сокращенного синтаксиса. Полная форма равна 1i (или 1j ).

>> [ i ; j ; 1i ; 1j]
ans =
   0.0000 + 1.0000i
   0.0000 + 1.0000i
   0.0000 + 1.0000i
   0.0000 + 1.0000i

Они представляют одно и то же значение sqrt(-1) , но более поздняя форма:

  • более явным, семантическим образом.
  • (кто-то, смотрящий на ваш код позже, не должен будет читать код, чтобы узнать, является ли i или j переменной или мнимой единицей).
  • быстрее (источник: Mathworks).

Обратите внимание, что полный синтаксис 1i действителен с любым числом, предшествующим символу:

>> a = 3 + 7.8j
a =
   3.0000 + 7.8000i

Это единственная функция, с которой вы можете придерживаться номера без оператора между ними.


Ловушки

Хотя их использование в качестве мнимой единицы ИЛИ переменной является совершенно законным, вот лишь небольшой пример того, как путаница могла бы возникнуть, если оба метода получаются смешанными:

Давайте переопределим i и сделаем его переменной:

>> i=3
i =
     3

Теперь iпеременная (удерживающая значение 3 ), но мы только преувеличиваем сокращенную нотацию мнимой единицы, полная форма по-прежнему интерпретируется правильно:

>> 3i
ans =
   0.0000 + 3.0000i

Что теперь позволяет нам строить самые неясные формулировки. Позвольте вам оценить читаемость всех следующих конструкций:

>> [ i ; 3i ; 3*i ; i+3i ; i+3*i ]
ans =
   3.0000 + 0.0000i
   0.0000 + 3.0000i
   9.0000 + 0.0000i
   3.0000 + 3.0000i
  12.0000 + 0.0000i

Как вы можете видеть, каждое значение в массиве выше возвращает другой результат. Хотя каждый результат действителен (при условии, что это было первоначальное намерение), большинство из вас признают, что было бы хорошим кошмаром прочитать код, пронизанный такими конструкциями.

Использование `length` для многомерных массивов

В распространенной ошибке кодеры MATLAB используют функцию length для матриц (в отличие от векторов , для которых она предназначена). Функция length , как указано в ее документации , « возвращает длину наибольшего размера массива » ввода.

Для векторов возвращаемое значение length имеет два разных значения:

  1. Общее число элементов в векторе.
  2. Наибольшая размерность вектора.

В отличие от векторов, приведенные выше значения не будут равны для массивов более чем одного не-одиночного (т. Е. Размера которого больше 1 ). Вот почему использование length для матриц неоднозначно. Вместо этого рекомендуется использовать одну из следующих функций, даже при работе с векторами, чтобы сделать код совершенно понятным:

  1. size(A) — возвращает вектор строки, элементы которого содержат количество элементов вдоль соответствующего размера A
  2. numel(A) — возвращает количество элементов в A Эквивалентен prod(size(A)) .
  3. ndims(A) — возвращает количество измерений в массиве A Эквивалент numel(size(A)) .

Это особенно важно при написании «перспективных», векторизованных библиотечных функций, входы которых неизвестны заранее и могут иметь различные размеры и формы.

Считайте матрицу из файла

Синтаксис

Описание

пример

A = readmatrix(filename) создает массив путем чтения данных в столбцах из файла. readmatrix функция выполняет автоматическое обнаружение параметров импорта для вашего файла.

readmatrix определяет формат файла из расширения файла:

  • .txt, .dat, или .csv для разделенных текстовых файлов

  • .xls, .xlsb, .xlsm, .xlsx, .xltm, .xltx, или .ods для файлов электронной таблицы

Для файлов, содержащих числовые и текстовые данные, readmatrix импортирует данные как числовой массив по умолчанию.

пример

A = readmatrix(filename,opts) дополнительно использует настройки импорта opts.

пример

A = readmatrix(___,Name,Value) создает массив из файла с дополнительными опциями, заданными одним или несколькими аргументами пары «имя-значение». Используйте любой из входных параметров от предыдущих синтаксисов прежде, чем задать пары «имя-значение».

Чтобы установить определенные настройки импорта для ваших данных, можно или использовать opts возразите или можно задать пары «имя-значение». Когда вы задаете пары «имя-значение» в дополнение к opts, затем readmatrix поддержки только эти пары «имя-значение»:

  • Текстовые файлы — DateLocale, Encoding

  • Файлы электронной таблицы — Sheet, UseExcel

Примеры

свернуть все

Считайте матрицу из текстового файла

Отобразите содержимое basic_matrix.txt и затем импортируйте данные в матрицу.

6,8,3,1
5,4,7,3
1,6,7,10
4,2,8,2
2,7,5,9
M = readmatrix('basic_matrix.txt')
M = 5×4

     6     8     3     1
     5     4     7     3
     1     6     7    10
     4     2     8     2
     2     7     5     9

Считайте матрицу из файла электронной таблицы

Импортируйте числовые данные от basic_matrix.xls в матрицу.

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

Считайте матрицу из заданного листа и области значений Используя настройки импорта

Предварительно просмотрите данные из файла электронной таблицы и импортируйте числовые данные как матрицу от заданного листа и области значений.

Файл электронной таблицы airlinesmall_subset.xlsx содержит данные в нескольких рабочих листах в течение многих лет между 1 996 и 2008. Каждый рабочий лист имеет данные в течение данного года. Предварительно просмотрите данные из файла airlinesmall_subset.xlsx. preview функция показывает данные из первого рабочего листа по умолчанию. Первые восемь переменных в файле содержат числовые данные.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Сконфигурируйте значения в объекте opts импортировать 10 строки для первых пяти переменных из рабочего листа под названием '2007'.

opts.Sheet = '2007';
opts.SelectedVariableNames = [1:5]; 
opts.DataRange = '2:11';
M = readmatrix('airlinesmall_subset.xlsx',opts)
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Считайте матрицу из заданного листа и области значений

Предварительно просмотрите данные из файла электронной таблицы и импортируйте числовые данные, как матрица, от заданного листа и области значений.

Файл электронной таблицы airlinesmall_subset.xlsx содержит данные в нескольких рабочих листах в течение многих лет между 1 996 и 2008. Каждый рабочий лист имеет данные в течение данного года. Предварительно просмотрите данные из файла airlinesmall_subset.xlsx. preview функция показывает данные из первого рабочего листа по умолчанию. Первые восемь переменных в файле содержат числовые данные.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Импортируйте 10 строки первого 5 переменные из рабочего листа под названием '2007'.

M = readmatrix('airlinesmall_subset.xlsx','Sheet','2007','Range','A2:E11')
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Входные параметры

свернуть все

filenameИмя файла, чтобы читать
вектор символов | строковый скаляр

Имя файла, чтобы читать в виде вектора символов или строкового скаляра.

В зависимости от местоположения вашего файла, filename может взять одну из следующих форм.

Местоположение

Форма

Текущая папка или папка на MATLAB® path

Задайте имя файла в filename.

Пример:
'myFile.txt'

Файл в папке

Если файл не находится в текущей папке или в папке на пути MATLAB, то задайте полное имя или относительный путь в filename.

Пример:
'C:myFoldermyFile.xlsx'

Пример:
'dataDirmyFile.txt'

Интернет URL

Если файл задан как интернет-универсальный локатор ресурса (URL), то filename должен содержать тип протокола 'http://' или 'https://'.

Пример:
'http://hostname/path_to_file/my_data.csv'

Удаленное местоположение

Если файл хранится в удаленном местоположении, то filename должен содержать полный путь файла, заданного с формой:

scheme_name://path_to_file/my_file.ext

На основе удаленного местоположения, scheme_name может быть одно из значений в этой таблице.

Удаленное местоположение scheme_name
Amazon S3™ s3
Windows Azure® Устройство хранения данных блоба wasb, wasbs
HDFS™ hdfs

Для получения дополнительной информации смотрите работу с Удаленными данными.

Пример:
's3://bucketname/path_to_file/my_file.csv'

  • Если filename включает расширение файла, затем функция импорта определяет формат файла из расширения. В противном случае необходимо задать 'FileType' аргументы пары «имя-значение», чтобы указать на тип файла.

  • На Windows® системы с Microsoft® Excel® программное обеспечение, функция импорта читает любой формат файла электронной таблицы Excel, распознанный вашей версией Excel.

  • Если ваша система не имеет Excel для Windows или если вы используете MATLAB Online™, функция импорта действует с UseExcel набор свойств к false, и чтения только .xls, .xlsx, .xlsm, .xltx, and .xltm файлы.

  • Для разделенных текстовых файлов функция импорта преобразует пустые поля в файле к любому NaN (для числовой переменной) или пустой символьный вектор (для текстовой переменной). Все линии в текстовом файле должны иметь то же количество разделителей. Функция импорта игнорирует незначительный пробел в файле.

Типы данных: char | string

optsНастройки импорта файла
SpreadsheetImportOptions | DelimitedtextImportOptions | FixedWidthImportOptions | XMLImportOptions

Настройки импорта файла в виде SpreadsheetImportOptionsDelimitedTextImportOptionsFixedWidthImportOptions, или XMLImportOptions объект, созданный detectImportOptions функция. opts объект содержит свойства, которые управляют процессом импорта данных. Для получения дополнительной информации о свойствах каждого объекта смотрите соответствующую объектную страницу.

Аргументы name-value

Задайте дополнительные разделенные запятой пары Name,Value аргументы. Name имя аргумента и Value соответствующее значение. Name должен появиться в кавычках. Вы можете задать несколько аргументов в виде пар имен и значений в любом порядке, например: Name1, Value1, ..., NameN, ValueN.

Пример: 'NumHeaderLines',5 указывает, что первые пять линий, которые предшествуют табличным данным, являются линиями заголовка.

Текст и файлы электронной таблицы

свернуть все

FileTypeТип файла
'text' | 'spreadsheet'

Тип файла в виде разделенной запятой пары, состоящей из 'FileType' и 'text' или 'spreadsheet'.

Задайте 'FileType' аргумент пары «имя-значение», когда filename не включает расширение файла или если расширение отличается от одного из следующего:

  • .txt, .dat, или .csv для разделенных текстовых файлов

  • .xls, .xlsb, .xlsm, .xlsx, .xltm, .xltx, или .ods для файлов электронной таблицы

Пример: 'FileType','text'

Типы данных: char | string

Количество линий заголовка в файле в виде разделенной запятой пары, состоящей из 'NumHeaderLines' и положительное целое число. Если незаданный, функция импорта автоматически обнаруживает количество линий заголовка в файле.

Пример: 'NumHeaderLines',7

Типы данных: single | double

ExpectedNumVariablesОжидаемое количество переменных
положительное целое число

Ожидаемое количество переменных в виде разделенной запятой пары, состоящей из 'ExpectedNumVariables' и положительное целое число. Если незаданный, функция импорта автоматически обнаруживает количество переменных.

Типы данных: single | double

RangeФрагмент данных, чтобы читать
вектор символов | строковый скаляр | числовой вектор

Фрагмент данных, чтобы считать из текста или файлов электронной таблицы в виде запятой разделенную пару, состоящую из 'Range' и вектор символов, строковый скаляр или числовой вектор в одной из следующих форм.

Способы задать Range Описание

Запуск ячейки

'Cell' или [row col]

Задайте стартовую ячейку для данных как вектор символов или строковый скаляр или два элемента числовой вектор.

  • Вектор символов или строковый скаляр, содержащий букву столбца и номер строки с помощью Excel A1 обозначение. Например, A5 идентификатор для ячейки на пересечении столбца A и строка 5.

  • Два элемента числовой вектор из формы [row col] указание на стартовую строку и столбец.

Используя стартовую ячейку, функция импорта автоматически обнаруживает степень данных путем начала импорта в ячейке запуска и окончания в последней пустой строке или области значений нижнего колонтитула.

Пример:
'A5' или [5 1]

Прямоугольная область значений

'Corner1:Corner2' или [r1 c1 r2 c2]

Укажите точный диапазон, чтобы считать использование прямоугольной области значений в одной из следующих форм.

  • 'Corner1:Corner2' — Укажите диапазон с помощью Corner1 и Corner2 которые являются двумя противостоящими углами, которые задают область, чтобы читать в Excel A1 обозначение. Например, 'C2:N15'.

  • [r1 c1 r2 c2] — Укажите диапазон с помощью четырех элементов числовой вектор, содержащий начинать-строку, начальный столбец, строку конца и столбец конца. Например, [2 3 15 13].

Функция импорта только считывает данные, содержавшиеся в заданной области. Любые пустые поля в заданной области импортируются как недостающие ячейки.

Область значений строки или область значений столбца

'Row1:Row2' или 'Column1:Column2'

Укажите диапазон путем идентификации начала и конечного использования строк номера строк Excel.

Используя указанный диапазон строки, функция импорта автоматически обнаруживает степень столбца путем чтения из первого непустого столбца в конец данных и создает одну переменную для каждого столбца.

Пример:
'5:500'

В качестве альтернативы укажите диапазон путем идентификации начала и конечного использования столбцов буквы столбца Excel или числа.

Используя указанный диапазон столбца, функция импорта автоматически обнаруживает степень строки путем чтения из первой непустой строки в конец данных или области значений нижнего колонтитула.

Количество столбцов в заданной области должно совпадать с номером, заданным в ExpectedNumVariables свойство.

Пример:
'A:K'

Запуск номера строки

n

Задайте первую строку, содержащую данные с помощью индекса строки положительной скалярной величины.

Используя заданный индекс строки, функция импорта автоматически обнаруживает степень данных путем чтения из заданной первой строки в конец данных или области значений нижнего колонтитула.

Пример 5

Именованная область значений Excel

'NamedRange'

В Excel можно создать имена, чтобы идентифицировать области значений в электронной таблице. Например, можно выбрать прямоугольный фрагмент электронной таблицы и вызвать ее 'myTable'. Если такие именованные области значений существуют в электронной таблице, то функция импорта может считать ту область значений с помощью своего имени.

Пример:
'Range','myTable'

Незаданный или пустой

''

Если незаданный, функция импорта автоматически обнаруживает используемую область значений.

Пример:
'Range',''

Примечание:
Используемая Область значений относится к прямоугольному фрагменту электронной таблицы, которая на самом деле содержит данные. Функция импорта автоматически обнаруживает используемую область значений путем обрезки любых начальных и конечных строк и столбцов, которые не содержат данные. Текст, который является только пробелом, рассматривается данными и получен в используемой области значений.

Типы данных: char | string | double

TreatAsMissing Текст, чтобы интерпретировать как недостающие данные
вектор символов | строковый скаляр | массив ячеек из символьных векторов | массив строк

Текст, чтобы интерпретировать как недостающие данные в виде вектора символов, строкового скаляра, массива ячеек из символьных векторов или массива строк.

Пример: 'TreatAsMissing',{'NA','TBD'} дает функции импорта команду обрабатывать любое вхождение NA или TBD как недостающие поля.

Типы данных: char | string | cell

OutputTypeТип выходных данных
вектор символов | строковый скаляр

Выходные данные вводят в виде разделенной запятой пары, состоящей из 'OutputType' и вектор символов или строковый скаляр, содержащий имя любого из типов данных в этой таблице.

Тип данных Тип выходных данных
Числовой 'uint8'int8int16int32int64uint16uint32uint64единственный, или 'double'
Текст 'char' или 'string'
Другие типы 'datetime'длительность, или 'categorical'

Пример: 'OutputType','uint8'

Типы данных: char | string

Текстовые файлы только

свернуть все

Символы разделителя полей в разделенном текстовом файле в виде вектора символов, строкового скаляра, массива ячеек из символьных векторов или массива строк.

Пример: 'Delimiter','|'

Пример: 'Delimiter',{';','*'}

Типы данных: char | string | cell

Символы, чтобы обработать как пробел в виде вектора символов или строкового скаляра, содержащего один или несколько символов.

Пример: 'Whitespace',' _'

Пример: 'Whitespace','?!.,'

Символы конца линии в виде вектора символов, строкового скаляра, массива ячеек из символьных векторов или массива строк.

Пример: 'LineEnding','n'

Пример: 'LineEnding','rn'

Пример: 'LineEnding',{'b',':'}

Типы данных: char | string | cell

Стиль комментариев в виде вектора символов, строкового скаляра, массива ячеек из символьных векторов или массива строк.

Например, чтобы проигнорировать текст после знака процента на той же линии, задайте CommentStyle как '%'.

Пример: 'CommentStyle',{'/*'}

Типы данных: char | string | cell

EncodingСхема кодировки символов
'UTF-8' | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | …

Схема кодировки символов, сопоставленная с файлом в виде разделенной запятой пары, состоящей из 'Encoding' и 'system' или имя схемы кодирования стандартного символа. Когда вы не задаете кодирования, readmatrix функционируйте использует автоматическое обнаружение набора символов, чтобы определить кодирование при чтении файла.

Если вы задаете 'Encoding' аргумент в дополнение к настройкам импорта, затем readmatrix функционируйте использует заданное значение для 'Encoding', переопределение кодирования задано в настройках импорта.

Пример: 'Encoding','UTF-8' использование UTF-8 как кодирование.

Пример: 'Encoding','system' использует кодирование системного значения по умолчанию.

Типы данных: char | string

DateLocaleЛокаль для чтения дат
вектор символов | строковый скаляр

Локаль для чтения дат в виде разделенной запятой пары, состоящей из 'DateLocale' и вектор символов или строковый скаляр формы xx_YY, где:

  • YY прописная альфа ISO 3166-1 2 кода, указывающие на страну.

  • xx строчный ISO 639-1 двухбуквенный код, указывающий на язык.

Эта таблица приводит некоторые общие значения для локали.

Локаль Язык Страна
'de_DE' Немецкий язык Германия
'en_GB' Английский язык Соединенное Королевство
'en_US' Английский язык Соединенные Штаты
'es_ES' Испанский язык Испания
'fr_FR' Французский язык Франция
'it_IT' Итальянский язык Италия
'ja_JP' Японский язык Япония
'ko_KR' Корейский язык Корея
'nl_NL' Нидерландский язык Нидерланды
'zh_CN' Китайский язык (упрощен) Китай

При использовании %D спецификатор формата, чтобы считать текст как datetime значения, используйте DateLocale задавать локаль, в которой функция импорта должна интерпретировать имена месяца и дня недели и сокращения.

Если вы задаете DateLocale аргумент в дополнение к opts настройки импорта, затем функция импорта использует заданное значение для DateLocale аргумент, заменяя локаль задан в настройках импорта.

Пример: 'DateLocale','ja_JP'

Символы, указывающие на десятичный разделитель в числовых переменных в виде вектора символов или строкового скаляра. Функция импорта использует символы, заданные в DecimalSeparator пара «имя-значение», чтобы отличить целую часть номера от десятичной части.

При преобразовании в целочисленные типы данных числа с десятичной частью округлены до ближайшего целого числа.

Пример: Если пара «имя-значение» задана как 'DecimalSeparator',',', затем функция импорта импортирует текст "3,14159" как номер 3.14159.

Типы данных: char | string

Символы, которые указывают на тысячи группировки в числовых переменных в виде вектора символов или строкового скаляра. Тысячи группирующихся символов действуют как визуальные диафрагмы, группируя номер в каждых трех значениях места. Функция импорта использует символы, заданные в ThousandsSeparator пара «имя-значение», чтобы интерпретировать импортируемые числа.

Пример: Если пара «имя-значение» задана как 'ThousandsSeparator',',', затем функция импорта импортирует текст "1,234,000" как 1234000.

Типы данных: char | string

TrimNonNumericУдалите нечисловые символы
false (значение по умолчанию) | true

Удалите нечисловые символы из числовой переменной в виде логического true или false.

Пример: Если пара «имя-значение» задана как 'TrimNonNumeric',true, затем функция импорта читает '$500/-' как 500.

Типы данных: логический

Процедура, чтобы обработать последовательные разделители в разделенном текстовом файле в виде одного из значений в этой таблице.

ConsecutiveDelimitersRule Поведение
'split' Разделите последовательные разделители в несколько полей.
'join' Соедините разделители в один разделитель.
'error' Возвратите ошибку и прервите операцию импорта.

Типы данных: char | string

Процедура, чтобы управлять ведущими разделителями в разделенном текстовом файле в виде одного из значений в этой таблице.

LeadingDelimitersRule Поведение
'keep' Сохраните разделитель.
'ignore' Проигнорируйте разделитель.
'error' Возвратите ошибку и прервите операцию импорта.

TrailingDelimitersRuleПроцедура, чтобы справиться с запаздыванием разделителей
'keep' | 'ignore' | 'error'

Процедура, чтобы справиться с запаздыванием разделителей в разделенном текстовом файле в виде одного из значений в этой таблице.

LeadingDelimitersRule Поведение
'keep' Сохраните разделитель.
'ignore' Проигнорируйте разделитель.
'error' Возвратите ошибку и прервите операцию импорта.

Файлы электронной таблицы только

свернуть все

Покройте, чтобы читать из в виде пустого символьного массива, вектора символов или строкового скаляра, содержащего имя листа или положительное скалярное целое число, обозначающее индекс листа. На основе значения, заданного для Sheet свойство, функция импорта ведет себя как описано в таблице.

Спецификация Поведение
'' (значение по умолчанию) Импортируйте данные от первого листа.
Имя Импортируйте данные с соответствующего имени листа, независимо от порядка листов в файле электронной таблицы.
Целое число Импортируйте данные от листа в положении, обозначенном целым числом, независимо от имен листа в файле электронной таблицы.

Типы данных: char | string | single | double

UseExcelОтметьте, чтобы запустить экземпляр Microsoft Excel для Windows
false (значение по умолчанию) | true

Отметьте, чтобы запустить экземпляр Microsoft Excel для Windows при чтении данных об электронной таблице в виде разделенной запятой пары, состоящей из 'UseExcel' и любой true, или false.

Можно установить 'UseExcel' параметр к одному из этих значений:

  • true — Функция импорта запускает экземпляр Microsoft Excel при чтении файла.

  • false — Функция импорта не запускает экземпляр Microsoft Excel при чтении файла. При работе в этом режиме функциональность функции импорта отличается в поддержку форматов файлов и интерактивных функций, таких как формулы и макросы.

UseExcel

true

false

Поддерживаемые форматы файлов

.xls, .xlsx, .xlsm, .xltx, .xltm, .xlsb, .ods

.xls, .xlsx, .xlsm, .xltx, .xltm

Поддержка интерактивных функций, таких как формулы и макросы

Да

Нет

Когда чтение из файлов электронной таблицы на платформах Windows, если вы хотите запустить экземпляр Microsoft Excel, затем установило 'UseExcel' параметр к true.

Введенный в R2019a

Read matrix from file

Since R2019a

Syntax

Description

example

A = readmatrix(filename) creates an array by
reading column-oriented data from a file. The readmatrix function
performs automatic detection of import parameters for your file.

readmatrix determines the file format from the file extension:

  • .txt, .dat, or .csv for
    delimited text files

  • .xls, .xlsb, .xlsm,
    .xlsx, .xltm, .xltx, or
    .ods for spreadsheet files

For files containing mixed numeric and text data, readmatrix imports
the data as a numeric array by default.

example

A = readmatrix(filename,opts)
additionally uses the import options opts.

example

A = readmatrix(___,Name,Value)
creates an array from a file with additional options specified by one or more name-value
pair arguments. Use any of the input arguments from the previous syntaxes before specifying
the name-value pairs.

To set specific import options for your data, you can either use the
opts object or you can specify name-value pairs. When you specify
name-value pairs in addition to opts, then readmatrix
supports only these name-value pairs:

  • Text Files — DateLocale, Encoding

  • Spreadsheet Files — Sheet, UseExcel

Examples

collapse all

Read Matrix from Text File

Display the contents of basic_matrix.txt and then import the data into a matrix.

6,8,3,1
5,4,7,3
1,6,7,10
4,2,8,2
2,7,5,9
M = readmatrix('basic_matrix.txt')
M = 5×4

     6     8     3     1
     5     4     7     3
     1     6     7    10
     4     2     8     2
     2     7     5     9

Read Matrix from Spreadsheet File

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

Read Matrix from Specified Sheet and Range Using Import Options

Preview the data from a spreadsheet file and import numerical data as a matrix from a specified sheet and range.

The spreadsheet file airlinesmall_subset.xlsx contains data in multiple worksheets for years between 1996 and 2008. Each worksheet has data for a given year. Preview the data from file airlinesmall_subset.xlsx. The preview function shows data from the first worksheet by default. The first eight variables in the file contain numerical data.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Configure the values in the opts object to import 10 rows for the first five variables from the worksheet named '2007'.

opts.Sheet = '2007';
opts.SelectedVariableNames = [1:5]; 
opts.DataRange = '2:11';
M = readmatrix('airlinesmall_subset.xlsx',opts)
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Read Matrix from Specified Sheet and Range

Preview the data from a spreadsheet file and import numerical data, as a matrix, from a specified sheet and range.

The spreadsheet file airlinesmall_subset.xlsx contains data in multiple worksheets for years between 1996 and 2008. Each worksheet has data for a given year. Preview the data from file airlinesmall_subset.xlsx. The preview function shows data from the first worksheet by default. The first eight variables in the file contain numerical data.

opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
ans=8×29 table
    Year    Month    DayofMonth    DayOfWeek    DepTime    CRSDepTime    ArrTime    CRSArrTime    UniqueCarrier    FlightNum     TailNum      ActualElapsedTime    CRSElapsedTime    AirTime    ArrDelay    DepDelay    Origin      Dest      Distance    TaxiIn    TaxiOut    Cancelled    CancellationCode    Diverted    CarrierDelay    WeatherDelay      SDelay      SecurityDelay    LateAircraftDelay
    ____    _____    __________    _________    _______    __________    _______    __________    _____________    _________    __________    _________________    ______________    _______    ________    ________    _______    _______    ________    ______    _______    _________    ________________    ________    ____________    ____________    __________    _____________    _________________

    1996      1          18            4         2117         2120        2305         2259          {'HP'}           415       {'N637AW'}           108                 99            85           6          -3       {'COS'}    {'PHX'}      551         5         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          12            5         1252         1245        1511         1500          {'HP'}           610       {'N905AW'}            79                 75            58          11           7       {'LAX'}    {'PHX'}      370         3         18           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          16            2         1441         1445        1708         1721          {'HP'}           211       {'N165AW'}            87                 96            74         -13          -4       {'RNO'}    {'PHX'}      601         4          9           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           1            1         2258         2300        2336         2335          {'HP'}          1245       {'N183AW'}            38                 35            20           1          -2       {'TUS'}    {'PHX'}      110         6         12           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1           4            4         1814         1814        1901         1910          {'US'}           683       {'N963VJ'}            47                 56            34          -9           0       {'DTW'}    {'PIT'}      201         6          7           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          31            3         1822         1820        1934         1925          {'US'}           757       {'N912VJ'}            72                 65            52           9           2       {'PHL'}    {'PIT'}      267         6         14           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          18            4          729          730         841          843          {'US'}          1564       {'N941VJ'}            72                 73            58          -2          -1       {'DCA'}    {'PVD'}      357         3         11           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    
    1996      1          26            5         1704         1705        1829         1839          {'NW'}          1538       {'N960N' }            85                 94            69         -10          -1       {'DTW'}    {'RIC'}      456         3         13           0           {0x0 char}          0         {0x0 char}      {0x0 char}     {0x0 char}     {0x0 char}         {0x0 char}    

Import 10 rows of the first 5 variables from the worksheet named '2007'.

M = readmatrix('airlinesmall_subset.xlsx','Sheet','2007','Range','A2:E11')
M = 10×5

        2007           1           2           2         711
        2007           1           3           3         652
        2007           1           4           4        1116
        2007           1           5           5         825
        2007           1           7           7        1411
        2007           1           8           1        1935
        2007           1           9           2        2005
        2007           1          11           4        1525
        2007           1          12           5        1133
        2007           1          13           6         922

Input Arguments

collapse all

filenameName of file to read
character vector | string scalar

Name of the file to read, specified as a character vector or a string scalar.

Depending on the location of your file, filename can take on one of
these forms.

Location

Form

Current folder or folder on the MATLAB® path

Specify the name of the file in
filename.

Example:
'myFile.txt'

File in a folder

If the file is not in the current folder or in a folder on the
MATLAB path, then specify the full or relative path name in
filename.

Example:
'C:myFoldermyFile.xlsx'

Example:
'dataDirmyFile.txt'

Internet URL

If the file is specified as an internet uniform resource locator (URL),
then filename must contain the protocol type
'http://' or
'https://'.

Example:
'http://hostname/path_to_file/my_data.csv'

Remote Location

If the file is stored at a remote location, then
filename must contain the full path of the file specified
with the
form:

scheme_name://path_to_file/my_file.ext

Based on the remote location,
scheme_name can be one of the values in this table.

Remote Location scheme_name
Amazon S3™ s3
Windows Azure® Blob Storage wasb, wasbs
HDFS™ hdfs

For more information, see Work with Remote Data.

Example:
's3://bucketname/path_to_file/my_file.csv'

  • If filename includes the file extension, then the importing
    function determines the file format from the extension. Otherwise, you must specify the
    'FileType' name-value pair arguments to indicate the type of file.

  • On Windows® systems with Microsoft®
    Excel® software, the importing function reads any Excel spreadsheet file format recognized by your version of Excel.

  • If your system does not have Excel for Windows or if you are using MATLAB
    Online™
    , the importing function operates with the UseExcel
    property set to false, and reads only .xls, .xlsx, .xlsm,
    .xltx, and .xltm
    files.

  • For delimited text files, the importing function converts empty fields in the file
    to either NaN (for a numeric variable) or an empty character vector
    (for a text variable). All lines in the text file must have the same number of
    delimiters. The importing function ignores insignificant white space in the file.

Data Types: char | string

optsFile import options
SpreadsheetImportOptions | DelimitedtextImportOptions | FixedWidthImportOptions | XMLImportOptions

File import options, specified as an SpreadsheetImportOptions,
DelimitedTextImportOptions,
FixedWidthImportOptions, or XMLImportOptions
object created by the detectImportOptions function. The
opts object contains properties that control the data import
process. For more information on the properties of each object, see the appropriate
object page.

Name-Value Arguments

Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN, where Name is
the argument name and Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.


Before R2021a, use commas to separate each name and value, and enclose

Name in quotes.

Example: 'NumHeaderLines',5 indicates that the first five lines that
precede the tabular data are header lines.

All Supported File Types

collapse all

WebOptionsHTTP or HTTPS request options
weboptions object

HTTP or HTTPS request options, specified as
a weboptions object. The
weboptions object determines how to import data when the
specified filename is an internet URL containing the protocol type
"http://" or "https://".

Text and Spreadsheet Files

collapse all

FileTypeType of file
'text' | 'spreadsheet'

Type of file, specified as the comma-separated pair consisting of
'FileType' and 'text' or
'spreadsheet'.

Specify the 'FileType' name-value pair argument when the
filename does not include the file extension or if the extension
is other than one of the following:

  • .txt, .dat, or
    .csv for delimited text files

  • .xls, .xlsb,
    .xlsm, .xlsx,
    .xltm, .xltx, or
    .ods for spreadsheet files

Example: 'FileType','text'

Data Types: char | string

Number of header lines in the file, specified as the comma-separated pair consisting of 'NumHeaderLines' and a positive integer. If unspecified, the importing function automatically detects the number of header lines in the file.

Example: 'NumHeaderLines',7

Data Types: single | double

ExpectedNumVariablesExpected number of variables
positive integer

Expected number of variables, specified as the comma-separated pair consisting of
'ExpectedNumVariables' and a positive integer. If unspecified,
the importing function automatically detects the number of variables.

Data Types: single | double

RangePortion of data to read
character vector | string scalar | numeric vector

Portion of the data to read from text or spreadsheet files, specified as the comma
separated pair consisting of 'Range' and a character vector, string
scalar, or numeric vector in one of these forms.

Ways to specify Range Description

Starting Cell

'Cell' or
[row col]

Specify the starting cell for the data as a character vector or
string scalar or a two element numeric vector.

  • Character vector or string scalar containing a column
    letter and row number using Excel
    A1 notation. For example,
    A5 is the identifier for the cell
    at the intersection of column A and
    row 5.

  • Two element numeric vector of the form [row
    col]
    indicating the starting row and
    column.

Using the starting cell, the importing function
automatically detects the extent of the data by beginning the import
at the start cell and ending at the last empty row or footer
range.

Example:
'A5' or [5 1]

Rectangular
Range

'Corner1:Corner2' or
[r1 c1 r2 c2]

Specify the exact range to read using the rectangular range in
one of these forms.

  • 'Corner1:Corner2' — Specify the
    range using Corner1 and
    Corner2 which are the two
    opposing corners that define the region to read in
    Excel
    A1 notation. For example,
    'C2:N15'.

  • [r1 c1 r2 c2] — Specify the range
    using a four element numeric vector containing
    start-row, start-column, end-row, and end-column. For
    example, [2 3 15 13].

The importing function only reads the
data contained in the specified range. Any empty fields within the
specified range are imported as missing cells.

Row Range or Column
Range

'Row1:Row2' or
'Column1:Column2'

Specify the range by identifying the beginning and ending rows
using Excel row numbers.

Using the specified row
range, the importing function automatically detects the column
extent by reading from the first nonempty column to the end of the
data, and creates one variable per column.

Example:
'5:500'

Alternatively, specify the
range by identifying the beginning and ending columns using
Excel column letters or numbers.

Using the
specified column range, the import function automatically detects
the row extent by reading from the first nonempty row to the end of
the data or the footer range.

The number of columns in
the specified range must match the number specified in the
ExpectedNumVariables
property.

Example:
'A:K'

Starting Row
Number

n

Specify the first row containing the data using the positive
scalar row index.

Using the specified row index, the
importing function automatically detects the extent of the data by
reading from the specified first row to the end of the data or the
footer range.

Example:5

Excel’s Named
Range

'NamedRange'

In Excel, you can create names to identify ranges in the
spreadsheet. For instance, you can select a rectangular portion of
the spreadsheet and call it 'myTable'. If such
named ranges exist in a spreadsheet, then the importing function can
read that range using its name.

Example:
'Range','myTable'

Unspecified or
Empty

''

If unspecified, the importing function automatically detects
the used range.

Example:
'Range',''

Note:
Used Range refers to the rectangular portion of
the spreadsheet that actually contains data. The importing function
automatically detects the used range by trimming any leading and
trailing rows and columns that do not contain data. Text that is
only white space is considered data and is captured within the used
range.

Data Types: char | string | double

TreatAsMissing Text to interpret as missing data
character vector | string scalar | cell array of character vectors | string array

Text to interpret as missing data, specified as a character vector, string scalar, cell array
of character vectors, or string array.

Example: 'TreatAsMissing',{'NA','TBD'} instructs the importing function to treat any occurrence of NA or TBD as a missing fields.

Data Types: char | string | cell

OutputTypeOutput data type
character vector | string scalar

Output data type, specified as the comma-separated pair consisting of
'OutputType' and a character vector or string scalar containing
name of any of the data types in this table.

Type of Data Output data type
Numeric 'uint8', 'int8',
'int16', 'int32',
'int64', 'uint16',
'uint32', 'uint64',
'single', or 'double'
Text 'char' or 'string'
Other types 'datetime', 'duration', or
'categorical'

Example: 'OutputType','uint8'

Data Types: char | string

Text Files Only

collapse all

Field delimiter characters in a delimited text file, specified as a string array,
character vector, or cell array of character vectors.

Example: "Delimiter","|"

Example: "Delimiter",[";","*"]

Characters to treat as white space, specified as a character vector or string scalar
containing one or more characters.

Example: 'Whitespace',' _'

Example: 'Whitespace','?!.,'

End-of-line characters, specified as a string array, character vector, or cell array of
character vectors.

Example: "LineEnding","n"

Example: "LineEnding","rn"

Example: "LineEnding",["b",":"]

Style of comments, specified as a string array, character vector, or cell array of
character vectors. For single- and multi-line comments, the starting identifier must be
the first non-white-space character. For single-line comments, specify a single
identifier to treat lines starting with the identifier as comments. For multi-line
comments, lines from the starting (first) identifier to the ending (second) identifier
are treated as comments. No more than two character vectors of identifiers can be
specified.

For example, to ignore the line following a percent symbol as the first
non-white-space character, specify CommentStyle as
"%".

Example: "CommentStyle",["/*"]

Example: "CommentStyle",["/*","*/"]

EncodingCharacter encoding scheme
'UTF-8' | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | …

Character encoding scheme associated with the file, specified as the
comma-separated pair consisting of 'Encoding' and
'system' or a standard character encoding scheme name. When you
do not specify any encoding, the readmatrix function uses
automatic character set detection to determine the encoding when reading the
file.

If you specify the 'Encoding' argument in addition to the
import options, then the readmatrix function uses the specified
value for 'Encoding', overriding the encoding defined in the import
options.

Example: 'Encoding','UTF-8' uses UTF-8 as the
encoding.

Example: 'Encoding','system' uses the system default
encoding.

Data Types: char | string

DateLocaleLocale for reading dates
character vector | string scalar

Locale for reading dates, specified as the comma-separated pair consisting of
'DateLocale' and a character vector or a string scalar of the
form xx_YY, where:

  • YY is an uppercase ISO 3166-1 alpha-2 code
    indicating a country.

  • xx is a lowercase ISO 639-1 two-letter code
    indicating a language.

This table lists some common values for the locale.

Locale Language Country
'de_DE' German Germany
'en_GB' English United Kingdom
'en_US' English United States
'es_ES' Spanish Spain
'fr_FR' French France
'it_IT' Italian Italy
'ja_JP' Japanese Japan
'ko_KR' Korean Korea
'nl_NL' Dutch Netherlands
'zh_CN' Chinese (simplified) China

When using the %D format specifier to read text as
datetime values, use DateLocale to specify the
locale in which the importing function should interpret month and day-of-week names and
abbreviations.

If you specify the DateLocale argument in addition to
opts the import options, then the importing function uses the
specified value for the DateLocale argument, overriding the locale
defined in the import options.

Example: 'DateLocale','ja_JP'

Characters indicating the decimal separator in numeric variables, specified as a character
vector or string scalar. The importing function uses the characters specified in the
DecimalSeparator name-value pair to distinguish the integer part
of a number from the decimal part.

When converting to integer data types, numbers with a decimal
part are rounded to the nearest integer.

Example: If name-value pair is specified as 'DecimalSeparator',',', then the
importing function imports the text "3,14159" as the number
3.14159.

Data Types: char | string

Characters that indicate the thousands grouping in numeric variables, specified as a
character vector or string scalar. The thousands grouping characters act as visual
separators, grouping the number at every three place values. The importing function uses
the characters specified in the ThousandsSeparator name-value pair to
interpret the numbers being imported.

Example: If name-value pair is specified as
'ThousandsSeparator',',', then the importing function imports the
text "1,234,000" as 1234000.

Data Types: char | string

TrimNonNumericRemove nonnumeric characters
false (default) | true

Remove nonnumeric characters from a numeric variable, specified as a logical true or false.

Example: If name-value pair is specified as 'TrimNonNumeric',true, then the
importing function reads '$500/-' as
500.

Data Types: logical

Procedure to manage consecutive delimiters in a delimited text file,
specified as one of the values in this table.

Value Behavior
"split" Split the consecutive delimiters into
multiple fields.
"join" Join the delimiters into one
delimiter.
"error" Return an error and cancel the import
operation.

Procedure to manage leading delimiters in a delimited text file, specified as one of the
values in this table.

Value Behavior
"keep" Keep the delimiter.
"ignore" Ignore the delimiter.
"error" Return an error and cancel the import operation.

TrailingDelimitersRuleProcedure to manage trailing delimiters
'keep' | 'ignore' | 'error'

Procedure to manage trailing delimiters in a delimited text file, specified as one
of the values in this table.

Leading Delimiters Rule Behavior
'keep' Keep the delimiter.
'ignore' Ignore the delimiter.
'error' Return an error and abort the import operation.

Spreadsheet Files Only

collapse all

Sheet to read from, specified as an empty character array, a character vector or string scalar
containing the sheet name, or a positive scalar integer denoting the sheet
index. Based on the value specified for the Sheet
property, the import function behaves as described in the table.

Specification Behavior
'' (default) Import data from the first sheet.
Name Import data from the matching sheet name,
regardless of order of sheets in the spreadsheet file.
Integer Import data from sheet in the position denoted by the integer,
regardless of the sheet names in the spreadsheet file.

Data Types: char | string | single | double

UseExcelFlag to start instance of Microsoft Excel for Windows
false (default) | true

Flag to start an instance of Microsoft
Excel
for Windows when reading spreadsheet data, specified as the comma-separated pair consisting of 'UseExcel' and either true, or false.

You can set the 'UseExcel' parameter to one of these values:

  • true — The importing function starts an instance of
    Microsoft
    Excel when reading the
    file.

  • false — The importing function does not start an
    instance of Microsoft
    Excel when reading the file. When
    operating in this mode, the importing function functionality differs in the
    support of file formats and interactive features, such as formulas and
    macros.

UseExcel

true

false

Supported file formats

.xls, .xlsx, .xlsm, .xltx, .xltm, .xlsb, .ods

.xls, .xlsx, .xlsm, .xltx, .xltm

Support for interactive features, such as formulas and macros

Yes

No

When reading from spreadsheet files on Windows platforms, if you want to start an instance of Microsoft
Excel
, then set the 'UseExcel' parameter to
true.

Version History

Introduced in R2019a

Понравилась статья? Поделить с друзьями:
  • Read error rate ошибка
  • Rdr 2 не устанавливается на пк ошибка
  • Rdr 2 выдает ошибку при запуске
  • Rdr 2 online ошибка 0x99270017
  • Rdr 2 exe ошибка приложения 0xc0000906