Вы находитесь на странице: 1из 226

table

Create table from workspace variables

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.

T = table creates an empty 0-by-0 table.

Examples collapse all

 Create Table from Workspace Variables

Define workspace variables with the same number of rows.


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

Create a table, T, as a container for the workspace variables.

T = table(Age,Height,Weight,BloodPressure,...
'RowNames',LastName)

T = 5×4 table
Age Height Weight BloodPressure
___ ______ ______ _____________

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

table names the variables with the workspace variable names.

 Create Table and Specify Variable Names

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.

 Create Table with String Array as Variable

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
_________ ________ ___________ ______ _________________________________________________

1261 "Jones" 20-Dec-2016 Good "Flight left on time, not crowded"


547 "Brown" 21-Dec-2016 Poor "Late departure, ran out of dinner options"
3489 "Smith" 22-Dec-2016 Fair "Late, but only by half an hour. Otherwise fine."

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
_________ ___________ ______ _________________________________________________

Jones 1261 20-Dec-2016 Good "Flight left on time, not crowded"


Brown 547 21-Dec-2016 Poor "Late departure, ran out of dinner options"
Smith 3489 22-Dec-2016 Fair "Late, but only by half an hour. Otherwise fine."

 Build Table by Assigning Variables Individually

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 Arguments collapse all

var1,...,varN — Input variables


 arrays

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.

Name-Value Pair 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 single
quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'RowNames',{'row1','row2','row3'} names the rows row1, row2, and row3.


collapse all

'RowNames' — Row names


 {} (default) | cell array of character vectors

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.

'VariableNames' — Variable names


 cell array of character vectors

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.

Output Arguments collapse all

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)

C = textscan( ___ ,Name,Value)

[C,position] = textscan( ___ )

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(chr,formatSpec,N) uses the formatSpec N times, where N is a positive integer.

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.

Examples collapse all

 Read Floating-Point Numbers

Read a character vector containing floating-point numbers.


Open Live Script

chr = '0.41 8.24 3.57 6.24 9.27';


C = textscan(chr,'%f');

The specifier '%f' in formatSpec tells textscan to match each field in chr to a double-precision floating-point number.

Display the contents of cell array C.

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.

Display the contents of cell array C.

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

Name Size Bytes Class Attributes

C 1x9 2249 cell


View the MATLAB® data type of each of the cells in C.

C = 1×9 cell array


{3×1 cell} {3×1 cell} [3×1 single] [3×1 int8] [3×1 uint32] [3×1 double] [3×1 double] {3×1 cell} [3×1 double]

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 Literal Text

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}

ans = 3×1 int32 column vector

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

 Skip the Remainder of a Line

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}

ans = 3×1 cell array


'09/12/2005'
'10/12/2005'
'11/12/2005'

textscan returns a 1-by-1 cell array dates.

 Specify Delimiter and Empty Value Conversion

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

Read the file, converting empty cells to -Inf.

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

column5 = 2×1 uint8 column vector

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.

 Specify Text to be Treated as Empty or Comments

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);

Display the output.


celldisp(C)

C{1}{1} =

abc

C{1}{2} =

def

C{2} =

2
NaN

C{3} =

NaN
5

C{4} =

3
6

C{5} =

4
7

 Treat Repeated Delimiters as One

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

 Specify Repeated Conversion Specifiers and Collect Numeric Data

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','|');

Read the numeric data in the file.

C_data0 = textscan(fileID,'%d %f %f %f')

C_data0 = 1×4 cell array


[4×1 int32] [4×1 double] [4×1 double] [4×1 double]

The default value for CollectOutput is 0 (false), so textscan returns each column of the numeric data in a separate array.

Set the file position indicator to the beginning of the file.

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)

C_data1 = 1×2 cell array


[4×1 int32] [4×3 double]

The test scores, which are all double, are collected into a single 4-by-3 array.

Close the file.

fclose(fileID);

 Read or Skip Quoted Text and Numeric Fields

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);

Display the output. |textscan| returns a |1-by-2| cell array, |C|.

Double quotation marks enclosing the text are removed.

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

 Read Foreign-Language Dates

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.

C = textscan(fileID,'%{dd MMMM yyyy}D %f %f',...


'DateLocale','de_DE','Delimiter',',');
fclose(fileID);

View the contents of the first cell in C. The dates display in the language MATLAB uses depending on your system locale.

C{1}

ans = 3×1 datetime array


01 January 2014
01 February 2014
01 March 2014

 Read Nondefault Control Characters

Use sprintf to convert nondefault escape sequences in your data.


Open Live Script
Create text that includes a form feed character, \f. Then, to read the text using textscan, call sprintf to explicitly
convert the form feed.

lyric = sprintf('Blackbird\fsinging\fin\fthe\fdead\fof\fnight');
C = textscan(lyric,'%s','delimiter',sprintf('\f'));
C{1}

ans = 7×1 cell array


'Blackbird'
'singing'
'in'
'the'
'dead'
'of'
'night'

textscan returns a 1-by-1 cell array, C.

 Resume Scanning

Resume scanning from a position other than the beginning.


Open Live Script
If you resume a scan of the text, textscan reads from the beginning each time. To resume a scan from any other position,
use the two-output argument syntax in your initial call to textscan.

