Как записать матрицу в файл в матлаб

Обновлено: 07.07.2024

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.

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

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:

Examples

Read Matrix from Text File

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

Read Matrix from Spreadsheet File

Import numeric data from basic_matrix.xls into a matrix.

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.

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

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.

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

Input Arguments

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.

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:\myFolder\myFile.xlsx'

Example: 'dataDir\myFile.txt'

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.

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.

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

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.

Type of FilesOutput
Spreadsheet files SpreadsheetImportOptions object (only available for the Sheet , DataRange , and VariableNames properties)
Text files DelimitedTextImportOptions object
Fixed-width text files FixedWidthImportOptions object
XML files XMLImportOptions object

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1. NameN,ValueN .

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

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

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

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.

'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]

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

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

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

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

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

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

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

Data Types: char | string | cell

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 DataOutput 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

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

Example: 'Delimiter','|'

Example: 'Delimiter',

Data Types: char | string | cell

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 character vector, string scalar, cell array of character vectors, or string array.

Example: 'LineEnding','\n'

Example: 'LineEnding','\r\n'

Example: 'LineEnding',

Data Types: char | string | cell

Style of comments, specified as a character vector, string scalar, cell array of character vectors, or string array.

For example, to ignore the text following a percent sign on the same line, specify CommentStyle as '%' .

Example: 'CommentStyle',

Data Types: char | string | cell

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

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 LanguageCountry
'de_DE' GermanGermany
'en_GB' EnglishUnited Kingdom
'en_US' EnglishUnited States
'es_ES' SpanishSpain
'fr_FR' FrenchFrance
'it_IT' ItalianItaly
'ja_JP' JapaneseJapan
'ko_KR' KoreanKorea
'nl_NL' DutchNetherlands
'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

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 handle consecutive delimiters in a delimited text file, specified as one of the values in this table.

Consecutive Delimiters RuleBehavior
'split' Split the consecutive delimiters into multiple fields.
'join' Join the delimiters into one delimiter.
'error' Return an error and abort the import operation.

Data Types: char | string

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

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

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

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

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.

SpecificationBehavior
'' (default)Import data from the first sheet.
NameImport data from the matching sheet name, regardless of order of sheets in the spreadsheet file.
IntegerImport 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

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:

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

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

Support for interactive features, such as formulas and macros

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 .

xlswrite( filename , A , sheet ) записи к заданному рабочему листу.

xlswrite( filename , A , xlRange ) записи в прямоугольную область заданы xlRange в первом рабочем листе рабочей книги. Используйте синтаксис области значений Excel, такой как 'A1:C3' .

xlswrite( filename , A , sheet , xlRange ) записи к заданному рабочему листу и области значений.

status = xlswrite( ___ ) возвращает состояние операции записи, с помощью любого из входных параметров в предыдущих синтаксисах. Когда операция успешна, состоянием является 1 . В противном случае состоянием является 0 .

Примеры

Запись вектора в электронную таблицу

Запишите вектор с 7 элементами в файл Excel®.

Запись в определенный лист и область значений в электронной таблице

Запишите смешанные текстовые и числовые данные в файл Excel®, запускающийся в ячейке E1 из Sheet2 .

filename FileName
вектор символов | строка

Имя файла в виде вектора символов или строки.

Если filename не существует, xlswrite создает файл, определяя формат на основе заданного расширения. Чтобы создать файл, совместимый с программным обеспечением Excel 97-2003, задайте расширение .xls . Чтобы создать файлы в форматах Excel 2007, задайте расширение .xlsx , .xlsb , или .xlsm . Если вы не задаете расширение, xlswrite использует значение по умолчанию, .xls .

Пример: 'myFile.xlsx' или "myFile.xlsx"

Пример: 'C:\myFolder\myFile.xlsx'

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

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

A — Введите матрицу
матрица

Введите матрицу в виде двумерного числового, символьного массива или массива строк, или, если каждая ячейка содержит один элемент, массив ячеек.

Если A массив ячеек, содержащий что-то другое, чем числовой скаляр или текст, затем xlswrite тихо оставляет соответствующую ячейку в электронной таблице пустой.

