Академический Документы
Профессиональный Документы
Культура Документы
Syntax
T = table(var1,...,varN)
T = table(var1,...,varN,Name,Value)
T = table
Description
T = table(var1,...,varN) creates a table from the input variables, var1,...,varN . Variables can be of different sizes and data types, but all variables
must have the same number of rows.
For more information on creating and using the table data type, see Tables.
example
T = table(var1,...,varN,Name,Value) includes additional options specified by one or more Name,Value pair arguments.
For example, you can specify row names or variable names to include in the table.
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T = table(Age,Height,Weight,BloodPressure,...
'RowNames',LastName)
T = 5×4 table
Age Height Weight BloodPressure
___ ______ ______ _____________
Create a table from arrays with different data types where each variable contains three rows.
Open Live Script
T = table(categorical({'M';'F';'M'}),[45;32;34],...
{'NY';'CA';'MA'},logical([1;0;0]),...
'VariableNames',{'Gender' 'Age' 'State' 'Vote'})
T = 3×4 table
Gender Age State Vote
______ ___ _____ _____
M 45 'NY' true
F 32 'CA' false
M 34 'MA' false
Gender is a categorical array, Age is a double-precision array, State is a cell array of character vectors, and Vote is a logical array. You can use the function summary
to print the data type and other information about the variables in the table.
Starting in R2016b, you can create string arrays with the string function, and add string arrays as table variables.
Open Live Script
FlightNum = [1261;547;3489];
Customer = string({'Jones';'Brown';'Smith'});
Date = datetime(2016,12,20:22)';
Rating = categorical({'Good';'Poor';'Fair'});
Comment = string({'Flight left on time, not crowded';...
'Late departure, ran out of dinner options';...
'Late, but only by half an hour. Otherwise fine.'});
T = table(FlightNum,Customer,Date,Rating,Comment)
T = 3×5 table
FlightNum Customer Date Rating Comment
_________ ________ ___________ ______ _________________________________________________
To use the text in a string array as row names, convert the string array to a cell array of character vectors. Then create a table with row names.
Customer = cellstr(Customer);
T = table(FlightNum,Date,Rating,Comment,'RowNames',Customer)
T = 3×4 table
FlightNum Date Rating Comment
_________ ___________ ______ _________________________________________________
Create workspace variables containing snowfall totals on different dates at three locations. These variables are row
vectors. Open Live Script
Date = {'12/25/11','1/2/12','1/23/12','2/7/12','2/15/12'};
location1 = [20 5 13 0 17];
location2 = [18 9 21 5 12];
location3 = [26 10 16 3 15];
One way to create a table from these variables is to call the table function with the syntax T = table(Date',location1',location2',location3'). Because the
workspace variables are row vectors, you must transpose them to put them into the table as column-oriented data. Therefore, the input arguments are expressions, not
simple variables. As a result, table creates T with the default variable names Var1, Var2, Var3, and Var4. You can assign more meaningful names to
T.Properties.VariableNames after you create T. But, it might be more convenient to create an empty table, and then add variables one at a time with new names.
Create an empty table. Transpose the workspace variables and add them to the table as column vectors. As part of assigning each workspace variable into T, provide a
meaningful name for the table variable.
T = table;
T.Date = Date';
T.Natick = location1';
T.Boston = location2';
T.Worcester = location3'
T = 5×4 table
Date Natick Boston Worcester
__________ ______ ______ _________
'12/25/11' 20 18 26
'1/2/12' 5 9 10
'1/23/12' 13 21 16
'2/7/12' 0 5 3
'2/15/12' 17 12 15
Input variables, specified as arrays with the same number of rows. The input variables can be of different sizes and different data types.
Common input variables are numeric arrays, logical arrays, character arrays, structure arrays, or cell arrays. Input variables also can be objects that are arrays. Such
an array must support indexing of the form var(index1,...,indexN), where index1 is a numeric or logical vector that corresponds to rows of the variable var. In
addition, the array must implement both a vertcat method and a size method with a dim argument.
Example: table([1:4]',ones(4,3,2),eye(4,2)) creates a table from variables with four rows, but different sizes.
Example: table([1:3]',{'one';'two';'three'},categorical({'A';'B';'C'})) creates a table from variables with three rows, but different data types.
Row names, specified as the comma-separated pair consisting of 'RowNames' and a cell array of character vectors that are nonempty and distinct. The number of
character vectors must equal the number of rows in the table.
Variable names, specified as the comma-separated pair consisting of 'VariableNames' and a cell array of character vectors that are nonempty and distinct. The
number of character vectors must equal the number of variables. The variable names that you assign must be valid MATLAB® variable names. You can determine valid
variable names using the function isvarname.
T — Output table
table
Output table, returned as a table. The table can store metadata such as descriptions, variable units, variable names, and row names. For more information, see Table
Properties.
Unless you specify the table variable names using the VariableNames name-value pair argument, the table function generates the variable names automatically. If an
input argument is a variable in the current workspace, table uses that variable name as the table variable name. Otherwise, it generates a name from Var followed by
an integer, such as Var2.
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
See Also
array2table | cell2table | isvarname | readtable | struct2table | summary | Table Properties | tall | uitable
Topics
Create and Work with Tables
Modify Units, Descriptions and Table Variable Names
Access Data in a Table
Calculations on Tables
Introduced in R2013b
textscan
Read formatted data from text file or string
Syntax
C = textscan(fileID,formatSpec)
C = textscan(fileID,formatSpec,N)
C = textscan(chr,formatSpec)
C = textscan(chr,formatSpec,N)
Description
C = textscan(fileID,formatSpec) reads data from an open text file into a cell array, C. The text file is indicated by the file identifier, fileID. Use fopen to example
open the file and obtain the fileID value. When you finish reading from a file, close the file by calling fclose(fileID).
textscan attempts to match the data in the file to the conversion specifier in formatSpec. The textscan function reapplies formatSpec throughout the entire
file and stops when it cannot match formatSpec to the data.
example
C = textscan(fileID,formatSpec,N) reads file data using the formatSpec N times, where N is a positive integer. To read additional data from the file after
N cycles, call textscan again using the original fileID. If you resume a text scan of a file by calling textscan with the same file identifier (fileID), then
textscan automatically resumes reading at the point where it terminated the last read.
C = textscan(chr,formatSpec) reads the text from character vector chr into cell array C. When reading text from a character vector, repeated calls to example
textscan restart the scan from the beginning each time. To restart a scan from the last position, request a position output.
textscan attempts to match the data in character vector chr to the format specified in formatSpec.
C = textscan( ___ ,Name,Value) specifies options using one or more Name,Value pair arguments, in addition to any of the input arguments in the previous example
syntaxes.
[C,position] = textscan( ___ ) returns the position in the file or the character vector at the end of the scan as the second output argument. For a file, this example
is the value that ftell(fileID) would return after calling textscan. For a character vector, position indicates how many characters textscan read.
The specifier '%f' in formatSpec tells textscan to match each field in chr to a double-precision floating-point number.
celldisp(C)
C{1} =
0.4100
8.2400
3.5700
6.2400
9.2700
Read the same character vector, and truncate each value to one decimal digit.
C = textscan(chr,'%3.1f %*1d');
The specifier %3.1f indicates a field width of 3 digits and a precision of 1. The textscan function reads a total of 3 digits, including the decimal point and the 1 digit
after the decimal point. The specifier, %*1d, tells textscan to skip the remaining digit.
celldisp(C)
C{1} =
0.4000
8.2000
3.5000
6.2000
9.2000
Read Different Types of Data
Load the data file and read each column with the appropriate type.
Open Live Script
Load file scan1.dat and preview its contents in a text editor. A screen shot is shown below.
filename = fullfile(matlabroot,'examples','matlab','scan1.dat');
Open the file, and read each column with the appropriate conversion specifier. textscan returns a 1-by-9 cell array C.
fileID = fopen(filename);
C = textscan(fileID,'%s %s %f32 %d8 %u %f %f %s %f');
fclose(fileID);
whos C
Examine the individual entries. Notice that C{1} and C{2} are cell arrays. C{5} is of data type uint32, so the first two elements of C{5} are the maximum values for a
32-bit unsigned integer, or intmax('uint32').
celldisp(C)
C{1}{1} =
09/12/2005
C{1}{2} =
10/12/2005
C{1}{3} =
11/12/2005
C{2}{1} =
Level1
C{2}{2} =
Level2
C{2}{3} =
Level3
C{3} =
12.3400
23.5400
34.9000
C{4} =
45
60
12
C{5} =
4294967295
4294967295
200000
C{6} =
Inf
-Inf
10
C{7} =
NaN
0.0010
100.0000
C{8}{1} =
Yes
C{8}{2} =
No
C{8}{3} =
No
C{9} =
5.1000 + 3.0000i
2.2000 - 0.5000i
3.1000 + 0.1000i
Remove the literal text 'Level' from each field in the second column of the data from the previous example. A preview of
the file is shown below. Open Live Script
Open the file and Match the literal text in the formatSpec input.
filename = fullfile(matlabroot,'examples','matlab','scan1.dat');
fileID = fopen(filename);
C = textscan(fileID,'%s Level%d %f32 %d8 %u %f %f %s %f');
fclose(fileID);
C{2}
1
2
3
View the MATLAB® data type of the second cell in C. The second cell of the 1-by-9 cell array, C, is now of data type int32.
disp( class(C{2}) )
int32
Read the first column of the file in the previous example into a cell array, skipping the rest of the line.
Open Live Script
filename = fullfile(matlabroot,'examples','matlab','scan1.dat');
fileID = fopen(filename);
dates = textscan(fileID,'%s %*[^\n]');
fclose(fileID);
dates{1}
Load the file data.csv and preview its contents in a text editor. A screen shot is shown below. Notice the file contains
data sperated by commas and also contains empty values. Open Live Script
filename = fullfile(matlabroot,'examples','matlab','data.csv');
fileID = fopen(filename);
C = textscan(fileID,'%f %f %f %f %u8 %f',...
'Delimiter',',','EmptyValue',-Inf);
fclose(fileID);
column4 = C{4}, column5 = C{5}
column4 =
4
-Inf
0
11
textscan returns a 1-by-6 cell array, C. The textscan function converts the empty value in C{4} to -Inf, where C{4} is associated with a floating-point format.
Because MATLAB® represents unsigned integer -Inf as 0, textscan converts the empty value in C{5} to 0, and not -Inf.
Load the file data2.csv and preview its contents in a text editor. A screen shot is shown below. Notice the file contains
data that can be interpreted as comments and other entries such as 'NA' or 'na' that may indicate empty fields. Open Live Script
filename = fullfile(matlabroot,'examples','matlab','data2.csv');
Designate the input that textscan should treat as comments or empty values and scan the data into C.
fileID = fopen(filename);
C = textscan(fileID,'%s %n %n %n %n','Delimiter',',',...
'TreatAsEmpty',{'NA','na'},'CommentStyle','//');
fclose(fileID);
C{1}{1} =
abc
C{1}{2} =
def
C{2} =
2
NaN
C{3} =
NaN
5
C{4} =
3
6
C{5} =
4
7
Load the file data3.csv and preview its contents in a text editor. A screen shot is shown below. Notice the file contains
repeated delimiters. Open Script
filename = fullfile(matlabroot,'examples','matlab','data3.csv');
To treat the repeated commas as a single delimiter, use the MultipleDelimsAsOne parameter, and set the value to 1 (true).
fileID = fopen(filename);
C = textscan(fileID,'%f %f %f %f','Delimiter',',',...
'MultipleDelimsAsOne',1);
fclose(fileID);
celldisp(C)
C{1} =
1
5
C{2} =
2
6
C{3} =
3
7
C{4} =
4
8
Load the data file grades.txt for this example and preview its contents in a text editor. A screen shot is shown below.
Notice the file contains repeated delimiters. Open Live Script
filename = fullfile(matlabroot,'examples','matlab','grades.txt');
Read the column headers using the format '%s' four times.
fileID = fopen(filename);
formatSpec = '%s';
N = 4;
C_text = textscan(fileID,formatSpec,N,'Delimiter','|');
The default value for CollectOutput is 0 (false), so textscan returns each column of the numeric data in a separate array.
frewind(fileID);
Reread the file and set CollectOutput to 1 (true) to collect the consecutive columns of the same class into a single array. You can use the repmat function to indicate
that the %f conversion specifier should appear three times. This technique is useful when a format repeats many times.
C_text = textscan(fileID,'%s',N,'Delimiter','|');
C_data1 = textscan(fileID,['%d',repmat('%f',[1,3])],'CollectOutput',1)
The test scores, which are all double, are collected into a single 4-by-3 array.
fclose(fileID);
Read the first and last columns of data from a text file. Skip a column of text and a column of integer data.
Open Live Script
Load the file names.txt and preview its contents in a text editor. A screen shot is shown below. Notice that file contains
two cloumns of quoted text, followed by a column of intergers, and finally a column of floating point numberes.
filename = fullfile(matlabroot,'examples','matlab','names.txt');
Read the first and last columns of data in the file. Use the conversion specifier, %q to read the text enclosed by double quotation marks ("). %*q skips the quoted text,
%*d skips the integer field, and %f reads the floating-point number. Specify the comma delimiter using the 'Delimiter' name-value pair argument.
fileID = fopen(filename,'r');
C = textscan(fileID,'%q %*q %*d %f','Delimiter',',');
fclose(fileID);
celldisp(C)
C{1}{1} =
Smith, J.
C{1}{2} =
Bates, G.
C{1}{3} =
Curie, M.
C{1}{4} =
Murray, G.
C{1}{5} =
Brown, K.
C{2} =
71.1000
69.3000
64.1000
133.0000
64.9000
Load the file german_dates.txt and preview its contents in a text editor. A screen shot is shown below. Notice that the
first column of values contains dates in German and the second and third columns are numeric values. Open Live Script
filename = fullfile(matlabroot,'examples','matlab','german_dates.txt');
Open the file. Specify the character encoding scheme associated with the file as the last input to fopen.
fileID = fopen(filename,'r','n','ISO-8859-15');
Read the file. Specify the format of the dates in the file using the %{dd % MMMM yyyy}D specifier. Specify the locale of the dates using the DateLocale name-value pair
argument.
View the contents of the first cell in C. The dates display in the language MATLAB uses depending on your system locale.
C{1}
lyric = sprintf('Blackbird\fsinging\fin\fthe\fdead\fof\fnight');
C = textscan(lyric,'%s','delimiter',sprintf('\f'));
C{1}
Resume Scanning
For example, create a character vector called lyric. Read the first word of the character vector, and then resume the scan.
File identifier of an open text file, specified as a number. Before reading a file with textscan, you must use fopen to open the file and obtain the fileID.
Format of the data fields, specified as a character vector or a string of one or more conversion specifiers. When textscan reads the input, it attempts to match the data
to the format specified in formatSpec. If textscan fails to match a data field, it stops reading and returns all fields read before the failure.
The number of conversion specifiers determines the number of cells in output array, C.
Numeric Fields
%d8 int8
%d16 int16
%d32 int32
%d64 int64
%u8 uint8
%u16 uint16
%u32 uint32
%u64 uint64
%f32 single
%f64 double
Numeric Input Type Conversion Specifier Output Class
%n double
Nonnumeric Fields
This table lists available conversion specifiers for inputs that include nonnumeric characters.
%q Read as a cell array of character vectors. If the text begins with a double quotation mark ("), omit
the leading quotation mark and its accompanying closing mark, which is the second instance of a
lone double quotation mark. Replace escaped double quotation marks (for example, ""abc"") with
lone double quotation marks ("abc"). %q ignores any double quotation marks that appear after the
closing double quotation mark.
Example: '%q' reads '"Joe ""Lightning"" Smith, Jr."' as 'Joe "Lightning" Smith,
Jr.'.
Dates and time %D Read the same way as %q above, and then convert to a datetime value.
%{fmt}D Read the same way as %q above, and then convert it to a datetime value. fmt describes the format
of the input text. The fmt input is a character vector of letter identifiers that is a valid value for the
Format property of a datetime. textscan converts text that does not match this format to NaT
values.
For more information about datetime display formats, see the Format property for datetime arrays.
Category %C Read the same way as %q, and then convert to a category name in a categorical array. textscan
converts <undefined> text to an undefined value in the output categorical array.
Pattern-matching %[...] Read as a cell array of character vectors, the characters inside the brackets up to the first
nonmatching character. To include ] in the set, specify it first: %[]...].
%[^...] Exclude characters inside the brackets, reading until the first matching character. To exclude ],
specify it first: %[^]...].
Optional Operators
Conversion specifiers in formatSpec can include optional operators, which appear in the following order (includes spaces for clarity):
%*k Skip the field. k is any conversion specifier identifying the field to skip. textscan does not create an output cell for any such fields.
Example: '%s %*s %s %s %*s %*s %s' (spaces are optional) converts the text
'Blackbird singing in the dead of night' into four output cells with
'Blackbird' 'in' 'the' 'night'
'%*ns' Skip up to n characters, where n is an integer less than or equal to the number of characters in the field.
Example: '%*3s %s' converts 'abcdefg' to 'defg'. When the delimiter is a comma, the same delimiter converts 'abcde,fghijkl' to a
cell array containing 'de';'ijkl'.
• Field Width
textscan reads the number of characters or digits specified by the field width or precision, or up to the first delimiter, whichever comes first. A decimal point, sign (+
or -), exponent character, and digits in the numeric exponent are counted as characters and digits within the field width. For complex numbers, the field width refers
to the individual widths of the real part and the imaginary part. For the imaginary part, the field width includes + or − but not i or j. Specify the field width by
inserting a number after the percent character (%) in the conversion specifier.
Example: %5f reads '123.456' as 123.4.
Example: %5c reads 'abcdefg' as 'abcde'.
When the field width operator is used with single characters (%c), textscan also reads delimiter, white-space, and end-of-line characters.
Example: %7c reads 7 characters, including white-space, so'Day and night' reads as 'Day and'.
• Precision
For floating-point numbers (%n, %f, %f32, %f64), you can specify the number of decimal digits to read.
Example: %7.2f reads '123.456' as 123.45.
• Literal Text to Ignore
textscan ignores the text appended to the formatSpec conversion specifier.
Example: Level%u8 reads 'Level1' as 1.
Example: %u8Step reads '2Step' as 2.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Example: C = textscan(fileID,formatSpec,'HeaderLines',3,'Delimiter',',') skips the first three lines of the data, and then reads the remaining data, treating
commas as a delimiter.
Logical indicator determining data concatenation, specified as the comma-separated pair consisting of 'CollectOutput' and either true or false. If true, then the
importing function concatenates consecutive output cells of the same fundamental MATLAB® class into a single array.
Symbols designating text to ignore, specified as the comma-separated pair consisting of 'CommentStyle' and a character vector, cell array of character vectors, string,
or string array.
For example, specify a character such as '%' to ignore text following the symbol on the same line. Specify a cell array of two character vectors, such as {'/*',
'*/'}, to ignore any text between those sequences.
MATLAB checks for comments only at the start of each field, not within a field.
Locale for reading dates, specified as the comma-separated pair consisting of 'DateLocale' and a character vector in the form xx_YY, where xx is a lowercase ISO
639-1 two-letter code that specifies a language, and YY is an uppercase ISO 3166-1 alpha-2 code that specifies a country. For a list of common values for the locale,
see the Locale name-value pair argument for the datetime function.
Use DateLocale to specify the locale in which textscan should interpret month and day of week names and abbreviations when reading text as dates using the %D
format specifier.
Example: 'DateLocale','ja_JP'
Field delimiter characters, specified as the comma-separated pair consisting of 'Delimiter' and a character vector or a cell array of character vectors. Specify
multiple delimiters in a cell array of character vectors.
Example: 'Delimiter',{';','*'}
textscan interprets repeated delimiter characters as separate delimiters, and returns an empty value to the output cell.
Within each row of data, the default field delimiter is white-space. White-space can be any combination of space (' '), backspace ('\b'), or tab ('\t') characters. If
you do not specify a delimiter, then:
• the delimiter characters are the same as the white-space characters. The default white-space characters are ' ', '\b', and '\t'. Use the 'Whitespace' name-
value pair argument to specify alternate white-space characters.
• textscan interprets repeated white-space characters as a single delimiter.
When you specify one of the following escape sequences as a delimiter, textscan converts that sequence to the corresponding control character:
\b Backspace
\n Newline
\r Carriage return
\t Tab
\\ Backslash (\)
Returned value for empty numeric fields in delimited text files, specified as the comma-separated pair consisting of 'EmptyValue' and a scalar.
End-of-line characters, specified as the comma-separated pair consisting of 'EndOfLine' and a character vector or string. The character vector must be '\r\n' or it
must specify a single character. Common end-of-line characters are a newline character ('\n') or a carriage return ('\r'). If you specify '\r\n', then the importing
function treats any of \r, \n, and the combination of the two (\r\n) as end-of-line characters.
The default end-of-line sequence is \n, \r, or \r\n, depending on the contents of your file.
If there are missing values and an end-of-line sequence at the end of the last line in a file, then the importing function returns empty values for those fields. This
ensures that individual cells in output cell array, C, are the same size.
Example: 'EndOfLine',':'
Example: "EndOfLine",":"
Exponent characters, specified as the comma-separated pair consisting of 'ExpChars' and a character vector or string. The default exponent characters are e, E, d,
and D.
Number of header lines, specified as the comma-separated pair consisting of 'HeaderLines' and a positive integer. textscan skips the header lines, including the
remainder of the current line.
Multiple delimiter handling, specified as the comma-separated pair consisting of 'MultipleDelimsAsOne' and either true or false. If true, then the importing
function treats consecutive delimiters as a single delimiter. Repeated delimiters separated by white-space are also treated as a single delimiter. You must also specify
the Delimiter option.
Example: 'MultipleDelimsAsOne',1
Behavior when textscan fails to read or convert, specified as the comma-separated pair consisting of 'ReturnOnError' and either true or false. If true, textscan
terminates without an error and returns all fields read. If false, textscan terminates with an error and does not return an output cell array.
Placeholder text to treat as empty value, specified as the comma-separated pair consisting of 'TreatAsEmpty' and a character vector, cell array of character vectors,
string, or string array. This option only applies to numeric fields.
When you specify one of the following escape sequences as any white-space character, textscan converts that sequence to the corresponding control character:
\b Backspace
\n Newline
\r Carriage return
\t Tab
\\ Backslash (\)
Output data type of text, specified as the comma-separated pair consisting of 'TextType' and either 'char' or 'string'. If you specify the value 'char', then
textscan returns text as a cell array of character vectors. If you specify the value 'string', then textscan returns text as an array of type string.
For each numeric conversion specifier in formatSpec, the textscan function returns a K-by-1 MATLAB numeric vector to the output cell array, C, where K is the
number of times that textscan finds a field matching the specifier.
For each text conversion specifier (%s, %q, or %[...]) in formatSpec, the textscan function returns a K-by-1 cell array of character vectors, where K is the number of
times that textscan finds a field matching the specifier. For each character conversion that includes a field width operator, textscan returns a K-by-M character array,
where M is the field width.
For each datetime or categorical conversion specifier in formatSpec, the textscan function returns a K-by-1 datetime or categorical vector to the output cell array, C,
where K is the number of times that textscan finds a field matching the specifier.
Position at the end of the scan, in the file or the character vector, returned as an integer of class double. For a file, ftell(fileID) would return the same value after
calling textscan. For a character vector, position indicates how many characters textscan read.
Algorithms
textscan converts numeric fields to the specified output type according to MATLAB rules regarding overflow, truncation, and the use of NaN, Inf, and -Inf. For example,
MATLAB represents an integer NaN as zero. If textscan finds an empty field associated with an integer format specifier (such as %d or %u), it returns the empty value as zero
and not NaN.
When matching data to a text conversion specifier, textscan reads until it finds a delimiter or an end-of-line character. When matching data to a numeric conversion
specifier, textscan reads until it finds a nonnumeric character. When textscan can no longer match the data to a particular conversion specifier, it attempts to match the
data to the next conversion specifier in the formatSpec. Sign (+ or -), exponent characters, and decimal points are considered numeric characters.
Read one sign Read one or more Read one decimal point If there is a decimal point, Read one exponent If there is an exponent If there is an exponent
character if it exists. digits. if it exists. read one or more digits character if it exists. character, read one character, read one or
that immediately follow it. sign character. more digits that follow it.
textscan imports any complex number as a whole into a complex numeric field, converting the real and imaginary parts to the specified numeric type (such as %d or %f).
Valid forms for a complex number are:
Do not include embedded white space in a complex number. textscan interprets embedded white space as a field delimiter.
See Also
dlmread | fopen | fread | fscanf | load | readtable | uiimport | xlsread
Topics
Import Data from a Nonrectangular Text File
Import Large Text File Data in Blocks
Access Data in Cell Array
Ways to Import Text Files
Syntax
writetable(T)
writetable(T,filename)
writetable( ___ ,Name,Value)
Description
writetable(T) writes table T to a comma delimited text file. The file name is the workspace variable name of the table, appended with the extension .txt. If example
writetable cannot construct the file name from the input table name, then it writes to the file table.txt.
Each column of each variable in T becomes a column in the output file. The variable names of T become column headings in the first line of the file.
writetable(T,filename) writes to a file with the name and extension specified by filename.
writetable 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
• .xls, .xlsm, or .xlsx for Excel® spreadsheet files
• .xlsb for Excel spreadsheet files supported on systems with Excel for Windows®
example
writetable( ___ ,Name,Value) writes the table 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.
For example, you can specify whether to write the variable names as column headings in the output file.
Create a table.
Open Live Script
T = 3×4 table
Var1 Var2 Var3 Var4
____ ________ ____ _____
M 45 45 'NY' true
F 41 32 'CA' false
M 40 34 'MA' false
Write the table to a comma delimited text file and display the file contents.
writetable(T)
type 'T.txt'
Var1,Var2_1,Var2_2,Var3,Var4
M,45,45,NY,1
F,41,32,CA,0
M,40,34,MA,0
writetable appends a unique suffix to the variable name, Var2, above the two columns of corresponding data.
Create a table.
Open Live Script
T = 3×4 table
Var1 Var2 Var3 Var4
____ ________ ____ _____
M 45 45 'NY' true
F 41 32 'CA' false
M 40 34 'MA' false
Write the table to a space-delimited text file named myData.txt and display the file contents.
writetable(T,'myData.txt','Delimiter',' ')
type 'myData.txt'
Var1 Var2_1 Var2_2 Var3 Var4
M 45 45 NY 1
F 41 32 CA 0
M 40 34 MA 0
writetable appends a unique suffix to the variable name, Var2, above the two columns of corresponding data.
Create a table.
Open Live Script
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T = table(Age,Height,Weight,BloodPressure,...
'RowNames',LastName)
T = 5×4 table
Age Height Weight BloodPressure
___ ______ ______ _____________
Write the table, T, to a comma delimited text file, called myPatientData.dat, and display the file contents.
writetable(T,'myPatientData.dat','WriteRowNames',true)
type 'myPatientData.dat'
Row,Age,Height,Weight,BloodPressure_1,BloodPressure_2
Smith,38,71,176,124,93
Johnson,43,69,163,109,77
Williams,38,64,131,125,83
Jones,40,67,133,117,75
Brown,49,64,119,122,80
The first column, which contains the row names, has the column heading, Row. This is the first dimension name for the table from the property
T.Properties.DimensionNames.
Convert English dates in a table to German and write the table to file.
Open Script
Create a table that contains a datetime array with dates in English. Create column vectors of numeric data to go with the
dates.
D = datetime({'01-Jan-2014';'01-Feb-2014';'01-Mar-2014'});
D.Format = 'dd MMMM yyyy';
X1 = [20.2;21.6;20.7];
X2 = [100.5;102.7;99.8];
T = table(D,X1,X2)
T =
D X1 X2
________________ ____ _____
Write the table to a text file. Specify German for the locale of the dates using the DateLocale name-value pair argument, and display the dates in the text file.
writetable(T,'myfile.txt','DateLocale','de_DE');
type myfile.txt
D,X1,X2
01 Januar 2014,20.2,100.5
01 Februar 2014,21.6,102.7
01 März 2014,20.7,99.8
Load Table_Japanese_Characters.mat which contains a table T. A preview of the table is shown below. Notice that the table contains two columns with Japanese
characters.
load('Table_Japanese_Characters.mat')
Write the table to a file. The writetable function uses your system default encoding when writing files. Results may differ based on your system settings. To examine
the resulting file, read the table back into the workspace by using the readtable function. Notice that writetable did not succeed in writing columns (1 and 3)
containing foreign-lanaguage characters.
writetable(T,'myTable.txt')
myTable = readtable('myTable.txt')
myTable =
A B C
_____ ______ _______
If your table contains foreign-language or non-ASCII characters, use the 'Encoding' parameter to ensure your data is written correctly. Set 'Encoding' to 'UTF-8'
which supports a wide range of foreign-language and non-ASCII characters. To examine the resulting file, read the table back into the workspace by using the
readtable function. Notice that this time the writetable function was successful in writing the data.
writetable(T,'myTable_UTF8.txt','Encoding','UTF-8')
myTable_UTF8 = readtable('myTable_UTF8.txt','Encoding','UTF-8')
myTable_UTF8 =
A B C
_____ ______ _______
Create a table.
Open Live Script
T = table(['M';'F';'M'],[45;41;36],...
{'New York, NY';'San Diego, CA';'Boston, MA'},[true;false;false])
T = 3×4 table
Var1 Var2 Var3 Var4
____ ____ _______________ _____
Write the table to a comma-separated text file named myData.csv and view the file contents. Use the 'QuoteStrings' name-value pair argument to ensure that the
commas in the third column are not treated as delimiters.
writetable(T,'myData.csv','Delimiter',',','QuoteStrings',true)
type 'myData.csv'
Var1,Var2,Var3,Var4
"M",45,"New York, NY",1
"F",41,"San Diego, CA",0
"M",36,"Boston, MA",0
Create a table.
Open Live Script
T = 3×4 table
Var1 Var2 Var3 Var4
____ ________ ____ _____
M 45 45 'NY' true
F 41 32 'CA' false
M 40 34 'MA' false
Write the table to a spreadsheet named myData.xls. Include the data on the second sheet in the 5-by-5 region with corners at B2 and F6.
writetable(T,'myData.xls','Sheet',2,'Range','B2:F6')
Excel® fills the row of the spreadsheet from B6 to F6 with #N/A since the range specified is larger than the size of the input table T.
T — Input data
table
File name, specified as a character vector or string. To write to a specific folder, specify the full path name. Otherwise, writetable writes to a file in the current folder. If
filename includes the file extension, then writetable determines the file format from the extension. Otherwise, writetable 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.
Example: 'C:\test\myData.txt'
Example: 'WriteVariableNames',false 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
writetable can determine the file type from an extension in the filename input argument. writetable can determine the file type from these extensions:
Example: writetable(T,'mySpreadsheet','FileType','spreadsheet')
Indicator for writing variable names as column headings, specified as the comma-separated pair consisting of 'WriteVariableNames' and either true, false, 1, or 0.
Indicator Behavior
true writetable includes variable names as the column headings of the output. This is the default behavior.
If both the 'WriteVariableNames' and 'WriteRowNames' logical indicators are true, then writetable uses the first dimension name
from the property T.Properties.DimensionNames as the column heading for the first column of the output.
Indicator for writing row names in first column, specified as the comma-separated pair consisting of 'WriteRowNames' and either false, true, 0, or 1.
Indicator Behavior
false writetable does not include the row names from T in the output. This is the default behavior.
true writetable includes the row names from T as the first column of the output.
If both the 'WriteVariableNames' and 'WriteRowNames' logical indicators are true, then writetable uses the first dimension name
from the property T.Properties.DimensionNames as the column heading for the first column of the output.
Locale for writing dates, specified as the comma-separated pair consisting of 'DateLocale' and a character vector or a string. When writing datetime values to the
file, use DateLocale to specify the locale in which writetable 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.
writetable ignores the 'DateLocale' parameter value whenever dates can be written as Excel-formatted dates. See Algorithms for more information.
Field delimiter character, specified as the comma-separated pair consisting of 'Delimiter' and a character vector or string containing one of the following specifiers.
'comma'
'space'
'\t' Tab
'tab'
';' Semicolon
'semi'
'bar'
You can use the 'Delimiter' name-value pair only for delimited text files.
You can use the 'QuoteStrings' name-value pair 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 like one of the values in this table. When you do not specify any encoding or specify encoding as 'system', the writetable function uses your system
default encoding to write the file.
'Macintosh' 'UTF-8'
'Shift_JIS'
Worksheet to write to, specified as the comma-separated pair consisting of 'Sheet' and a character vector or a string 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 [status,sheets]
= xlsfinfo(filename).
If the sheet does not exist, then writetable adds a new sheet at the end of the worksheet collection. If the sheet is an index larger than the number of worksheets,
then writetable appends empty sheets until the number of worksheets in the workbook equals the sheet index. In either case, writetable generates a warning
indicating that it has added a new worksheet.
You can use the 'Sheet' name-value pair only with spreadsheet files.
Example: 'Sheet',2
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 in one of the following
forms.
'Corner1' Corner1 specifies the first cell of the region to write. writetable writes table T beginning at this cell.
Example: 'Range','D2'
'Corner1:Corner2' 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 table T, then writetable writes only a subset of the
input table that fits into the range.
• If the range you specify is larger than the size of the input table T, then writetable leaves the remainder of the
region as it is.
The 'Range' name-value pair can only be used with Excel files.
Limitations
• On Linux® platforms, the xlsread function or the Import Tool cannot open spreadsheet files written by the writetable function.
Algorithms
• Excel converts Inf values to 65535. MATLAB® converts NaN, NaT, <undefined> categorical values, and <missing> string values to empty cells.
• For Excel files, writetable writes table variables containing datetime arrays as Excel dates. If the table contains datetime arrays with years prior to either 1900 or
1904, then writetable writes the variables as text. For more information on Excel dates, see https://support.microsoft.com/en-us/kb/214330.
• There are some instances where the writetable function creates a file that does not represent T exactly. You will notice this when you use readtable to read that file.
The resulting table might not have the same format or contents as the original table. If you need to save a table and retrieve it at a later time to match the original table
exactly, with the same data and organization, then save it as a MAT-file. writetable writes an inexact table in the following instances:
˗ When writing to text files, writetable outputs numeric variables using long g format, and categorical or character variables as unquoted characters.
˗ For variables that have more than one column, writetable appends a unique identifier to the variable name to use as the column headings.
˗ For output variables that have more than two dimensions, writetable outputs these variables as two dimensional where the trailing dimensions are collapsed. For
example, writetable outputs a 4-by-3-by-2 variable as if its size were 4-by-6.
˗ For variables with a cell data type, writetable outputs the contents of each cell as a single row, in multiple fields. If the contents are other than numeric, logical,
character, or categorical, then writetable outputs a single empty field.
See Also
readtable | table
Introduced in R2013b
Access Data in a Table
If you use curly braces, the resulting array is the horizontal concatenation of the specified table variables containing only the specified rows. The data types of all the
specified variables must be compatible for concatenation. You can then perform calculations using MATLAB® functions.
Dot indexing extracts data from one table variable. The result is an array of the same data type as extracted variable. You can follow the dot indexing with parentheses to
specify a subset of rows to extract from a variable.
T.Variables horizontally concatenates all table variables into an array. T.Variables is equivalent to T{:,:}.
To subscript into a table and select variables of a specified type, use the vartype function.
Parentheses table T(rows,vars) One or more rows, specified by rows One or more variables, specified by vars
Curly Braces extracted data T{rows,vars} One or more rows, specified by rows One or more variables, specified by vars
Dot Indexing extracted data T.var All rows One variable, specified by var (a name) or by
varindex (a number)
T.(varindex)
Dot Indexing extracted data T.var(rows) One or more rows, specified by rows One variable, specified by var (a name)
Variables Property extracted data T.Variables All rows All variables when they can be horizontally
concatenated into an array
Subscripting by Variable table S = vartype(type); One or more rows, specified by rows One or more variables of the specified type (for
Type example, 'numeric')
T(rows,S)
Subscripting by Variable extracted data S = vartype(type); One or more rows, specified by rows One or more variables of the specified type (for
Type example, 'numeric')
T{rows,S}
A logical expression can contain curly braces or dot indexing to extract data from which you can define the subset of rows. For example, rows = T.Var2>0 returns a logical
array with logical true (1) for rows where the value in the variable Var2 is greater than zero.
When using dot indexing, you must specify a single variable to access. For a single variable name, use T.var. For a single variable index, specified as a positive integer, use
T.(varindex).
Load the sample patients data and create a table. Use the unique identifiers in LastName as row names.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);
View the data type, description, units, and other descriptive statistics for each variable by using summary to summarize the table.
summary(patients)
Variables:
Values:
Min 25
Median 39
Max 50
Values:
Min 60
Median 67
Max 72
Values:
Min 111
Median 142.5
Max 202
Values:
True 34
False 66
Index Using Numeric Indices
Create a subtable containing the first five rows and all the variables from the table, patients. Use numeric indexing within the parentheses to specify the desired rows and
variables. This is similar to indexing with numeric arrays.
T1 = patients(1:5,:)
T1 = 5×5 table
Age Gender Height Weight Smoker
___ ________ ______ ______ ______
T1 is a 5-by-5 table. In addition to numeric indices, you can use row or variable names inside the parentheses. In this case, using row indices and a colon is more compact
than using row or variable names.
Select all the data for the patients with the last names 'Adams' and 'Brown'. In this case, it is simpler to use the row names than to use the numeric index.
T2 = patients({'Adams','Brown'},:)
T2 = 2×5 table
Age Gender Height Weight Smoker
___ ________ ______ ______ ______
T2 is a 2-by-5 table.
Create a new table, T3, containing the gender, height, and weight of the patients under the age of 30. Select only the rows where the value in the variable, Age, is less than
30.
Use dot notation to extract data from a table variable and a logical expression to define the subset of rows based on that extracted data.
rows = patients.Age<30;
vars = {'Gender','Height','Weight'};
rows is a 100-by-1 logical array containing logical true (1) for rows where the value in the variable, Age, is less than 30.
Use parentheses to return a table containing the desired subset of the data.
T3 = patients(rows,vars)
T3 = 15×3 table
Gender Height Weight
________ ______ ______
T3 is a 15-by-3 table.
Load the sample patients data and create a table. Use the unique identifiers in LastName as row names.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);
Extract data from multiple variables in the table, patients by using curly braces. Since dot indexing extracts data from a single variable at a time, braces are more
convenient when you want to extract more than one variable.
Extract the height and weight for the first five patients. Use numeric indices to select the subset of rows, 1:5, and variable names to select the subset of variables,
{Height,Weight}.
A = patients{1:5,{'Height','Weight'}}
A =
71 176
69 163
64 131
67 133
64 119
Use dot indexing to easily extract the contents of a single variable. Plot a histogram of the numeric data in the variable, Weight.
figure()
histogram(patients.Weight)
title(' Patient Weight')
patients.Weight is a double-precision column vector with 100 rows. Alternatively, you can use curly braces, patients{:,'Weight'}, to extract all the rows for the
variable Weight.
To specify a subset of rows for a single variable, you can follow the dot indexing with parentheses or curly braces. Extract the heights of the nonsmoker patients under the
age of 30.
Use dot notation to extract data from table variables and a logical expression to define the subset of rows based on that extracted data.
Use dot notation to extract the desired rows from the variable, Height.
patients.Height(rows)
ans =
68
71
70
63
64
63
65
66
68
66
The output is a 11-by-1 numeric array. Alternatively, you can specify the single variable, Height, within curly braces to extract the desired data, patients{rows,'Height'}.
See Also
histogram | summary | table | Table Properties
Related Examples
• Create and Work with Tables
• Modify Units, Descriptions and Table Variable Names
• Calculations on Tables
More About
• Advantages of Using Tables
Calculations on Tables
This example shows how to perform calculations on tables.
Open Live Script
The functions rowfun and varfun each apply a specified function to a table, yet many other functions require numeric or
homogeneous arrays as input arguments. You can extract data from individual variables using dot indexing or from one or more
variables using curly braces. The extracted data is then an array that you can use as input to other functions.
T = readtable(fullfile(matlabroot,'examples','matlab','testScores.csv'),...
'ReadRowNames',true)
T = 10×4 table
Gender Test1 Test2 Test3
________ _____ _____ _____
HOWARD 'male' 90 87 93
WARD 'male' 87 85 83
TORRES 'male' 86 85 88
PETERSON 'female' 75 80 72
GRAY 'female' 89 86 87
RAMIREZ 'female' 96 92 98
JAMES 'male' 78 75 77
WATSON 'female' 91 94 92
BROOKS 'female' 86 83 85
KELLY 'male' 79 76 82
summary(T)
Variables:
Values:
Min 75
Median 86.5
Max 96
Values:
Min 75
Median 85
Max 94
Values:
Min 72
Median 86
Max 98
The summary contains the minimum, median, and maximum score for each test.
T.TestAvg = mean(T{:,2:end},2)
T = 10×5 table
Gender Test1 Test2 Test3 TestAvg
________ _____ _____ _____ _______
HOWARD 'male' 90 87 93 90
WARD 'male' 87 85 83 85
TORRES 'male' 86 85 88 86.333
PETERSON 'female' 75 80 72 75.667
GRAY 'female' 89 86 87 87.333
RAMIREZ 'female' 96 92 98 95.333
JAMES 'male' 78 75 77 76.667
WATSON 'female' 91 94 92 92.333
BROOKS 'female' 86 83 85 84.667
KELLY 'male' 79 76 82 79
Alternatively, you can use the variable names, T{:,{'Test1','Test2','Test3'}} or the variable indices, T{:,2:4} to select the subset of data.
varfun(@mean,T,'InputVariables','TestAvg',...
'GroupingVariables','Gender')
'female' 5 87.067
'male' 5 83.4
T{:,2:end} = T{:,2:end}*25/100
T = 10×5 table
Gender Test1 Test2 Test3 TestAvg
________ _____ _____ _____ _______
T.Properties.VariableNames{end} = 'Final'
T = 10×5 table
Gender Test1 Test2 Test3 Final
________ _____ _____ _____ ______
See Also
findgroups | rowfun | splitapply | summary | table | Table Properties | varfun
Related Topics
• Access Data in a Table
• Split Table Data Variables and Apply Functions
Modify Units, Descriptions and Table Variable Names
This example shows how to access and modify table properties for variable units, descriptions and names. You also can edit
these property values using the Variables Editor. Open Live Script
load patients
BloodPressure = [Systolic Diastolic];
T = table(Gender,Age,Height,Weight,Smoker,BloodPressure);
T(1:5,:)
An individual empty character vector within the cell array indicates that the corresponding variable does not have units.
T.Properties.VariableDescriptions{'BloodPressure'} = 'Systolic/Diastolic';
You can use the variable name, 'BloodPressure', or the numeric index of the variable, 6, to index into the cell array of character vectors containing the variable
descriptions.
summary(T)
Variables:
Units: Yrs
Values:
Min 25
Median 39
Max 50
Units: In
Values:
Min 60
Median 67
Max 72
Units: Lbs
Values:
Min 111
Median 142.5
Max 202
True 34
False 66
Description: Systolic/Diastolic
Values:
BloodPressure_1 BloodPressure_2
_______________ _______________
Min 109 68
Median 122 81.5
Max 138 99
The BloodPressure variable has a description and the Age, Height, Weight, and BloodPressure variables have units.
T.Properties.VariableNames{'Gender'} = 'Sex';
T(1:5,:)
In addition to properties for variable units, descriptions and names, there are table properties for row and dimension names, a table description, and user data.
See Also
array2table | cell2table | readtable | struct2table | summary | table | Table Properties
Related Topics
• Add and Delete Table Variables
• Access Data in a Table
Create and Work with Tables
This example shows how to create a table from workspace variables, work with table data, and write tables to files for later use. table is a
data type for collecting heterogeneous data and metadata properties such as variable names, row names, descriptions, and variable units, Open Live Script
in a single container.
Tables are suitable for column-oriented or tabular data that are often stored as columns in a text file or in a spreadsheet. Each variable in a table can have a different data type, but
must have the same number of rows. However, variables in a table are not restricted to column vectors. For example, a table variable can contain a matrix with multiple columns as
long as it has the same number of rows as the other table variables. A typical use for a table is to store experimental data, where rows represent different observations and columns
represent different measured variables.
Tables are convenient containers for collecting and organizing related data variables and for viewing and summarizing data. For example, you can extract variables to perform
calculations and conveniently add the results as new table variables. When you finish your calculations, write the table to a file to save your results.
Load sample data for 100 patients from the patients MAT-file to workspace variables.
load patients
whos
Create a table and populate it with the Gender, Smoker, Height, and Weight workspace variables. Display the first five rows.
T = table(Gender,Smoker,Height,Weight);
T(1:5,:)
As an alternative, use the readtable function to read the patient data from a comma-delimited file. readtable reads all the columns that are in a file.
T2 = readtable('patients.dat');
T2(1:5,:)
You can assign more column-oriented table variables using dot notation, T.varname, where T is the table and varname is the desired variable name. Create identifiers that are random
numbers. Then assign them to a table variable, and name the table variable ID. All the variables you assign to a table must have the same number of rows. Display the first five rows of
T.
T.ID = randi(1e4,100,1);
T(1:5,:)
All the variables you assign to a table must have the same number of rows.
View the data type, description, units, and other descriptive statistics for each variable by creating a table summary using the summary function.
summary(T)
Variables:
Values:
True 34
False 66
Values:
Min 60
Median 67
Max 72
Values:
Min 111
Median 142.5
Max 202
Values:
Min 120
Median 5485.5
Max 9706
Return the size of the table.
size(T)
ans =
100 5
Create a new, smaller table containing the first five rows of T and display it. You can use numeric indexing within parentheses to specify rows and variables. This method is similar to
indexing into numeric arrays to create subarrays. Tnew is a 5-by-5 table.
Tnew = T(1:5,:)
Create a smaller table containing all rows of Tnew and the variables from the second to the last. Use the end keyword to indicate the last variable or the last row of a table. Tnew is a 5-
by-4 table.
Tnew = Tnew(:,2:end)
T.Properties.RowNames = LastName;
Return the size of T. The size does not change because row and variable names are not included when calculating the size of a table.
size(T)
ans =
100 5
Select all the data for the patients with the last names 'Smith' and 'Johnson'. In this case, it is simpler to use the row names than to use numeric indices. Tnew is a 2-by-5 table.
Tnew = T({'Smith','Johnson'},:)
Select the height and weight of the patient named 'Johnson' by indexing on variable names. Tnew is a 1-by-2 table.
Tnew = T('Johnson',{'Height','Weight'})
Johnson 69 163
You can access table variables either with dot syntax, as in T.Height, or by named indexing, as in T(:,'Height').
Calculate BMI using the table variables, Weight and Height. You can extract Weight and Height for the calculation while conveniently keeping Weight, Height, and BMI in the table
with the rest of the patient data. Display the first five rows of T.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2;
T(1:5,:)
Populate the variable units and variable descriptions properties for BMI. You can add metadata to any table variable to describe further the data contained in the variable.
T.Properties.VariableUnits{'BMI'} = 'kg/m^2';
T.Properties.VariableDescriptions{'BMI'} = 'Body Mass Index';
Create a histogram to explore whether there is a relationship between smoking and body-mass-index in this group of patients. You can index into BMI with the logical values from the
Smoker table variable, because each row contains BMI and Smoker values for the same patient.
tf = (T.Smoker == false);
h1 = histogram(T.BMI(tf),'BinMethod','integers');
hold on
tf = (T.Smoker == true);
h2 = histogram(T.BMI(tf),'BinMethod','integers');
xlabel('BMI (kg/m^2)');
ylabel('Number of Patients');
legend('Nonsmokers','Smokers');
title('BMI Distributions for Smokers and Nonsmokers');
hold off
Add blood pressure readings for the patients from the workspace variables Systolic and Diastolic. Each row contains Systolic, Diastolic, and BMI values for the same patient.
T.Systolic = Systolic;
T.Diastolic = Diastolic;
Create a histogram to show whether there is a relationship between high values of Diastolic and BMI.
Sort the table by row names so that patients are listed in alphabetical order.
T = sortrows(T,'RowNames');
T(1:5,:)
Create a BloodPressure variable to hold blood pressure readings in a 100-by-2 table variable.
T.Systolic = [];
T.Diastolic = [];
T(1:5,:)
T(1:5,:)
You also can reorder table variables by name. To reorder the table variables so that Gender is last:
varnames = T.Properties.VariableNames;
others = ~strcmp('Gender',varnames);
varnames = [varnames(others) 'Gender'];
T = T(:,varnames);
T(1:5,:)
writetable(T,'allPatientsBMI.txt');
You can use the readtable function to read the data in allPatientsBMI.txt into a new table.
Create a subtable and write the subtable to a separate file. Delete the rows that contain data on patients who are smokers. Then remove the Smoker variable. nonsmokers contains
data only for the patients who are not smokers.
nonsmokers = T;
toDelete = (nonsmokers.Smoker == true);
nonsmokers(toDelete,:) = [];
nonsmokers.Smoker = [];
writetable(nonsmokers,'nonsmokersBMI.txt');
See Also
array2table | cell2table | Import Tool | readtable | sortrows | struct2table | summary | table | Table Properties | writetable
Related Examples
• Clean Messy and Missing Data in Tables
• Modify Units, Descriptions and Table Variable Names
• Access Data in a Table
More About
• Advantages of Using Tables
End-to-End Deployment of MATLAB Function
If you are still in the process of developing a MATLAB® function that is not yet ready to be deployed, you may find this example to be an appropriate introduction to using
MATLAB Compiler™ for Excel® add-ins.
The Function Wizard allows you to iteratively test, develop, and debug your MATLAB function. It does this by invoking MATLAB from the Function Wizard Control Panel.
Developing your function in an interactive environment ensures that it works in an expected manner, prior to deployment to larger-scale applications. Usually, these
applications are programmed by the Excel Developer using an enterprise language like Microsoft® Visual Basic®.
Similar to the Magic Square example, the Prototyping and Debugging example develops a function named mymagic, which wraps a MATLAB function, magic, which
computes a magic square, a function with a single multidimensional matrix output.
If your MATLAB function is ready to be deployed and you have already built your add-in and COM component with the Deployment Tool, see Execute Functions and Create
Macros.
Task Reference
1. Review MATLAB Compiler for Excel add-ins prerequisites, if you have not already done MATLAB Compiler for Microsoft Excel Add-In Prerequisites
so.
2. Prepare to run the example by copying the example files. Example File Copying
3. Test the MATLAB function you want to deploy as an add-in or COM component. mymagic Testing
6. Select the prototyping and debugging workflow. Workflow Selection for Prototyping and Debugging MATLAB Functions
7. Define the new MATLAB function you want to prototype by adding it to the Function New MATLAB Function Definition
Wizard and establishing input and output ranges.
8. Test your MATLAB function by executing it with the Function Wizard. Function Execution from MATLAB
9. Prototype and Debug the MATLAB function if needed, using MATLAB and the Function MATLAB Function Prototyping and Debugging
Wizard.
10. Create the add-in and COM component, as well as the macro, using the Function Microsoft Excel Add-In and Macro Creation Using the Function Wizard
Wizard to invoke MATLAB and the Deployment Tool.
11. Execute the your function from the newly created component, to ensure the function's Function Execution from the Deployed Component
behavior is identical to when it was tested.
12. Execute the macro you created using the Function Wizard. Macro Execution
13. Package your deployable add-in and macro using the Function Wizard to invoke Microsoft Excel Add-In and Macro Packaging using the Function Wizard
MATLAB and the Deployment Tool.
14. Optionally inspect or modify the Microsoft Visual Basic code you generated with the Microsoft Visual Basic Code Access (Optional Advanced Task)
COM component. Optionally, attach the macro you created to a GUI button.
The Function Wizard provides an intuitive interface to Excel worksheets. You do not need previous knowledge of Microsoft Visual Basic for Applications (VBA) programming.
The Function Wizard reflects any changes that you make in the worksheets, such as range selections. You also use the Function Wizard to control the placement and output
of data from MATLAB functions to the worksheets.
Note: The Function Wizard does not currently support the MATLAB sparse, and complex data types.
For Example Files Relating To... Find Example Code in Folder... For Example Documentation See...
Magic Square Example xlmagic Integrate an Add-In and COM Component with Microsoft
Excel
Variable-Length Argument Example xlmulti Work with Variable-Length Inputs and Outputs
Calling Compiled MATLAB Functions from Microsoft Excel xlbasic Calling Compiled MATLAB Functions from Microsoft Excel
Spectral Analysis Example xlspectral Build and Integrate Spectral Analysis Functions
mymagic Testing
In this example, you test a MATLAB file (mymagic.m) containing the predefined MATLAB function magic. You test to have a baseline to compare to the results of the function
when it is ready to deploy.
1. In MATLAB, locate mymagic.m. See Example File Copying for locations of examples. The contents of the file are as follows:
function y = mymagic(x)
%MYMAGIC Magic square of size x.
% Y = MYMAGIC(X) returns a magic square of size x.
% This file is used as an example for the MATLAB Compiler product.
2. At the MATLAB command prompt, enter mymagic(5). View the resulting output, which appears as follows:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
After you install the Function Wizard, the entry MATLAB Functions appears as an available Microsoft Excel add-in button.
The Home tab of the Microsoft Office Ribbon should now contain the Function Wizard tile. See The Home Tab of the Microsoft Office Ribbon with Function Wizard Installed.
3. In the left pane of the Excel Options dialog box, click Add-Ins.
4. In the right pane of the Excel Options dialog box, select Excel Add-ins from the Manage drop-down box.
5. Click Go.
6. Click Browse. Navigate to matlabroot\toolbox\matlabxl\matlabxl\arch and select FunctionWizard2007.xlam. Click OK.
7. In the Excel Add-Ins dialog box, verify that the entry MATLAB Compiler Function Wizard is selected. Click OK.
The Home Tab of the Microsoft Office Ribbon with Function Wizard Installed
You can also access Function Wizard from the File tab.
1. Select File > Options > Add-Ins from the Excel main menu.
2. Select Function Wizard.
1. From the Function Wizard Start Page dialog box, select I have one or more MATLAB functions that I want to use in a workbook (MATLAB installation required).
The New Project option is selected by default. Enter a meaningful project name in the Project Name field, like testmymagic, for example.
Tip: Some customers find it helpful to assign a unique name as the Class Name (default is Class1) and to assign a Version number for source control purposes.
2. Click OK. The Function Wizard Control Panel displays with the Add Function button enabled.
• The project files created by the Function Wizard are the same project files created and used by the Deployment Tool (deploytool).
• The Function Wizard prompts you to specify a location for your project files when you open your first new project. Project files are auto-saved to this location and may be
opened in the future through either the Deployment Tool or the Function Wizard.
• If you previously built a component using the Function Wizard, the wizard will prompt you to load it.
2. Browse to locate your MATLAB function. Select the function and click Open.
3. In the New MATLAB Function dialog box, click Add. The Function Properties dialog box appears.
Tip: The Function Syntax and Help area, in the Function Properties dialog box, displays the first help text line (sometimes called the H1 line) in a MATLAB function. Displaying
these comments in the Function Properties dialog box can be helpful when deploying new or unfamiliar MATLAB functions to end-users.
Caution: Avoid selecting ranges using arrow keys. If you must use arrow keys to select ranges, apply the necessary fix from the Microsoft site:
http://support.microsoft.com/kb/291110.
c. Click Done.
Tip: To specify how MATLAB Compiler for Excel add-ins handles blank cells (or cells containing no data), see Empty Cell Value Control.
Tip: You can also specify MATLAB Compiler to Auto Resize, Transpose or output your data in date format (Output as date). To do so, select the appropriate option in the
Argument Properties For y dialog box.
b. Specify a Range. Alternately, select a range of cells on your Excel sheet; the range will be entered for you in the Range field.
Caution: Avoid selecting ranges using arrow keys. If you must use arrow keys to select ranges, apply the necessary fix from the Microsoft site:
http://support.microsoft.com/kb/291110.
1. If you have not already done so, select This is a MATLAB structure array argument in the Input Data for n dialog box and click OK.
The Input Data for Structure Array Argument n dialog box opens.
2. The Function Wizard supports Vector and Two-dimensional struct arrays organized in either Element by Element or Plane organization, for both input and output.
In the Input Data for Structure Array Argument n dialog box, do the following:
a. In the Structure Array Organization area, select either Element by Element Organization or Plane Organization.
b. Click Add Field to add fields for each of your struct array arguments. The Field for Structure Array Argument dialog box opens.
Caution: Avoid selecting ranges using arrow keys. If you must use arrow keys to select ranges, apply the necessary fix from the Microsoft site:
http://support.microsoft.com/kb/291110.
c. Click Done.
How Structure Arrays are Supported. MATLAB Compiler supports one and two-dimensional MATLAB structure arrays.
The product converts data passed into structure arrays in element-by-element organization or plane organization. See MATLAB Programming Fundamentals for more
information about all MATLAB data types, including structures.
Deploying Structure Arrays as Inputs and Outputs. If you are a MATLAB programmer and want to deploy a MATLAB function with structure arrays as input or output
arguments, build Microsoft Excel macros using the Function Wizard and pass them (with the Excel add-in and COM component) to the end users. If you can't do this, let your
end users know:
Using Macros with Struct Arrays. The macro generation feature of MATLAB Compiler for Excel add-ins works with struct arrays as input or output arguments. See Macro
Creation if you have a MATLAB function you are ready to deploy. See Microsoft Excel Add-In and Macro Creation Using the Function Wizard if you are using the Function
Wizard to create your MATLAB function from scratch. See Choosing Function Deployment Workflow for more information on both workflows.
Since mymagic calls the prewritten MATLAB magic function directly, it does not provide an illustrative example of how to use the prototyping and debugging feature of
MATLAB Compiler.
Following is an example of how you might use this feature with myprimes, a function containing multiple lines of code.
if p((k+1)/2)
p(((k*k+1)/2):k:q) = 0;
end
end
p = (p(p>0));
In designing your code, you want to handle various use cases. For example, you want to experiment with scenarios that may assign a column vector value to the output
variable p ( (myprimes only returns a row vector, as stated previously). You follow this general workflow:
1. Set a breakpoint in myprimes at the first if statement, using the GUI or dbstop, for instance.
2. On the Function Wizard Control Panel, in the Execute Functions area, click Execute. Execution will stop at the previously set breakpoint. Note the value of p. Step-
through and debug your code as you normally would using the MATLAB Editor.
For more information about debugging MATLAB code, see Debug a MATLAB Program (MATLAB).
1. From the Function Wizard Control Panel, in the Execute Functions area, select Execute MATLAB Functions in MATLAB.
2. Click Execute. In Excel, the Magic Square function executes, producing results similar to the following.
Microsoft Excel Add-In and Macro Creation Using the Function Wizard
The Function Wizard can automatically create a deployable Microsoft Excel add-in and macro. To create your add-in in this manner, use one of the following procedures.
1. In the Function Wizard Control Panel dialog box, in the Create Component area, select Create Both Excel Add-in Component and Excel Macro.
2. Enter mymagic in the Macro Name field.
3. Select the location of where to store the macro, using the Store Macro In drop-down box.
4. Enter a brief description of the macro's functionality in the Description field.
5. Click Create to build both the add-in (as well as the underlying COM component) and the associated macro. The Deployment Tool Build dialog box appears, indicating
the status of the add-in and COM component compilation (build).
The Build Dialog
1. In the Function Wizard Control Panel dialog box, in the Create Component area, select either MATLAB Excel Add-in Component Only or Create Excel Macro Only.
2. Enter mymagic in the Macro Name field.
3. Select the location of where to store the macro, using the Store Macro In drop-down box.
4. Enter a brief description of the macro's functionality in the Description field.
5. Click Create.
1. From the Function Wizard Control Panel, in the Execute Functions area, select Execute MATLAB Functions from Deployed Component.
2. Click Execute. In Excel, the Magic Square function executes, producing results similar to the following.
Macro Execution
Run the macro you created in Macro Creation by doing one of the following, after first clearing cells A1:E5 (which contain the output of the Magic Square function you ran in
Function Execution).
Tip: You may need to enable the proper security settings before running macros in Microsoft Excel. For information about macro permissions and related error messages, see the
Troubleshooting appendix.
Microsoft Excel Add-In and Macro Packaging using the Function Wizard
The Function Wizard can automatically package a deployable Microsoft Excel add-in and macro for sharing. To package your add-in in this manner, use one of the following
procedures.
1. After successfully building your component and add-in, in the Share Component area of the Function Wizard Control Panel dialog box, review the files listed in the Files
to include in packaging field. Add Files or Remove Files to and from the package by clicking the appropriate buttons.
2. To add access to the MATLAB Runtime installer to your package, select one of the options in the MATLAB Runtime area. For information about the MATLAB Runtime
and the MATLAB Runtime installer, see Install and Configure the MATLAB Runtime.
3. When you are ready to create your package, click Create Package.
From the Excel main window, open the Microsoft Visual Basic editor by doing one of the following. select Tools > Macro > Visual Basic Editor.
Tip: Hover your mouse over the Form Controls menu to see the various control labels.
3. In the Assign Macros dialog box, select the macro you want to assign the GUI button to, and click OK.
See more examples about building add-ins and COM components Create Macros from MATLAB Functions
Learn more about the MATLAB Runtime About the MATLAB Runtime
Learn how to customize and integrate the COM component you built by modifying the Integrate Components using Visual Basic ApplicationBuild and Integrate Spectral Analysis
Microsoft Visual Basic code Functions
Advantages of Using Tables
Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size, but each variable must have the same
number of rows.
load patients
Then, combine the workspace variables, Systolic and Diastolic into a single BloodPressure variable and convert the workspace variable, Gender, from a cell array of
character vectors to a categorical array.
whos('Gender','Age','Smoker','BloodPressure')
Now, create a table from the variables and display the first five rows.
T = table(Gender,Age,Smoker,BloodPressure);
T(1:5,:)
The table displays in a tabular format with the variable names at the top.
Each variable in a table is a single data type. If you add a new row to the table, MATLAB® forces consistency of the data type between the new data and the corresponding
table variables. For example, if you try to add information for a new patient where the first column contains the patient's age instead of gender, as in the expression
T(end+1,:) = {37,{'Female'},true,[130 84]}, then you receive the error:
The error occurs because MATLAB® cannot assign numeric data, 37, to the categorical array, Gender.
For comparison of tables with structures, consider the structure array, StructArray, that is equivalent to the table, T.
StructArray = table2struct(T)
Structure arrays organize records using named fields. Each field's value can have a different data type or size. Now, display the named fields for the first element of
StructArray.
StructArray(1)
Fields in a structure array are analogous to variables in a table. However, unlike with tables, you cannot enforce homogeneity within a field. For example, you can have some
values of S.Gender that are categorical array elements, Male or Female, others that are character vectors, 'Male' or 'Female', and others that are integers, 0 or 1.
Now consider the same data stored in a scalar structure, with four fields each containing one variable from the table.
ScalarStruct = struct(...
'Gender',{Gender},...
'Age',Age,...
'Smoker',Smoker,...
'BloodPressure',BloodPressure)
Unlike with tables, you cannot enforce that the data is rectangular. For example, the field ScalarStruct.Age can be a different length than the other fields.
A table allows you to maintain the rectangular structure (like a structure array) and enforce homogeneity of variables (like fields in a scalar structure). Although cell arrays do
not have named fields, they have many of the same disadvantages as structure arrays and scalar structures. If you have rectangular data that is homogeneous in each
variable, consider using a table. Then you can use numeric or named indexing, and you can use table properties to store metadata.
Consider the sample table from above. Each row in the table, T, represents a different patient. The workspace variable, LastName, contains unique identifiers for the 100
rows. Add row names to the table by setting the RowNames property to LastName and display the first five rows of the updated table.
T.Properties.RowNames = LastName;
T(1:5,:)
In addition to labeling the data, you can use row and variable names to access data in the table. For example, use named indexing to display the age and blood pressure of
the patients Williams and Brown.
T({'Williams','Brown'},{'Age','BloodPressure'})
Williams 38 125 83
Brown 49 122 80
Now, use numeric indexing to return an equivalent subtable. Return the third and fifth row from the second and fourth variables.
T(3:2:5,2:2:4)
Williams 38 125 83
Brown 49 122 80
With cell arrays or structures, you do not have the same flexibility to use named or numeric indexing.
• With a cell array, you must use strcmp to find desired named data, and then you can index into the array.
• With a scalar structure or structure array, it is not possible to refer to a field by number. Furthermore, with a scalar structure, you cannot easily select a subset of variables
or a subset of observations. With a structure array, you can select a subset of observations, but you cannot select a subset of variables.
• With a table, you can access data by named index or by numeric index. Furthermore, you can easily select a subset of variables and a subset of rows.
For example, add a table description, variable descriptions, and variable units for Age.
T.Properties.VariableDescriptions = ...
{'Male or Female' ...
'' ...
'true or false' ...
'Systolic/Diastolic'};
T.Properties.VariableUnits{'Age'} = 'Yrs';
Individual empty character vectors within the cell array for VariableDescriptions indicate that the corresponding variable does not have a description. For more
information, see Table Properties.
summary(T)
Variables:
Female 53
Male 47
Units: Yrs
Values:
Min 25
Median 39
Max 50
True 34
False 66
Description: Systolic/Diastolic
Values:
BloodPressure_1 BloodPressure_2
_______________ _______________
Min 109 68
Median 122 81.5
Max 138 99
Structures and cell arrays do not have properties for storing metadata.
See Also
summary | table
Related Topics
• Create and Work with Tables
• Modify Units, Descriptions and Table Variable Names
• Access Data in a Table