For example, create a character vector called lyric. Read the first word of the character vector, and then resume the scan.

lyric = 'Blackbird singing in the dead of night';


[firstword,pos] = textscan(lyric,'%9c',1);
lastpart = textscan(lyric(pos+1:end),'%s');

Input Arguments collapse all

fileID — File identifier


 numeric scalar

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.

Data Types: double

formatSpec — Format of the data fields


 character vector | string

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

This table lists available conversion specifiers for numeric inputs.

Numeric Input Type Conversion Specifier Output Class

Integer, signed %d int32

%d8 int8

%d16 int16

%d32 int32

%d64 int64

Integer, unsigned %u uint32

%u8 uint8

%u16 uint16

%u32 uint32

%u64 uint64

Floating-point number %f double

%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.

Nonnumeric Input Type Conversion Specifier Details

Character %c Read any single character, including a delimiter.

Text Array %s Read as a cell array of character vectors.

%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.

Example: '%{dd-MMM-yyyy}D' specifies the format of a date such as '01-Jan-2014' .

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: %[]...].

Example: %[mus] reads 'summer ' as 'summ'.

%[^...] Exclude characters inside the brackets, reading until the first matching character. To exclude ],
specify it first: %[^]...].

Example: %[^xrg] reads 'summer ' as 'summe'.

Optional Operators

Conversion specifiers in formatSpec can include optional operators, which appear in the following order (includes spaces for clarity):

Optional operators include:

• Fields and Characters to Ignore


textscan reads all characters in your file in sequence, unless you tell it to ignore a particular field or a portion of a field.
Insert an asterisk character (*) after the percent character (%) to skip a field or a portion of a character field.

Operator Action Taken

%*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'.

'%*nc' Skip n characters, including delimiter characters.

• 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: char | string

N — Number of times to apply formatSpec


 Inf (default) | positive integer

Number of times to apply formatSpec, specified as a positive integer.

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

chr — Input text


 character vector | string

Input text to read.

Data Types: char | string

Name-Value Pair 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 single
quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

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.

Names are not case sensitive. collapse all

'CollectOutput' — Logical indicator determining data concatenation


 false (default) | true

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.

'CommentStyle' — Symbols designating text to ignore


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

Example: 'CommentStyle',{'/*', '*/'}

Example: 'CommentStyle',["/*", "*/"}

Data Types: char | string

'DateLocale' — Locale for reading dates


 character vector | string

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'

'Delimiter' — Field delimiter characters


 character vector | cell array of character vectors | string | string array

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 (\)

Data Types: char | string

'EmptyValue' — Returned value for empty numeric fields


 NaN (default) | scalar

Returned value for empty numeric fields in delimited text files, specified as the comma-separated pair consisting of 'EmptyValue' and a scalar.

'EndOfLine' — End-of-line characters


 character vector | string

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",":"

Data Types: char | string

'ExpChars' — Exponent characters


 'eEdD' (default) | character vector | string

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.

Data Types: char | string

'HeaderLines' — Number of header lines


 0 (default) | positive integer

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.

'MultipleDelimsAsOne' — Multiple delimiter handling


 0 (false) (default) | 1 (true)

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

'ReturnOnError' — Behavior when textscan fails to read or convert


 1 (true) (default) | 0 (false)

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.

'TreatAsEmpty' — Placeholder text to treat as empty value


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

Data Types: char | string

'Whitespace' — White-space characters


 ' \b\t' (default) | character vector | string
White-space characters, specified as the comma-separated pair consisting of 'Whitespace' and a character vector or string containing one or more characters.
textscan adds a space character, char(32), to any specified Whitespace, unless Whitespace is empty ('') and formatSpec includes any conversion specifier.

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 (\)

Data Types: char | string

'TextType' — Output data type of text


 'char' (default) | 'string'

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.

Output Arguments collapse all

C — File or text data


 cell array

File or text data, returned as a cell array.

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 — Position in the file or character vector


 integer

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.

Sign Digits Decimal Point Digits Exponent Character Sign Digits

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:

±<real>±<imag>i|j Example: 5.7-3.1i

±<imag>i|j Example: -7j

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

Introduced before R2006a


writetable
Write table to file

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.

Examples collapse all

 Write Table to Text File

Create a table.
Open Live Script

T = table(['M';'F';'M'],[45 45;41 32;40 34],...


{'NY';'CA';'MA'},[true;false;false])

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)

writetable outputs a text file named T.txt.

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.

 Write Table to Space-Delimited Text File

Create a table.
Open Live Script

T = table(['M';'F';'M'],[45 45;41 32;40 34],...


{'NY';'CA';'MA'},[true;false;false])

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.

 Write Table to Text File Including Row Names

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
___ ______ ______ _____________

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

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.

 Write Foreign-Language Dates to Text File

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
________________ ____ _____

01 January 2014 20.2 100.5


01 February 2014 21.6 102.7
01 March 2014 20.7 99.8

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

 Write Foreign-Language Characters to Text Files


When your data contains foreign-language or non-ASCII characters use the encoding parameter to ensure the file is
written correctly. First, load the provided table into the workspace. Then, write the table to a file using the default encoding.
Open Script
Finally, write the table using 'UTF-8' encoding and examine the result.

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 =

9×3 table array

A B C
_____ ______ _______