Максимальный размер массива A зависит от связанной версии Excel. Для получения дополнительной информации о технических требованиях Excel и пределах, смотрите справку Excel.

Пример: [10,2,45;-32,478,50]

Пример:

Пример: "ABCDEF"

Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string | cell

sheet — Имя рабочего листа
вектор символов | представляет в виде строки | положительное целое число

Имя рабочего листа в виде одного из следующего:

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

Положительное целое число, которое указывает на индекс рабочего листа.

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

Типы данных: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

xlRange — Прямоугольная область значений
вектор символов | строка

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

Задайте xlRange использование двух противостоящих углов, которые задают область, чтобы записать. Например, 'D2:H4' представляет прямоугольную область 3 на 5 между этими двумя углами D2 и H4 на рабочем листе. xlRange вход не является чувствительным к регистру, и использует стиль ссылки Excel A1 (см. справку Excel). xlswrite не распознает названные области значений.

Если вы не задаете sheet , затем xlRange должен включать оба угла и символ двоеточия, даже для отдельной ячейки (такие как 'D2:D2' ). В противном случае, xlswrite интерпретирует вход как имя рабочего листа (такое как 'D2' ).

Если вы задаете sheet , затем xlRange может задать только первую ячейку (такую как 'D2' xlswrite входной массив записей A начало в этой ячейке.

writematrix( A ) пишет гомогенный массив A к разделенному текстовому файлу запятой. Имя файла является именем переменной рабочей области массива, добавленного с дополнительным .txt . Если writematrix не может создать имя файла из имени массивов, затем это пишет в файл matrix.txt .

Каждый столбец каждой переменной в A становится столбцом в выходном файле. writematrix функционируйте перезаписывает любой существующий файл.

writematrix( A , filename ) записи к файлу с именем и расширением заданы filename .

writematrix определяет формат файла на основе заданного расширения. Расширение должно быть одним из следующего:

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

writematrix( ___ , Name,Value ) пишет массив в файл с дополнительными опциями, заданными одним или несколькими Name,Value парные аргументы и могут включать любой из входных параметров в предыдущих синтаксисах.

Примеры

Запишите матрицу в текстовый файл

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

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

Запишите матрицу в разделенный текстовый файл запятой и отобразите содержимое файла. writematrix функционируйте выводит текстовый файл под названием M.txt .

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

Запишите матрицу в файл электронной таблицы

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

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

Запишите матрицу в файл электронной таблицы.

Считайте и отобразите матрицу от M.xls .

Запишите матрицу в заданный лист и область значений

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

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

Запишите матрицу в M.xls , к второму рабочему листу в файле, запускающемся в третьей строке.

Считайте и отобразите матрицу.

Добавьте данные к электронной таблице

Добавьте массив данных ниже существующих данных в электронной таблице.

Создайте две матрицы в рабочей области.

Запишите матричный M1 в файл электронной таблицы, M.xls.

Добавьте данные в матричном M2 ниже существующих данных в файле электронной таблицы.

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

Добавьте матричные данные к текстовому файлу

Добавьте массив данных ниже существующих данных в текстовом файле.

Создайте две матрицы в рабочей области.

Запишите матричный fibonacci1 к текстовому файлу, fibonacci.txt.

Добавьте данные в fibonacci2 ниже существующих данных в текстовом файле.

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

filename FileName
вектор символов | строковый скаляр

Имя файла в виде вектора символов или строкового скаляра.

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

Чтобы записать в текущую папку, задайте имя файла в filename .

Пример: 'myTextFile.csv'

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

Пример: 'C:\myFolder\myTextFile.csv'

Пример: 'myFolder\myExcelFile.xlsx'

Записать в удаленное местоположение, filename должен содержать полный путь файла, заданного как универсальный локатор ресурса (URL) формы:

scheme_name :// path_to_file / my_file.ext

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

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

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

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

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

Если filename имя файла существующего текста, затем функция записи перезаписывает файл.

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

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

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

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

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

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

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

'FileType' пара "имя-значение" должна использоваться с filename входной параметр. Вы не должны задавать 'FileType' аргумент пары "имя-значение", если filename входной параметр включает стандартное расширение файла. Следующие стандартные расширения файла распознаны функцией записи:

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

.xls , .xlsm , или .xlsx для файлов электронной таблицы Excel

.xlsb для файлов электронной таблицы Excel, поддержанных в системах с Excel для Windows

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

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

DateLocale — Локаль для записи дат
вектор символов | строковый скаляр

Локаль для записи дат в виде разделенной запятой пары, состоящей из 'DateLocale' и вектор символов или строковый скаляр. При записи datetime значения к файлу, используйте DateLocale задавать локаль в который writematrix должен написать имена месяца и дня недели и сокращения. Вектор символов или строка принимают форму xx _ YY , где xx строчный ISO 639-1 двухбуквенный код, указывающий на язык и YY прописная альфа ISO 3166-1 2 кода, указывающие на страну. Для списка общих значений для локали смотрите Locale аргумент пары "имя-значение" для datetime функция.

Функция записи игнорирует 'DateLocale' значение параметров каждый раз, когда даты могут быть записаны как отформатированные даты Excel.

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

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

WriteMode — Режим Writing
вектор символов | строковый скаляр

Режим Writing в виде разделенной запятой пары, состоящей из 'WriteMode' и вектор символов или строковый скаляр. Выберите режим записи на основе типа файла.

'overwrite' (значение по умолчанию) — Перезапись файл.

'append' — Добавьте данные к файлу.

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

'inplace' (значение по умолчанию) — Обновление только область значений занято входными данными. Функция записи не изменяет данных за пределами области значений, занятой входными данными.

Если вы не задаете лист, то функция записи пишет в первый лист.

'overwritesheet' — Очистите заданный лист и запишите входные данные в очищенный лист.

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

'append' — Функция записи добавляет входные данные к нижней части занятой области значений заданного листа.

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

'replacefile' — Удалите все другие листы из файла, затем очистите и запишите входные данные в к заданному листу.

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

Если файл, который вы задали, не существует, то функция записи создает новый файл и пишет входные данные в первый лист.

Когда WriteVariableNames установлен в true , функция записи не поддерживает режим записи 'append' .

Для файлов электронной таблицы:

Когда режимом записи является 'append' , функция записи не поддерживает Range параметр.

Если файл, который вы задали, не существует, то функция записи выполняет те же действия как 'replacefile' .

Пример: 'WriteMode','append'

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

Delimiter — Символ разделителя полей
вектор символов | строковый скаляр

Символ разделителя полей в виде разделенной запятой пары, состоящей из 'Delimiter' и вектор символов или строковый скаляр, содержащий один из этих спецификаторов:

Запятая. Это поведение по умолчанию.

Точка с запятой

Можно использовать 'Delimiter' пара "имя-значение" только для разделенных текстовых файлов.

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

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

QuoteStrings — Индикатор для записи заключенного в кавычки текста
true | false

Индикатор для записи заключенного в кавычки текста в виде 'QuoteStrings' и любой true или false .

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

Если 'QuoteStrings' false , затем текст записан без изменения.

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

Можно использовать 'QuoteStrings' аргумент значения имени только с разделенными текстовыми файлами.

Encoding — Схема кодировки символов
'UTF-8' (значение по умолчанию) | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | .

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

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

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

Sheet — Рабочий лист, чтобы записать в
вектор символов | строковый скаляр | положительное целое число

Рабочий лист, чтобы записать в в виде разделенной запятой пары, состоящей из 'Sheet' и вектор символов или строковый скаляр, содержащий имя рабочего листа или положительное целое число, указывающее на индекс рабочего листа. Имя рабочего листа не может содержать двоеточие ( : ). Чтобы определить имена листов в файле электронной таблицы, используйте sheets = sheetnames(filename) . Для получения дополнительной информации смотрите sheetnames .

Задайте рабочий лист, чтобы записать в по наименованию или индекс:

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

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

Можно использовать 'Sheet' пара "имя-значение" только с файлами электронной таблицы.

Пример: 'Sheet' ,2

Пример: 'Sheet' , 'MySheetName'

Типы данных: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Range — Прямоугольный фрагмент рабочего листа, чтобы записать в
вектор символов | строковый скаляр

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

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

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

Corner1 и Corner2 два противостоящих угла, которые задают область, чтобы записать. Например, 'D2:H4' представляет прямоугольную область 3 на 5 между этими двумя углами D2 и H4 на рабочем листе. 'Range' аргумент пары "имя-значение" не является чувствительным к регистру, и использует стиль ссылки Excel A1 (см. справку Excel).

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

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

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

'Range' пара "имя-значение" может только использоваться с файлами Excel.

writematrix( A ) writes homogeneous array A to a comma delimited text file. The file name is the workspace variable name of the array, appended with the extension .txt . If writematrix cannot construct the file name from the array name, then it writes to the file matrix.txt .

Each column of each variable in A becomes a column in the output file. The writematrix function overwrites any existing file.

writematrix( A , filename ) writes to a file with the name and extension specified by filename .

writematrix determines the file format based on the specified extension. The extension must be one of the following:

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

writematrix( ___ , Name,Value ) writes an array to a file with additional options specified by one or more Name,Value pair arguments and can include any of the input arguments in previous syntaxes.

Examples

Write Matrix to Text File

Create a matrix, write it to a comma-separated text file, and then write the matrix to another text file with a different delimiter character.

Create a matrix in the workspace.

Write the matrix to a comma delimited text file and display the file contents. The writematrix function outputs a text file named M.txt .

To write the same matrix to a text file with a different delimiter character, use the 'Delimiter' name-value pair.

Write Matrix to Spreadsheet File

Create a matrix, write it to a spreadsheet file, and then read and display the contents of the file.

Create a matrix in the workspace.

Write the matrix to a spreadsheet file.

Read and display the matrix from M.xls .

Write Matrix to Specified Sheet and Range

Create a matrix and write it to a specified sheet and range in a spreadsheet file.

Create a matrix in the workspace.

Write the matrix to M.xls , to the second worksheet in the file, starting at the third row.

Read and display the matrix.

Append Data to Spreadsheet

Append an array of data below existing data in a spreadsheet.

Create two matrices in the workspace.

Write the matrix M1 to a spreadsheet file, M.xls.

Append the data in matrix M2 below the existing data in the spreadsheet file.

Read the spreadsheet file and display the matrix.

Append Matrix Data to Text File

Append an array of data below existing data in a text file.

Create two matrices in the workspace.

Write the matrix fibonacci1 to a text file, fibonacci.txt.

Append the data in fibonacci2 below the existing data in the text file.

Read the text file and display the matrix.

Input Arguments

Input data, specified as a matrix.

File name, specified as a character vector or string scalar.

Depending on the location you are writing to, filename can take on one of these forms.

To write to the current folder, specify the name of the file in filename .

Example: 'myTextFile.csv'

To write to a folder different from the current folder, specify the full or relative path name in filename .

Example: 'C:\myFolder\myTextFile.csv'

Example: 'myFolder\myExcelFile.xlsx'

To write to a remote location, filename must contain the full path of the file specified as a uniform resource locator (URL) of 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.

For more information, see Work with Remote Data.

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

If filename includes the file extension, then the writing function determines the file format from the extension. Otherwise, the writing function creates a comma separated text file and appends the extension .txt . Alternatively, you can specify filename without the file’s extension, and then include the 'FileType' name-value pair arguments to indicate the type of file.

If filename does not exist, then the writing function creates the file.

If filename is the name of an existing text file, then the writing function overwrites the file.

If filename is the name of an existing spreadsheet file, then the writing function writes the data to the specified location, but does not overwrite any values outside the range of the input data.

Data Types: char | string

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1. NameN,ValueN .

Example: 'FileType',text indicates that the variable names should not be included as the first row of the output file.

Type of file, specified as the comma-separated pair consisting of 'FileType' and a character vector or string containing 'text' or 'spreadsheet' .

The 'FileType' name-value pair must be used with the filename input argument. You do not need to specify the 'FileType' name-value pair argument if the filename input argument includes a standard file extension. The following standard file extensions are recognized by the writing function:

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

.xls , .xlsm , or .xlsx for Excel spreadsheet files

.xlsb for Excel spreadsheet files supported on systems with Excel for Windows

Example: 'FileType','spreadsheet'

Data Types: char | string

Locale for writing dates, specified as the comma-separated pair consisting of 'DateLocale' and a character vector or a string scalar. When writing datetime values to the file, use DateLocale to specify the locale in which writematrix should write month and day-of-week names and abbreviations. The character vector or string takes the form xx _ YY , where xx is a lowercase ISO 639-1 two-letter code indicating a language, and YY is an uppercase ISO 3166-1 alpha-2 code indicating a country. For a list of common values for the locale, see the Locale name-value pair argument for the datetime function.

The writing function ignores the 'DateLocale' parameter value whenever dates can be written as Excel-formatted dates.

Example: 'DateLocale','ja_JP'

Data Types: char | string

Writing mode, specified as the comma-separated pair consisting of 'WriteMode' and a character vector or a string scalar. Select a write mode based on the file type.

If the file you specified does not exist, then the writing function creates and writes data to a new file.

If you do not specify a sheet, then the writing function writes to the first sheet.

If you do not specify a sheet, then the writing function clears the first sheet and writes the input data to it.

If you do not specify a sheet, then the writing function appends the input data to the bottom of the occupied range of the first sheet.

If you do not specify a sheet, then the writing function removes all other sheets from the file, and then clears and writes the input data to the first sheet.

If the file you specified does not exist, then the writing function creates a new file and writes the input data to the first sheet.

When WriteVariableNames is set to true , the writing function does not support the write mode 'append' .

For spreadsheet files:

When the write mode is 'append' , the writing function does not support the Range parameter.

If the file you specified does not exist, then the writing function performs the same actions as 'replacefile' .

Example: 'WriteMode','append'

Data Types: char | string

Field delimiter character, specified as the comma-separated pair consisting of 'Delimiter' and a character vector or string scalar containing one of these specifiers:

Comma. This is the default behavior.

You can use the 'Delimiter' name-value pair only for delimited text files.

Example: 'Delimiter','space'

Data Types: char | string

Indicator for writing quoted text, specified as 'QuoteStrings' and either true or false .

If 'QuoteStrings' is true , then the function encloses text in double-quote characters and replaces any double-quote characters surrounding text with two double-quote characters. The two double-quote characters are also referred to as escaped characters.

If 'QuoteStrings' is false , then text is written without alteration.

If 'QuoteStrings' is unspecified, the function inspects the data for delimiters designated by the 'Delimiter' name-value argument. If a delimiter is found within a column, each element within the column will be written with double-quotes.

You can use the 'QuoteStrings' name-value argument only with delimited text files.

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 writing function uses UTF-8 to write the file.

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

Data Types: char | string

Worksheet to write to, specified as the comma-separated pair consisting of 'Sheet' and a character vector or a string scalar containing the worksheet name or a positive integer indicating the worksheet index. The worksheet name cannot contain a colon ( : ). To determine the names of sheets in a spreadsheet file, use sheets = sheetnames(filename) . For more information, see sheetnames .

Specify the worksheet to write to by name or index:

You can use the 'Sheet' name-value pair only with spreadsheet files.

Example: 'Sheet' , 2

Example: 'Sheet' , 'MySheetName'

Data Types: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Rectangular portion of worksheet to write to, specified as the comma-separated pair consisting of 'Range' and a character vector or string scalar in one of the following forms.

Corner1 specifies the first cell of the region to write. The writing function writes the data starting at this cell.

Example: 'Range','D2'

Corner1 and Corner2 are two opposing corners that define the region to write. For example, 'D2:H4' represents the 3-by-5 rectangular region between the two corners D2 and H4 on the worksheet. The 'Range' name-value pair argument is not case sensitive, and uses Excel A1 reference style (see Excel help).

Example: 'Range','D2:H4'

If the range you specify is smaller than the size of the input data, then the writing function writes only a subset of the input data that fits into the range.

If the range you specify is larger than the size of the input data, then the writing function leaves the remainder of the region as it is.

Читайте также: