Read matrix matlab ошибка

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

55k10 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

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

Синтаксис

Описание

пример

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

readmatrix returns NaNs instead of numeric values for nearly indistinguishable .txt file

Oliver Johnson

Input Files

The attached file1.txt and file2.txt have identical structure (9 lines of header followed by data arranged in 15 columns). The header looks like this:

ITEM: BOX BOUNDS pp pp pp

-9.6850194863609573e-01 1.0509150710611115e+02

-8.0199580669506787e-01 8.7024035559953262e+01

-2.0781435615505643e+02 2.0781435615505643e+02

ITEM: ATOMS mass id type x y z c_1 c_2 f_eco[1] f_eco[2] c_sv[1] c_sv[2] c_sv[3] c_sv[4] backforth

Expected Behavior

I want to extract the numerical data in the header contained on lines 6-8 (3 rows and 2 columns). I use readmatrix to do this as follows (for file1.txt.):

simcell = readmatrix(‘file1.txt’,‘Filetype’,‘text’,‘Range’,[6 1 8 2])

simcell =

-0.9646 105.0876
-0.7987 87.0208
-207.7989 207.7989

It also works to extract the data that appears after the header as follows:

data_raw = readmatrix(‘file1.txt’,‘FileType’,‘text’,‘NumHeaderLines’,9);

I have hundreds of thousands of files like this, and this approach works for almost all of them, but occasionally it fails…

Unexpected Behavior

When I do the same thing for file2.txt, it returns NaNs and I can’t figure out why:

simcell = readmatrix(‘file2.txt’,‘Filetype’,‘text’,‘Range’,[6 1 8 2])

In an effort to debug the issue I looked at hidden characters, delimiters, character encoding and all appear identical between the two input files. However, I did find that if I manually delete all of the data after the header (attached as file2short.txt) I get the correct result:

simcell = readmatrix(‘file2short.txt’,‘Filetype’,‘text’,‘Range’,[6 1 8 2])

simcell =

-0.9685 105.0915
-0.8020 87.0240
-207.8144 207.8144

Question

I know there are many other ways one could accomplish the desired result, but that is not my question. My question is: why does this unexpected behavior occur in this example?

Accepted Answer

Kangming Xu

Here is the update.

The difference between the two files is that the delimiter is default detected as {‘,’} for file2.txt and detected as {‘t’ ‘ ‘} for file1.txt. The reason for it is that the provided «Range» values is limited, so rows outside of the Range are used to determine the format of a file to ensure the best result. As there are more rows of the numeric space-delimited rows of data in file1, the delimiter is selected as {‘t’ ‘ ‘}.

As for why the function works properly without «Delimiter» property for file2short.txt , the detection heuristics would depend strongly on the selected data if there are only a few rows.

If the format of files and range of selected data is same, you could capture the detection options in a «DelimitedTextImportOptions» object. Please refer to the link below for more information.

Eg:

opts = delimitedTextImportOptions(‘Delimiter’, ‘ ‘, ‘DataLines’, [6 8], ‘NumVariables’, 2, ‘VariableTypes’, {‘double’, ‘double’})

data1 = readmatrix(‘file1.txt’, opts)

data2 = readmatrix(‘file2.txt’, opts)


More Answers (0)

See Also

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

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

  • Re2 exe неустранимая ошибка приложения 0x887a0006
  • Read handshake record ошибка
  • Re00w ошибка батареи hp
  • Read from disk ошибка торрента как исправить
  • React сообщение об ошибке