' ' 458.98 ' '


' ' 530.14 ' '
' ' 289.4 ' '
' ' 434.81 ' '
' ' 186.44 ' '
' ' 0 ' '
' ' 231.29 ' '
' ' 311.86 ' '
' ' 239.93 ' '

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 =

9×3 table array

A B C
_____ ______ _______

'南西' 458.98 '冬の嵐'


'南東' 530.14 '冬の嵐'
'南東' 289.4 '冬の嵐'
'西' 434.81 '機器の故障'
'中西部' 186.44 '深刻な嵐'
'西' 0 '攻撃'
'西' 231.29 '機器の故障'
'西' 311.86 '機器の故障'
'北東' 239.93 '火災'

 Write Quoted Text to CSV File

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
____ ____ _______________ _____

M 45 'New York, NY' true


F 41 'San Diego, CA' false
M 36 'Boston, MA' false

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

 Write Table to Specific Sheet and Range in Spreadsheet

Create a table.
Open Live Script

T = table(['M';'F';'M'],[45 45;41 32;40 34],...


{'NY';'CA';'MA'},[true;false;false])

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.

Input Arguments collapse all

T — Input data
 table

Input data, specified as a table.

filename — File name


 character vector | string

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.

• If filename does not exist, then writetable creates the file.


• If filename is the name of an existing text file, then writetable overwrites the file.
• If filename is the name of an existing spreadsheet file, then writetable writes a table to the specified location, but does not overwrite any values outside that
range.

Example: 'myData.xls' or "myData.xls"

Example: 'C:\test\myData.txt'

Data Types: char | string

Name-Value Pair 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 single
quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

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

Text and Spreadsheet Files collapse all

'FileType' — Type of file


 'text' | 'spreadsheet'

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:

• .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(T,'mySpreadsheet','FileType','spreadsheet')

Data Types: char | string

'WriteVariableNames' — Indicator for writing variable names as column headings


 true (default) | false | 1 | 0

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.

false writetable does not include variable names in the output.

'WriteRowNames' — Indicator for writing row names in first column


 false (default) | true | 0 | 1

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.

'DateLocale' — Locale for writing dates


 character vector | string

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.

Example: 'DateLocale','ja_JP' or 'DateLocale',"ja_JP"

Text Files Only collapse all

'Delimiter' — Field delimiter character


 character vector | string

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

Specifier Field Delimiter

',' Comma. This is the default behavior.

'comma'

' ' Space

'space'

'\t' Tab

'tab'

';' Semicolon

'semi'

'|' Vertical bar

'bar'

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

Example: 'Delimiter','space' or 'Delimiter',"space"

'QuoteStrings' — Indicator for writing quoted text


 false (default) | true | 0 | 1
Indicator for writing quoted text, specified as the comma-separated pair consisting of 'QuoteStrings' and either false, true, 0, or 1. If 'QuoteStrings' is true,
then writetable encloses the text in double quotation marks, and replaces any double-quote characters that appear as part of that text with two double-quote
characters. For an example, see Write Quoted Text to CSV File.

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

'Encoding' — Character encoding scheme


 'UTF-8' | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | ...

Character encoding scheme associated with the file, specified as the comma-separated pair consisting of 'Encoding' and 'system' or a standard character encoding
scheme name 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.

'Big5' 'ISO-8859-1' 'windows-847'

'Big5-HKSCS' 'ISO-8859-2' 'windows-949'

'CP949' 'ISO-8859-3' 'windows-1250'

'EUC-KR' 'ISO-8859-4' 'windows-1251'

'EUC-JP' 'ISO-8859-5' 'windows-1252'

'EUC-TW' 'ISO-8859-6' 'windows-1253'

'GB18030' 'ISO-8859-7' 'windows-1254'

'GB2312' 'ISO-8859-8' 'windows-1255'

'GBK' 'ISO-8859-9' 'windows-1256'

'IBM866' 'ISO-8859-11' 'windows-1257'

'KOI8-R' 'ISO-8859-13' 'windows-1258'

'KOI8-U' 'ISO-8859-15' 'US-ASCII'

'Macintosh' 'UTF-8'

'Shift_JIS'

Example: 'system' or "system" uses the system default encoding.

Data Types: char | string

Spreadsheet Files Only collapse all

'Sheet' — Worksheet to write to


 character vector | string | positive integer

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

Example: 'Sheet', 'MySheetName'

Example: 'Sheet', "MySheetName"

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

'Range' — Rectangular portion of worksheet to write to


 character vector | string

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.

Form of the Value of Range Description

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

Example: 'Range', 'A1:F10'

Example: 'Range', "A1:F10"


Data Types: char | string

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

Ways to Index into a Table


A table is a container for storing column-oriented variables that have the same number of rows. Parentheses allow you to select a subset of the data in a table and preserve
the table container. Curly braces and dot indexing allow you to extract data from 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.

Summary of Table Indexing Methods


Consider a table, T.

Type of Indexing Result Syntax Rows Variables

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}

How to Specify Rows to Access


When indexing into a table with parentheses, curly braces, or dot indexing, you can specify rows as a colon, numeric indices, or logical expressions. Furthermore, you can
index by name using a single row name or a cell array of row names.

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.

How to Specify Variables to Access


When indexing into a table with parentheses or curly braces, you can specify vars as a colon, numeric indices, logical expressions, a single variable name, a cell array of
variable names, or as the output of the vartype function..

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).

Create Table from Subset of Larger Table


This example shows how to create a table from a subset of a larger table.
Open Live Script
Load Sample Data

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);

The table, patients, contains 100 rows and 5 variables.

View the data type, description, units, and other descriptive statistics for each variable by using summary to summarize the table.

summary(patients)

Variables:

Age: 100×1 double

Values:

Min 25
Median 39
Max 50

Gender: 100×1 cell array of character vectors

Height: 100×1 double

Values:

Min 60
Median 67
Max 72

Weight: 100×1 double

Values:

Min 111
Median 142.5
Max 202

Smoker: 100×1 logical

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
___ ________ ______ ______ ______

Smith 38 'Male' 71 176 true


Johnson 43 'Male' 69 163 false
Williams 38 'Female' 64 131 false
Jones 40 'Female' 67 133 false
Brown 49 'Female' 64 119 false

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.

Index Using 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
___ ________ ______ ______ ______

Adams 48 'Female' 66 137 false


Brown 49 'Female' 64 119 false

T2 is a 2-by-5 table.

Index Using a Logical Expression

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
________ ______ ______

Moore 'Male' 68 183


Jackson 'Male' 71 174
Garcia 'Female' 69 131
Walker 'Female' 65 123
Hall 'Male' 70 189
Young 'Female' 63 114
Hill 'Female' 64 138
Rivera 'Female' 63 130
Cooper 'Female' 65 127
Cox 'Female' 66 111
Howard 'Female' 68 134
James 'Male' 66 186
Jenkins 'Male' 69 189
Perry 'Female' 64 120
Alexander 'Male' 69 171

T3 is a 15-by-3 table.

Create Array from the Contents of Table


This example shows how to extract the contents of a table using curly braces or dot indexing.
Open Live Script
Load Sample Data

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);

The table, patients, contains 100 rows and 5 variables.

Extract Multiple Rows and Multiple Variables

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

A is a 5-by-2 numeric array.

Extract Data from One Variable

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.

rows = patients.Smoker==false & patients.Age<30;

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.

Read Sample Data into Table


Read data from a comma-separated text file, testScores.csv, into a table using the readtable function. testScores.csv contains test scores for several students. Use
the student names in the first column of the text file as row names in the table.

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

T is a table with 10 rows and four variables.

Summarize the Table


View the data type, description, units, and other descriptive statistics for each variable by using the summary function to summarize the table.

summary(T)

Variables:

Gender: 10×1 cell array of character vectors

Test1: 10×1 double

Values:

Min 75
Median 86.5
Max 96

Test2: 10×1 double

Values:

Min 75
Median 85
Max 94

Test3: 10×1 double

Values:

Min 72
Median 86
Max 98
The summary contains the minimum, median, and maximum score for each test.

Find the Average Across Each Row


Extract the data from the second, third, and fourth variables using curly braces, {}, find the average of each row, and store it in a new variable, TestAvg.

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.

Compute Statistics Using Grouping Variable


Compute the mean and maximum of TestAvg by gender of the students.

varfun(@mean,T,'InputVariables','TestAvg',...
'GroupingVariables','Gender')

ans = 2×3 table


Gender GroupCount mean_TestAvg
________ __________ ____________

'female' 5 87.067
'male' 5 83.4

Replace Data Values


The maximum score for each test is 100. Use curly braces to extract the data from the table and convert the test scores to a 25 point scale.

T{:,2:end} = T{:,2:end}*25/100

T = 10×5 table
Gender Test1 Test2 Test3 TestAvg
________ _____ _____ _____ _______

HOWARD 'male' 22.5 21.75 23.25 22.5


WARD 'male' 21.75 21.25 20.75 21.25
TORRES 'male' 21.5 21.25 22 21.583
PETERSON 'female' 18.75 20 18 18.917
GRAY 'female' 22.25 21.5 21.75 21.833
RAMIREZ 'female' 24 23 24.5 23.833
JAMES 'male' 19.5 18.75 19.25 19.167
WATSON 'female' 22.75 23.5 23 23.083
BROOKS 'female' 21.5 20.75 21.25 21.167
KELLY 'male' 19.75 19 20.5 19.75

Change Variable Name


Change the variable name from TestAvg to Final.

T.Properties.VariableNames{end} = 'Final'

T = 10×5 table
Gender Test1 Test2 Test3 Final
________ _____ _____ _____ ______

HOWARD 'male' 22.5 21.75 23.25 22.5


WARD 'male' 21.75 21.25 20.75 21.25
TORRES 'male' 21.5 21.25 22 21.583
PETERSON 'female' 18.75 20 18 18.917
GRAY 'female' 22.25 21.5 21.75 21.833
RAMIREZ 'female' 24 23 24.5 23.833
JAMES 'male' 19.5 18.75 19.25 19.167
WATSON 'female' 22.75 23.5 23 23.083
BROOKS 'female' 21.5 20.75 21.25 21.167
KELLY 'male' 19.75 19 20.5 19.75

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 Sample Data


Load the sample patients data and create a table.

load patients
BloodPressure = [Systolic Diastolic];

T = table(Gender,Age,Height,Weight,Smoker,BloodPressure);

Display the first five rows of the table, T.

T(1:5,:)

ans = 5×6 table


Gender Age Height Weight Smoker BloodPressure
________ ___ ______ ______ ______ _____________

'Male' 38 71 176 true 124 93


'Male' 43 69 163 false 109 77
'Female' 38 64 131 false 125 83
'Female' 40 67 133 false 117 75
'Female' 49 64 119 false 122 80

T has 100 rows and 6 variables.

Add Variable Units


Specify units for each variable in the table by modifying the table property, VariableUnits. Specify the variable units as a cell array of character vectors.

T.Properties.VariableUnits = {'' 'Yrs' 'In' 'Lbs' '' ''};

An individual empty character vector within the cell array indicates that the corresponding variable does not have units.

Add a Variable Description for a Single Variable


Add a variable description for the variable, BloodPressure. Assign a single character vector to the element of the cell array containing the description for BloodPressure.

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.

Summarize the Table


View the data type, description, units, and other descriptive statistics for each variable by using summary to summarize the table.

summary(T)

Variables:

Gender: 100×1 cell array of character vectors

Age: 100×1 double

Units: Yrs
Values:

Min 25
Median 39
Max 50

Height: 100×1 double

Units: In
Values:

Min 60
Median 67
Max 72

Weight: 100×1 double

Units: Lbs
Values:

Min 111
Median 142.5
Max 202

Smoker: 100×1 logical


Values:

True 34
False 66

BloodPressure: 100×2 double

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.

Change a Variable Name


Change the variable name for the first variable from Gender to Sex.

T.Properties.VariableNames{'Gender'} = 'Sex';

Display the first five rows of the table, T.

T(1:5,:)

ans = 5×6 table


Sex Age Height Weight Smoker BloodPressure
________ ___ ______ ______ ______ _____________

'Male' 38 71 176 true 124 93


'Male' 43 69 163 false 109 77
'Female' 38 64 131 false 125 83
'Female' 40 67 133 false 117 75
'Female' 49 64 119 false 122 80

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.

Create and View Table


Create a table from workspace variables and view it. Alternatively, use the Import Tool or the readtable function to create a table from a spreadsheet or a text file. When you import
data from a file using these functions, each column becomes a table variable.

Load sample data for 100 patients from the patients MAT-file to workspace variables.

load patients
whos

Name Size Bytes Class Attributes

Age 100x1 800 double


Diastolic 100x1 800 double
Gender 100x1 12212 cell
Height 100x1 800 double
LastName 100x1 12416 cell
Location 100x1 15008 cell
SelfAssessedHealthStatus 100x1 12340 cell
Smoker 100x1 100 logical
Systolic 100x1 800 double
Weight 100x1 800 double
Populate a table with column-oriented variables that contain patient data. You can access and assign table variables by name. When you assign a table variable from a workspace
variable, you can assign the table variable a different name.

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,:)

ans = 5×4 table


Gender Smoker Height Weight
________ ______ ______ ______

'Male' true 71 176


'Male' false 69 163
'Female' false 64 131
'Female' false 67 133
'Female' false 64 119

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.

Create a table by reading all columns from the file, patients.dat.

T2 = readtable('patients.dat');
T2(1:5,:)

ans = 5×10 table


LastName Gender Age Location Height Weight Smoker Systolic Diastolic SelfAssessedHealthStatus
__________ ________ ___ ___________________________ ______ ______ ______ ________ _________ ________________________

'Smith' 'Male' 38 'County General Hospital' 71 176 1 124 93 'Excellent'


'Johnson' 'Male' 43 'VA Hospital' 69 163 0 109 77 'Fair'
'Williams' 'Female' 38 'St. Mary's Medical Center' 64 131 0 125 83 'Good'
'Jones' 'Female' 40 'VA Hospital' 67 133 0 117 75 'Fair'
'Brown' 'Female' 49 'County General Hospital' 64 119 0 122 80 'Good'

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,:)

ans = 5×5 table


Gender Smoker Height Weight ID
________ ______ ______ ______ ____

'Male' true 71 176 8148


'Male' false 69 163 9058
'Female' false 64 131 1270
'Female' false 67 133 9134
'Female' false 64 119 6324

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:

Gender: 100×1 cell array of character vectors

Smoker: 100×1 logical

Values:

True 34
False 66

Height: 100×1 double

Values:

Min 60
Median 67
Max 72

Weight: 100×1 double

Values:

Min 111
Median 142.5
Max 202

ID: 100×1 double

Values:

Min 120
Median 5485.5
Max 9706
Return the size of the table.

size(T)

ans =

100 5

T contains 100 rows and 5 variables.

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,:)

Tnew = 5×5 table


Gender Smoker Height Weight ID
________ ______ ______ ______ ____

'Male' true 71 176 8148


'Male' false 69 163 9058
'Female' false 64 131 1270
'Female' false 67 133 9134
'Female' false 64 119 6324

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)

Tnew = 5×4 table


Smoker Height Weight ID
______ ______ ______ ____

true 71 176 8148


false 69 163 9058
false 64 131 1270
false 67 133 9134
false 64 119 6324

Access Data by Row and Variable Names


Add row names to T and index into the table using row and variable names instead of numeric indices. Add row names by assigning the LastName workspace variable to the RowNames
property of T.

T.Properties.RowNames = LastName;

Display the first five rows of T with row names.


T(1:5,:)

ans = 5×5 table


Gender Smoker Height Weight ID
________ ______ ______ ______ ____

Smith 'Male' true 71 176 8148


Johnson 'Male' false 69 163 9058
Williams 'Female' false 64 131 1270
Jones 'Female' false 67 133 9134
Brown 'Female' false 64 119 6324

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'},:)

Tnew = 2×5 table


Gender Smoker Height Weight ID
______ ______ ______ ______ ____

Smith 'Male' true 71 176 8148


Johnson 'Male' false 69 163 9058

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'})

Tnew = 1×2 table


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 and Add Result as Table Variable


You can access the contents of table variables, and then perform calculations on them using MATLAB® functions. Calculate body-mass-index (BMI) based on data in the existing table
variables and add it as a new variable. Plot the relationship of BMI to a patient's status as a smoker or a nonsmoker. Add blood-pressure readings to the table, and plot the relationship
of blood pressure to BMI.

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,:)

ans = 5×6 table


Gender Smoker Height Weight ID BMI
________ ______ ______ ______ ____ ______

Smith 'Male' true 71 176 8148 24.547


Johnson 'Male' false 69 163 9058 24.071
Williams 'Female' false 64 131 1270 22.486
Jones 'Female' false 67 133 9134 20.831
Brown 'Female' false 64 119 6324 20.426

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.

tf = (T.BMI <= 25);


h1 = histogram(T.Diastolic(tf),'BinMethod','integers');
hold on
tf = (T.BMI > 25);
h2 = histogram(T.Diastolic(tf),'BinMethod','integers');
xlabel('Diastolic Reading (mm Hg)');
ylabel('Number of Patients');
legend('BMI <= 25','BMI > 25');
title('Diastolic Readings for Low and High BMI');
hold off

Reorder Table Variables and Rows for Output


To prepare the table for output, reorder the table rows by name, and table variables by position or name. Display the final arrangement of the table.

Sort the table by row names so that patients are listed in alphabetical order.

T = sortrows(T,'RowNames');

T(1:5,:)

ans = 5×8 table


Gender Smoker Height Weight ID BMI Systolic Diastolic
________ ______ ______ ______ ____ ______ ________ _________

Adams 'Female' false 66 137 8235 22.112 127 83


Alexander 'Male' true 69 171 1300 25.252 128 99
Allen 'Female' false 63 143 7432 25.331 113 80
Anderson 'Female' false 68 128 1577 19.462 114 77
Bailey 'Female' false 68 130 2239 19.766 113 81

Create a BloodPressure variable to hold blood pressure readings in a 100-by-2 table variable.

T.BloodPressure = [T.Systolic T.Diastolic];


Delete Systolic and Diastolic from the table since they are redundant.

T.Systolic = [];
T.Diastolic = [];

T(1:5,:)

ans = 5×7 table


Gender Smoker Height Weight ID BMI BloodPressure
________ ______ ______ ______ ____ ______ _____________

Adams 'Female' false 66 137 8235 22.112 127 83


Alexander 'Male' true 69 171 1300 25.252 128 99
Allen 'Female' false 63 143 7432 25.331 113 80
Anderson 'Female' false 68 128 1577 19.462 114 77
Bailey 'Female' false 68 130 2239 19.766 113 81

To put ID as the first column, reorder the table variables by position.

T = T(:,[5 1:4 6 7]);

T(1:5,:)

ans = 5×7 table


ID Gender Smoker Height Weight BMI BloodPressure
____ ________ ______ ______ ______ ______ _____________

Adams 8235 'Female' false 66 137 22.112 127 83


Alexander 1300 'Male' true 69 171 25.252 128 99
Allen 7432 'Female' false 63 143 25.331 113 80
Anderson 1577 'Female' false 68 128 19.462 114 77
Bailey 2239 'Female' false 68 130 19.766 113 81

You also can reorder table variables by name. To reorder the table variables so that Gender is last:

1. Find 'Gender' in the VariableNames property of the table.


2. Move 'Gender' to the end of a cell array of variable names.
3. Use the cell array of names to reorder the table variables.

varnames = T.Properties.VariableNames;
others = ~strcmp('Gender',varnames);
varnames = [varnames(others) 'Gender'];
T = T(:,varnames);

Display the first five rows of the reordered table.

T(1:5,:)

ans = 5×7 table


ID Smoker Height Weight BMI BloodPressure Gender
____ ______ ______ ______ ______ _____________ ________

Adams 8235 false 66 137 22.112 127 83 'Female'


Alexander 1300 true 69 171 25.252 128 99 'Male'
Allen 7432 false 63 143 25.331 113 80 'Female'
Anderson 1577 false 68 128 19.462 114 77 'Female'
Bailey 2239 false 68 130 19.766 113 81 'Female'

Write Table to File


You can write the entire table to a file, or create a subtable to write a selected portion of the original table to a separate file.

Write T to a file with the writetable function.

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 = [];

Write nonsmokers to a file.

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.

Key Tasks for the MATLAB Programmer

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

4. Install the Function Wizard. Installation of the Function Wizard

5. Start the Function Wizard. Function Wizard Start-Up

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.

What Can the Function Wizard Do for Me?


The Function Wizard enables you to pass Microsoft Excel (Excel 2000 or later) worksheet values to a compiled MATLAB model and then return model output to a cell or
range of cells in the worksheet.

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.

Example File Copying


All MATLAB Compiler examples reside in matlabroot\toolbox\matlabxl\examples\. The following table identifies examples by folder:

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.

% Copyright 2001-2012 The MathWorks, Inc.


y = magic(x)

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

Installation of the Function Wizard


Before you can use the Function Wizard, you must first install it as an add-in that is accessible from Microsoft Excel.

After you install the Function Wizard, the entry MATLAB Functions appears as an available Microsoft Excel add-in button.

Using Office 2010 or Office 2013


1. Click the File tab.
2. On the left navigation pane, select Options.
3. In the Excel Options dialog box, on the left navigation pane, select Add-Ins.
4. In the Manage drop-down, select Excel Add-Ins, and click Go.
5. In the Add-Ins dialog box, click Browse.
6. Browse to matlabroot/toolbox/matlabxl/matlabxl/arch, and select FunctionWizard2007.xlam. Click OK.
7. In the Excel Add-Ins dialog, verify that the entry MATLAB Compiler Function Wizard is selected. Click OK.

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.

Using Office 2007


1. Start Microsoft Excel if it is not already running.

2. Click the Office Button ( ) and select Excel Options.

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.

Using Office 2003


1. Select Tools > Add-Ins from the Excel main menu.
2. If the Function Wizard was previously installed, MATLAB Compiler Function Wizard appears in the list. Select the item, and click OK.
If the Function Wizard was not previously installed, click Browse and navigate to matlabroot\toolbox\matlabxl\matlabxl folder. Select FunctionWizard.xla.
Click OK to proceed.

Function Wizard Start-Up


Start the Function Wizard in one of the following ways. When the wizard has initialized, the Function Wizard Start Page dialog box displays.

Using Office 2007 or Office 2010 or 2013


In Microsoft Excel, on the Microsoft Office ribbon, on the Home tab, select Function Wizard.

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.

The Function Wizard Start Page Dialog Box


Workflow Selection for Prototyping and Debugging MATLAB Functions
After you have installed and started the Function Wizard, do the following.

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.

About Project Files


Keep in mind the following information about project files when working with the Function Wizard:

• 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.

Quitting the MATLAB Session Invoked by the Function Wizard


Avoid manually terminating the MATLAB session invoked by the Function Wizard. Doing so can prevent you from using the Wizard's MATLAB-related features from your
Excel session. If you want to quit the remotely invoked MATLAB session, restart Excel.

New MATLAB Function Definition


1. Add the function you want to deploy to the Function Wizard. Click Add in the Set Up Functions area of the Function Wizard Control Panel. The New MATLAB Function
dialog box appears.

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.

4. Define input argument properties as follows.


a. On the Input tab, click Set Input Data. The Input Data for n dialog box appears.
b. Specify a Range or Value by selecting the appropriate option and entering the value.

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.

5. Define output argument properties as follows.


a. On the Output tab, click Set Output Data. The Output Data for y dialog box appears, where x is the name of the output variable you are defining properties of.

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.

c. Select Auto Resize if it is not already selected.


d. Click Done in the Argument Properties For y dialog box.
e. Click Done in the Function Properties dialog box. mymagic now appears in the Active Functions list of the Function Wizard Control Panel.
Empty Cell Value Control
You can specify how MATLAB Compiler processes empty cells, allowing you to assign undefined or unrepresented (NaN, for example) data values to them.

To specify how to handle empty cells, do the following.

1. Click Options in the Input Data for N dialog box.


The Input Conversion Options dialog box opens.

2. Click the Treat Missing Data As drop-down box.


3. Specify either Zero or NaN (Not a Number), depending on how you want to handle empty cells.

Working with Struct Arrays


To assign ranges to fields in a struct array, do the following:

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.

3. In the Field for Argument dialog box, do the following:


a. In the Name field, define the field name. The Name you specify must match the field name of the structure array in your MATLAB function.
b. Specify the Range for the 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.
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:

• Which arguments are structure arrays


• Field names of the structure arrays

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.

MATLAB Function Prototyping and Debugging


Use the Function Wizard to interactively prototype and debug a MATLAB function.

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.

Prototyping and Debugging with myprimes


For example, say you are in the process of prototyping code that uses the equation P = myprimes(n). This equation returns a row vector of prime numbers less than or
equal to n (a prime number has no factors other than 1 and the number itself).

Your code uses P = myprimes(n) as follows:

function [p] = myprimes(n)

if length(n)~=1, error('N must be a scalar'); end


if n < 2, p = zeros(1,0); return, end
p = 1:2:n;
q = length(p);
p(1) = 2;
for k = 3:2:sqrt(n)

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).

Function Execution from MATLAB


Test your deployable MATLAB function by executing it in 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.

Creating an Add-In and Associated Excel Macro


To create both a deployable add-in and an associated Excel macro:

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

Creating a COM Component or a Macro Only Without Creating an Add-In


To create either a COM component or a macro without also creating the Excel add-in, do the following

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.

Function Execution from the Deployed Component


Execute your function as you did similarly in Function Execution from MATLAB, but this time execute it from the deployed component to ensure it matches your previous
output.

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.

Using Office 2007 or Office 2010 or 2013


1. In Microsoft Excel, click View > Macros > View Macros.
2. Select mymagic from the Macro name drop-down box.
3. Click Run. Cells A1:E5 on the Excel sheet are automatically populated with the output of mymagic.

Using Office 2003


1. In Microsoft Excel, click Tools > Macro > Macros.
2. Select mymagic from the Macro name drop-down box.
3. Click Run. Cells A1:E5 on the Excel sheet are automatically populated with the output of mymagic.

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.

Microsoft Visual Basic Code Access (Optional Advanced Task)


Optionally, you may want to access the Visual Basic code or modify it, depending on your programming expertise or the availability of an Excel developer. If so, follow these
steps.

From the Excel main window, open the Microsoft Visual Basic editor by doing one of the following. select Tools > Macro > Visual Basic Editor.

Using Office 2007 or Office 2010 or 2013


1. Click Developer > Visual Basic.
2. When the Visual Basic Editor opens, in the Project - VBAProject window, double-click to expand VBAProject (mymagic.xls).
3. Expand the Modules folder and double-click the Matlab Macros module.
This opens the Visual Basic Code window with the code for this project.

Using Office 2003


1. Click Tools > Macro > Visual Basic Editor.
2. When the Visual Basic Editor opens, in the Project - VBAProject window, double-click to expand VBAProject (mymagic.xls).
3. Expand the Modules folder and double-click the Matlab Macros module.
This opens the VB Code window with the code for this project.

Mapping a Macro to a GUI Button or Control (Optional)


To attach the macro to a GUI button, do the following:

1. Click Developer > Insert.


2. From the Form Controls menu, select the Button (Form Control) icon.

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.

Attaching a Macro to a Button


For More Information

If you want to... See...

• Perform basic MATLAB Programmer tasks Write Deployable MATLAB Code


• Understand how the deployment products process your MATLAB functions
• Understand how the deployment products work together
• Explore guidelines about writing deployable MATLAB code

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

Open Live Script

Conveniently Store Mixed-Type Data in Single Container


You can use the table data type to collect mixed-type data and metadata properties, such as variable name, row names, descriptions, and variable units, in a single
container. Tables are suitable for column-oriented or tabular data that is often stored as columns in a text file or in a spreadsheet. For example, you can use a table to store
experimental data, with rows representing different observations and columns representing different measured variables.

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.

For example, load sample patients data.

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.

BloodPressure = [Systolic Diastolic];


Gender = categorical(Gender);

whos('Gender','Age','Smoker','BloodPressure')

Name Size Bytes Class Attributes

Age 100x1 800 double


BloodPressure 100x2 1600 double
Gender 100x1 346 categorical
Smoker 100x1 100 logical
The variables Age, BloodPressure, Gender, and Smoker have varying data types and are candidates to store in a table since they all have the same number of rows, 100.

Now, create a table from the variables and display the first five rows.

T = table(Gender,Age,Smoker,BloodPressure);
T(1:5,:)

ans = 5×4 table


Gender Age Smoker BloodPressure
______ ___ ______ _____________

Male 38 true 124 93


Male 43 false 109 77
Female 38 false 125 83
Female 40 false 117 75
Female 49 false 122 80

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:

Invalid RHS for assignment to a categorical array.

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)

StructArray = 100×1 struct array with fields:


Gender
Age
Smoker
BloodPressure

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)

ans = struct with fields:


Gender: Male
Age: 38
Smoker: 1
BloodPressure: [124 93]

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)

ScalarStruct = struct with fields:


Gender: [100×1 categorical]
Age: [100×1 double]
Smoker: [100×1 logical]
BloodPressure: [100×2 double]

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.

Access Data Using Numeric or Named Indexing


You can index into a table using parentheses, curly braces, or dot indexing. Parentheses allow you to select a subset of the data in a table and preserve the table container.
Curly braces and dot indexing allow you to extract data from a table. Within each table indexing method, you can specify the rows or variables to access by name or by
numeric index.

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,:)

ans = 5×4 table


Gender Age Smoker BloodPressure
______ ___ ______ _____________

Smith Male 38 true 124 93


Johnson Male 43 false 109 77
Williams Female 38 false 125 83
Jones Female 40 false 117 75
Brown Female 49 false 122 80

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'})

ans = 2×2 table


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)

ans = 2×2 table


Age BloodPressure
___ _____________

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 more information on table indexing, see Access Data in a Table.

Use Table Properties to Store Metadata


In addition to storing data, tables have properties to store metadata, such as variable names, row names, descriptions, and variable units. You can access a property using
T.Properties.PropName, where T is the name of the table and PropName is one of the table properties.

For example, add a table description, variable descriptions, and variable units for Age.

T.Properties.Description = 'Simulated Patient Data';

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.

To print a table summary, use the summary function.

summary(T)

Description: Simulated Patient Data

Variables:

Gender: 100×1 categorical

Description: Male or Female


Values:

Female 53
Male 47

Age: 100×1 double

Units: Yrs
Values:

Min 25
Median 39
Max 50

Smoker: 100×1 logical

Description: true or false


Values:

True 34
False 66

BloodPressure: 100×2 double

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

Вам также может понравиться