Matlab table

table

Main Content

Description

arrays store column-oriented or tabular data, such as columns from a text file or spreadsheet. Tables store each piece of column-oriented data in a variable. Table variables can have different data types and sizes as long as all variables have the same number of rows. Table variables have names, just as the fields of a structure have names. Use the function to get information about a table.

To index into a table, use smooth parentheses to return a subtable or curly braces to extract the contents. You can access variables and rows using names. For more information on indexing using numbers and names, see Access Data in Tables.

Creation

You can read data from a file into a table using either the or the function. Alternatively, use the function described below to create a table from existing workspace variables.

You also can create a table that allows space for variables whose values are filled in later. To create a table with preallocated space for variables, use the function with as the first input argument, as described below.

Description

example

creates a table from the input variables . The variables can have different sizes and data types, but all variables must have the same number of rows.

If the inputs are workspace variables, then assigns their names as the variable names in the output table. Otherwise, assigns variable names of the form , where is the number of variables.

example

creates a table and preallocates space for the variables that have data types you specify. is a two-element numeric array, where specifies the number of rows and specifies the number of variables. specifies the data types of the variables.

example

specifies additional input arguments using one or more name-value pair arguments. For example, you can specify variable names using the name-value pair. You can use this syntax with any of the input arguments of the previous syntaxes.

example

creates an empty 0-by-0 table.

Input Arguments

expand all

— Input variables
arrays

Input variables, specified as arrays with the same number of rows. The input variables can have 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 , where is a numeric or logical vector that corresponds to rows of the variable . In addition, the array must implement both a method and a method with a argument.

Example: creates a table from variables with four rows, but different sizes.

Example: creates a table from variables with three rows, but different data types.

— Size of preallocated table
two-element numeric vector

Size of the preallocated table, specified as a two-element numeric vector. The first element of specifies the number of rows, and the second element specifies the number of table variables.

To create variables only, without any rows, specify as the first element of .

Example: preallocates 50 rows for a table that contains a string array, a double array, and a datetime array.

Example: specifies zero rows and four variables.

— Data types of preallocated variables
cell array of character vectors | string array

Data types of the preallocated variables, specified as a cell array of character vectors or a string array. The number of types specified by must equal the number of variables specified by the second element of .

can contain the names of any data types, including the names shown in the table.

Data Type Name

Initial Value in Each Element

Double- or single-precision

, , ,

Double- or single-precision

, , , 

Signed 8-, 16-, 32-, or 64-bit integer

, , , 

Unsigned 8-, 16-, 32-, or 64-bit integer

()

categorical value

value

seconds, as a value

days, as a value

(1-by-1 string with no characters)

(cell with 0-by-0 character array)

(cell with 0-by-0 double array)

Scalar structure with no fields

Table with no variables

Timetable with no variables and for row times

For any other data type, the initial value is the value used by that type or class to "in-fill" unassigned elements of an array.

If you specify as a data type, then preallocates the corresponding variable as a cell array of character vectors, not as a character array. Best practice is to avoid creating table or timetable variables that are character arrays. When working with text data in a table or a timetable, consider using a string array or a categorical array.

Name-Value Pair Arguments

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

Example: creates a table from input arrays and , and names the corresponding table variables and .

— Variable names
cell array of character vectors | string array

Variable names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct.

  • The number of names in the array must equal the number of table variables.

  • The function also stores the variable names in the property of the table.

  • Variable names can have any Unicode® characters, including spaces and non-ASCII characters.

— Row names
cell array of character vectors | string array

Row names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct.

  • The number of names in the array must equal the number of rows.

  • The function also stores the row names in the property of the table.

  • Row names can have any Unicode characters, including spaces and non-ASCII characters.

  • The function removes any leading or trailing whitespace characters from the row names.

Example: creates a table with both variable names and row names.

— Dimension names
two-element cell array of character vectors | two-element string array

Since R2021a

Dimension names, specified as a two-element cell array of character vectors or two-element string array whose elements are nonempty and distinct.

  • The function also stores the dimension names in the property of the table.

  • Dimension names can have any Unicode characters, including spaces and non-ASCII characters.

Before R2021a, you can specify dimension names only by setting the property.

Properties

expand all

Access Table Metadata Properties

A table contains metadata properties that describe the table and its variables. Access these properties using the syntax , where is the name of a property. For example, you can access the names of the variables in table using the syntax .

You can return a summary of all the metadata properties using the syntax .

Tables provide metadata access through the property because you can access table data directly using dot syntax. For example, if table has a variable named , then you can access the values in the variable by using the syntax .

Table Metadata

— Dimension names
(default) | two-element cell array of character vectors | two-element string array

Dimension names, specified as a two-element cell array of character vectors or a two-element string array.

  • Dimension names can have any Unicode characters, including spaces and non-ASCII characters.

  • If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.

You can access table data using the two dimension names.

  • If the table has row names, and you use dot syntax and the first dimension name, then you can access the row names as a vector.

  • If you use dot syntax and the second dimension name, then the data from all the variables are concatenated together in one array, as though you had indexed into the table using syntax.

Example

Create a table and display its dimension names. You can access row names and data using dimension names with dot syntax.

load patients T = table(Age,Height,Weight,Systolic,Diastolic, ...'RowNames',LastName); T.Properties.DimensionNames
ans = 1x2 cell {'Row'} {'Variables'}

Access the row names using the first dimension name. Display the first five names.

ans = 5x1 cell {'Smith' } {'Johnson' } {'Williams'} {'Jones' } {'Brown' }

Access the data using the second dimension name. This syntax is equivalent to .

ans = 100×5 38 71 176 124 93 43 69 163 109 77 38 64 131 125 83 40 67 133 117 75 49 64 119 122 80 46 68 142 121 70 33 64 142 130 88 40 68 180 115 82 28 68 183 115 78 31 66 132 118 86 ⋮

Modify the names of its dimensions using the property. Having changed the dimension names, you can access the row names and data using the syntaxes and respectively.

T.Properties.DimensionNames = {'Patient','Data'}; T.Properties
ans = TableProperties with properties: Description: '' UserData: [] DimensionNames: {'Patient' 'Data'} VariableNames: {'Age' 'Height' 'Weight' 'Systolic' 'Diastolic'} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {100x1 cell} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.

— Row names
(default) | cell array of character vectors | string array

Row names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct. If is not empty, then the number of row names must equal the number of rows in the table.

  • Row names can have any Unicode characters, including spaces and non-ASCII characters.

  • If you assign row names with leading or trailing whitespace characters, then MATLAB® removes them from the row names.

  • The row names are visible when you view the table. Furthermore, you can use the row names within parentheses or curly braces to access the table data.

  • Another way to access the row names is to use dot syntax and the name of the first dimension of the table.

  • If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.

Example

Create a table. Then add row names and access rows by their names.

load patients T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);

Add row names using the property. By default, tables do not have row names, but you can add them at any time.

T.Properties.RowNames = LastName; head(T,4)
ans=4×7 table Gender Age Height Weight Smoker Systolic Diastolic __________ ___ ______ ______ ______ ________ _________ Smith {'Male' } 38 71 176 true 124 93 Johnson {'Male' } 43 69 163 false 109 77 Williams {'Female'} 38 64 131 false 125 83 Jones {'Female'} 40 67 133 false 117 75

Another way to access the row names is by using dot syntax with the name of the first dimension of the table. Display the first five row names.

T.Properties.DimensionNames
ans = 1x2 cell {'Row'} {'Variables'}
ans = 5x1 cell {'Smith' } {'Johnson' } {'Williams'} {'Jones' } {'Brown' }

Index into the table by row names.

T({'Smith','Williams'},:)
ans=2×7 table Gender Age Height Weight Smoker Systolic Diastolic __________ ___ ______ ______ ______ ________ _________ Smith {'Male' } 38 71 176 true 124 93 Williams {'Female'} 38 64 131 false 125 83

— Table description
(default) | character vector | string scalar

Table description, specified as a character vector or string scalar. This description is visible when using the function.

If you specify this property using a string scalar, then it is converted and stored as a character vector.

Example

Create a table. Modify the description of the table. Display a summary of the result.

load patients T = table(Gender,Age,Height,Weight); T.Properties.Description = 'Simulated patient data'; summary(T)
Description: Simulated patient data Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Values: Min 25 Median 39 Max 50 Height: 100x1 double Values: Min 60 Median 67 Max 72 Weight: 100x1 double Values: Min 111 Median 142.5 Max 202

— Additional table information
(default) | array

Additional table information, specified as an array. You can attach data of any kind to a table using this property.

Example

Create a table. Attach an anonymous function as a piece of user data that is associated with the table.

load patients T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic); formula = @(x) x.^2; T.Properties.UserData = formula; T.Properties
ans = TableProperties with properties: Description: '' UserData: @(x)x.^2 DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.

Variable Metadata

— Variable names
cell array of character vectors | string array

Variable names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct. The number of names must equal the number of variables.

  • Variable names can have any Unicode characters, including spaces and non-ASCII characters.

  • The variable names are visible when viewing the table and when using the function. Furthermore, you can use the variable names within parentheses, within curly braces, or with dot indexing to access table data.

  • If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.

Example

Create a table with default variable names. Then modify the names using the property.

T = table({'M';'M';'F';'F';'F'},[38;43;38;40;49], ... [71;69;64;67;64],[176;163;131;133;119])
T=5×4 table Var1 Var2 Var3 Var4 _____ ____ ____ ____ {'M'} 38 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119
T.Properties.VariableNames = {'Gender','Age','Height','Weight'}
T=5×4 table Gender Age Height Weight ______ ___ ______ ______ {'M'} 38 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119

A fundamental way to display and modify variables is to access them by name using dot syntax.

T=5×4 table Gender Age Height Weight ______ ___ ______ ______ {'M'} 53 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119

— Variable descriptions
(default) | cell array of character vectors | string array

Variable descriptions, specified as a cell array of character vectors or a string array This property can be an empty cell array, which is the default. If the array is not empty, then it must contain as many elements as there are variables. You can specify an individual empty character vector or empty string for a variable that does not have a description.

  • The variable descriptions are visible when using the function.

  • If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.

Example

Create a table. Modify the variable descriptions. Display a summary of the result.

load patients T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic); T.Properties.VariableDescriptions = {'','','','', ...'Has the patient ever been a smoker', ...'Systolic Pressure','Diastolic Pressure'}; summary(T)
Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Values: Min 25 Median 39 Max 50 Height: 100x1 double Values: Min 60 Median 67 Max 72 Weight: 100x1 double Values: Min 111 Median 142.5 Max 202 Smoker: 100x1 logical Properties: Description: Has the patient ever been a smoker Values: True 34 False 66 Systolic: 100x1 double Properties: Description: Systolic Pressure Values: Min 109 Median 122 Max 138 Diastolic: 100x1 double Properties: Description: Diastolic Pressure Values: Min 68 Median 81.5 Max 99

— Variable units
(default) | cell array of character vectors | string array

Variable units, specified as a cell array of character vectors or a string array. This property can be an empty cell array, which is the default. If the array is not empty, then it must contain as many elements as there are variables. You can specify an individual empty character vector or empty string for a variable that does not have units.

  • The variable units are visible when using the function.

  • If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.

Example

Create a table. Modify the variable units. Display a summary of the result.

load patients T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic); T.Properties.VariableUnits = {'','Yrs','In','Lbs','','mm Hg','mm Hg'}; summary(T)
Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Properties: Units: Yrs Values: Min 25 Median 39 Max 50 Height: 100x1 double Properties: Units: In Values: Min 60 Median 67 Max 72 Weight: 100x1 double Properties: Units: Lbs Values: Min 111 Median 142.5 Max 202 Smoker: 100x1 logical Values: True 34 False 66 Systolic: 100x1 double Properties: Units: mm Hg Values: Min 109 Median 122 Max 138 Diastolic: 100x1 double Properties: Units: mm Hg Values: Min 68 Median 81.5 Max 99

— Status as continuous or discrete variables
(default) | cell array of character vectors | string array

Status as continuous or discrete variables, specified as a cell array of character vectors or a string array.

While tables and timetables both have this property, only timetables use it. For more information, see the property of .

Custom Metadata

— Customized metadata of table and its variables
object

Customized metadata of a table and its variables, specified as a object.

The object is a container for customized metadata that you can add to a table. By default, has zero properties. Each property you add to can contain either table metadata or variable metadata. If a property contains variable metadata, then its value must be an array, and the number of elements in the array must equal the number of table variables.

  • To add properties for customized metadata to a table, use the function.

  • To access or modify customized metadata, use the syntax . In this syntax, is the name you chose when you added that property using .

  • To remove properties, use the function.

Note: You can add or remove only properties for customized metadata using and . You cannot add or remove properties of the object.

Example

Create a table.

load patients T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);

Add properties that can hold customized metadata about the table and its variables. In this example, the metadata are names of instruments, and values indicating whether variables are to be plotted, and the name of an output file. To add properties, use the function.

T = addprop(T,{'Instrument','ToPlot','OutputFile'},{'variable','variable','table'}); T.Properties
ans = TableProperties with properties: Description: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.<name>): OutputFile: [] Instrument: [] ToPlot: []

Assign values to the customized metadata using dot syntax. When you assign an array of text values to customized metadata, the best practice is to use a string array, not a cell array of character vectors. If a property of is a cell array of character vectors, then there is no mechanism to prevent you from later assigning nontext values as elements of the cell array.

T.Properties.CustomProperties.Instrument = ["","","height rod","scale","","blood pressure cuff","blood pressure cuff"]; T.Properties.CustomProperties.ToPlot = [false false true true false true true]; T.Properties.CustomProperties.OutputFile = 'patientData.csv'; T.Properties
ans = TableProperties with properties: Description: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.<name>): OutputFile: 'patientData.csv' Instrument: ["" "" "height rod" "scale" ... ] ToPlot: [0 0 1 1 0 1 1]

Remove the property from .

T = rmprop(T,'OutputFile'); T.Properties
ans = TableProperties with properties: Description: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.<name>): Instrument: ["" "" "height rod" "scale" ... ] ToPlot: [0 0 1 1 0 1 1]

Examples

collapse all

Store Related Data Variables in Table

Store data about a group of patients in a table. You can perform calculations and store results in the same table. Also, you can annotate the table to describe your work and the variables of the table.

First, create workspace variables that have the patient data. The variables can have any data types but must have the same number of rows.

LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'}; Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); 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, , as a container for the workspace variables. The function uses the workspace variable names as the names of the table variables in . A table variable can have multiple columns. For example, the variable in T is a 5-by-2 array.

T = table(LastName,Age,Smoker,Height,Weight,BloodPressure)
T=5×6 table LastName Age Smoker Height Weight BloodPressure ___________ ___ ______ ______ ______ _____________ {'Sanchez'} 38 true 71 176 124 93 {'Johnson'} 43 false 69 163 109 77 {'Li' } 38 true 64 131 125 83 {'Diaz' } 40 false 67 133 117 75 {'Brown' } 49 true 64 119 122 80

You can use dot indexing to access table variables. For example, calculate the mean height of the patients using the values in .

meanHeight = mean(T.Height)

Calculate body mass index (BMI), and add it as a new table variable. You also can add and name table variables in one step, using dot syntax.

T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2
T=5×7 table LastName Age Smoker Height Weight BloodPressure BMI ___________ ___ ______ ______ ______ _____________ ______ {'Sanchez'} 38 true 71 176 124 93 24.547 {'Johnson'} 43 false 69 163 109 77 24.071 {'Li' } 38 true 64 131 125 83 22.486 {'Diaz' } 40 false 67 133 117 75 20.831 {'Brown' } 49 true 64 119 122 80 20.426

Annotate the table with a description of the BMI calculation. You can annotate and its variables using metadata accessed through .

T.Properties.Description = 'Patient data, including body mass index (BMI) calculated using Height and Weight'; T.Properties
ans = TableProperties with properties: Description: 'Patient data, including body mass index (BMI) calculated using Height and Weight' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.

Access All Table Data as Matrix

Access all the data from a table as a matrix, using the name of the second dimension of the table.

Create a table that has five rows of data about a set of patients.

Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); 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,Smoker,Height,Weight,BloodPressure)
T=5×5 table Age Smoker Height Weight BloodPressure ___ ______ ______ ______ _____________ 38 true 71 176 124 93 43 false 69 163 109 77 38 true 64 131 125 83 40 false 67 133 117 75 49 true 64 119 122 80

Display the names of the table dimensions using the property. The default name of the second dimension is .

T.Properties.DimensionNames
ans = 1x2 cell {'Row'} {'Variables'}

Access the table data as a matrix using the syntax . This syntax is equivalent to accessing all the contents using curly brace syntax, . If the table data cannot be concatenated into a matrix, then an error message is raised.

ans = 5×6 38 1 71 176 124 93 43 0 69 163 109 77 38 1 64 131 125 83 40 0 67 133 117 75 49 1 64 119 122 80

Rename the second dimension. If you change the name, then you can use the new name to access the data.

T.Properties.DimensionNames{2} = 'PatientData'; T.PatientData
ans = 5×6 38 1 71 176 124 93 43 0 69 163 109 77 38 1 64 131 125 83 40 0 67 133 117 75 49 1 64 119 122 80

Specify Size and Variable Types

Preallocate a table by specifying its size and the data types of the variables. The function fills the variables with default values that are appropriate for the data types you specify. It also gives the variables default names, but you also can assign variable names of your own. Preallocation provides room for data you add to the table later.

sz = [4 3]; varTypes = {'double','datetime','string'}; T = table('Size',sz,'VariableTypes',varTypes)
T=4×3 table Var1 Var2 Var3 ____ ____ _________ 0 NaT <missing> 0 NaT <missing> 0 NaT <missing> 0 NaT <missing>

To specify names for the variables, use the name-value pair argument.

varNames = {'Temperature','Time','Station'}; T2 = table('Size',sz,'VariableTypes',varTypes,'VariableNames',varNames)
T2=4×3 table Temperature Time Station ___________ ____ _________ 0 NaT <missing> 0 NaT <missing> 0 NaT <missing> 0 NaT <missing>

Add rows of data to the first two rows of . Preallocation can be a useful technique when your code adds one row of data, or a few rows of data, at a time. Instead of growing the table every time you add a row, you can fill in table variables that already have room for your data.

T2(1,:) = {75,datetime('now'),"S1"}; T2(2,:) = {68,datetime('now')+1,"S2"}
T2=4×3 table Temperature Time Station ___________ ____________________ _________ 75 01-Sep-2021 09:50:40 "S1" 68 02-Sep-2021 09:50:40 "S2" 0 NaT <missing> 0 NaT <missing>

You can encapsulate a row of data values in a cell array. When you assign a row from a cell array, elements from the cell array are assigned to the row in the table.

Specify Variable Names

Create a table from arrays. To specify table variable names, use the name-value pair argument. For example, you can use to specify names when the other input arguments are not workspace variables.

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

Create a table with the state names as row names. You can specify both the and name-value pairs when using the function.

T = table(categorical({'M';'F';'M'}),[45;32;34],logical([1;0;0]),...'VariableNames',{'Gender','Age','Vote'},...'RowNames',{'NY';'CA';'MA'})
T=3×3 table Gender Age Vote ______ ___ _____ NY M 45 true CA F 32 false MA M 34 false

Specify Row Names

Specify row names for a table. Tables do not have to have row names, but if you specify them, then you can index into a table by row name. You also can access the set of row names using the name of the first dimension of a table.

Create arrays containing patient data.

LastName = {'Sanchez';'Johnson';'Lee';'Diaz';'Brown'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119];

Create a table containing the arrays. Specify as the source of row names for the table. The table has only three variables. The row names are not a table variable, but instead a property of the table.

T = table(Age,Weight,Height,'RowNames',LastName)
T=5×3 table Age Weight Height ___ ______ ______ Sanchez 38 176 71 Johnson 43 163 69 Lee 38 131 64 Diaz 40 133 67 Brown 49 119 64

Since the rows have row names, you can index into the rows of by name.

ans=1×3 table Age Weight Height ___ ______ ______ Lee 38 131 64

To specify multiple rows, use a cell array.

ans=2×3 table Age Weight Height ___ ______ ______ Lee 38 131 64 Brown 49 119 64

To access all the row names of as a cell array, use the syntax . By default, is the name of the first dimension of a table.

ans = 5x1 cell {'Sanchez'} {'Johnson'} {'Lee' } {'Diaz' } {'Brown' }

Change the name of the first dimension. If you change the name, then you can access the row names using the new name.

T.Properties.DimensionNames{1} = 'LastNames'; T.LastNames
ans = 5x1 cell {'Sanchez'} {'Johnson'} {'Lee' } {'Diaz' } {'Brown' }

Specify Table Variables and Row Names Using String Arrays

Starting in R2017a, you can create strings using double quotes, and add string arrays as table variables.

FlightNum = [1261;547;3489]; Customer = ["Jones";"Brown";"Smith"]; Date = datetime(2016,12,20:22)'; Rating = categorical(["Good";"Poor";"Fair"]); Comment = ["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.

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 function with the syntax . 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, creates with the default variable names , , , and . You can assign more meaningful names to after you create . 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 , 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

Specify Variable Names Using Any Characters

Starting in R2019b, you can specify table variable names that are not valid MATLAB® identifiers. Such variable names can include spaces, non-ASCII characters, and can have any character as the leading character. When you access such a variable name, enclose it quotation marks.

Create a table that stores data about a set of patients. Start with their ages and status as smokers.

Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); 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,Smoker)
T=5×2 table Age Smoker ___ ______ 38 true 43 false 38 true 40 false 49 true

Add the blood pressure readings with the variable name . You can use dot syntax to add or access the variable. Since its name is not a valid MATLAB identifier, use parentheses and quotation marks with dot syntax.

T.('29-May-2019 Blood Pressure Reading') = BloodPressure
T=5×3 table Age Smoker 29-May-2019 Blood Pressure Reading ___ ______ __________________________________ 38 true 124 93 43 false 109 77 38 true 125 83 40 false 117 75 49 true 122 80

When table variable names are valid MATLAB identifiers, you can use dot syntax without parentheses and quotation marks.

T.Height = Height; T.Weight = Weight
T=5×5 table Age Smoker 29-May-2019 Blood Pressure Reading Height Weight ___ ______ __________________________________ ______ ______ 38 true 124 93 71 176 43 false 109 77 69 163 38 true 125 83 64 131 40 false 117 75 67 133 49 true 122 80 64 119

Index into using variable names.

T(:,{'Age','Smoker','29-May-2019 Blood Pressure Reading'})
ans=5×3 table Age Smoker 29-May-2019 Blood Pressure Reading ___ ______ __________________________________ 38 true 124 93 43 false 109 77 38 true 125 83 40 false 117 75 49 true 122 80

Limitations

  • Use single quotes for these input names:

    • (since R2021a)

    To avoid confusion with variable inputs, do not use double-quoted string scalars (such as ) for these names.

Tips

  • For a list of functions that accept or return tables, see Tables.

Compatibility Considerations

expand all

Variable names can contain leading and trailing whitespace characters

Behavior changed in R2019b

Table and timetable variable names with leading or trailing whitespace characters are not modified.

In previous releases, leading and trailing whitespace characters were deleted from variable names when you specified them using the name-value pair argument, or assigned them to the property.

To manually remove such characters, first use the function on the names, then assign them as variable names to the table or timetable.

Variable names and dimension names must be unique

Behavior changed in R2019b

MATLAB raises an error if you assign a table variable name that matches a dimension name, or a dimension name that matches a variable name. In previous releases, MATLAB raised a warning and modified the names so they were unique.

Dimension names cannot match reserved names

Behavior changed in R2021a

MATLAB raises an error if you assign a dimension name that matches one of these reserved names: , , , or . In previous releases, MATLAB raised a warning and modified the dimension names so that they were different from the reserved names.

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function supports tall arrays with the limitation:

  • The syntax constructs a tall table from several tall arrays . You can use the name-value pair argument to specify variable names.

For more information, see Tall Arrays for Out-of-Memory Data.

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

Usage notes and limitations:

  • The input arrays must be distributed and have the same number of rows.

  • The result is distributed, using a 1D distribution scheme over the first dimension.

For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

Introduced in R2013b

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web site

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

Sours: https://uk.mathworks.com/help/matlab/ref/table.html

Create Tables and Assign Data to Them

Create Tables from Input Arrays

You can create a table from arrays by using the function. For example, create a small table with data for five patients.

First, create six column-oriented arrays of data. These arrays have five rows because there are five patients. (Most of these arrays are 5-by-1 column vectors, while is a 5-by-2 matrix.)

LastName = ["Sanchez";"Johnson";"Zhang";"Diaz";"Brown"]; Age = [38;43;38;40;49]; Smoker = [true;false;true;false;true]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];

Now create a table, , as a container for the data. In this call to the function, the input arguments use the workspace variable names for the names of the variables in .

patients = table(LastName,Age,Smoker,Height,Weight,BloodPressure)
patients=5×6 table LastName Age Smoker Height Weight BloodPressure _________ ___ ______ ______ ______ _____________ "Sanchez" 38 true 71 176 124 93 "Johnson" 43 false 69 163 109 77 "Zhang" 38 true 64 131 125 83 "Diaz" 40 false 67 133 117 75 "Brown" 49 true 64 119 122 80

The table is a 5-by-6 table because it has six variables. As the variable shows, a table variable itself can have multiple columns. This example shows why tables have rows and variables, not rows and columns.

Add Variable to Table Using Dot Notation

Once you have created a table, you can add a new variable at any time by using dot notation. Dot notation refers to table variables by name, , where is the table and is the variable name. This notation is similar to the notation you use to access and assign data to the fields of a structure.

For example, add a variable to . Calculate body mass index, or BMI, using the values in and . Assign the BMI values to a new table variable.

patients.BMI = (patients.Weight*0.453592)./(patients.Height*0.0254).^2
patients=5×7 table LastName Age Smoker Height Weight BloodPressure BMI _________ ___ ______ ______ ______ _____________ ______ "Sanchez" 38 true 71 176 124 93 24.547 "Johnson" 43 false 69 163 109 77 24.071 "Zhang" 38 true 64 131 125 83 22.486 "Diaz" 40 false 67 133 117 75 20.831 "Brown" 49 true 64 119 122 80 20.426

Assign Variables to Empty Table

Another way to create a table is to start with an empty table and assign variables to it. For example, re-create the table of patient data, but this time assign variables using dot notation.

First, create an empty table, , by calling without arguments.

patients2 = 0x0 empty table

Next, create a copy of the patient data by assigning variables. Table variable names do not have to match array names, as shown by the and table variables.

patients2.Name = LastName; patients2.Age = Age; patients2.Smoker = Smoker; patients2.Height = Height; patients2.Weight = Weight; patients2.BP = BloodPressure
patients2=5×6 table Name Age Smoker Height Weight BP _________ ___ ______ ______ ______ __________ "Sanchez" 38 true 71 176 124 93 "Johnson" 43 false 69 163 109 77 "Zhang" 38 true 64 131 125 83 "Diaz" 40 false 67 133 117 75 "Brown" 49 true 64 119 122 80

Preallocate Table and Fill Rows

Sometimes you know the sizes and data types of the data that you want to store in a table, but you plan to assign the data later. Perhaps you plan to add only a few rows at a time. In that case, preallocating space in the table and then assigning values to empty rows can be more efficient.

For example, to preallocate space for a table to contain time and temperature readings at different stations, use the function. Instead of supplying input arrays, specify the sizes and data types of the table variables. To give them names, specify the argument. Preallocation fills table variables with default values that are appropriate for their data types.

sz = [4 3]; varTypes = ["double","datetime","string"]; varNames = ["Temperature","Time","Station"]; temps = table('Size',sz,'VariableTypes',varTypes,'VariableNames',varNames)
temps=4×3 table Temperature Time Station ___________ ____ _________ 0 NaT <missing> 0 NaT <missing> 0 NaT <missing> 0 NaT <missing>

One way to assign or add a row to a table is to assign a cell array to a row. If the cell array is a row vector and its elements match the data types of their respective variables, then the assignment converts the cell array to a table row. However, you can assign only one row at a time using cell arrays. Assign values to the first two rows.

temps(1,:) = {75,datetime('now'),"S1"}; temps(2,:) = {68,datetime('now')+1,"S2"}
temps=4×3 table Temperature Time Station ___________ ____________________ _________ 75 01-Sep-2021 10:20:08 "S1" 68 02-Sep-2021 10:20:08 "S2" 0 NaT <missing> 0 NaT <missing>

As an alternative, you can assign rows from a smaller table into a larger table. With this method, you can assign one or more rows at a time.

temps(3:4,:) = table([63;72],[datetime('now')+2;datetime('now')+3],["S3";"S4"])
temps=4×3 table Temperature Time Station ___________ ____________________ _______ 75 01-Sep-2021 10:20:08 "S1" 68 02-Sep-2021 10:20:08 "S2" 63 03-Sep-2021 10:20:08 "S3" 72 04-Sep-2021 10:20:08 "S4"

You can use either syntax to increase the size of a table by assigning rows beyond the end of the table. If necessary, missing rows are filled in with default values.

temps(6,:) = {62,datetime('now')+6,"S6"}
temps=6×3 table Temperature Time Station ___________ ____________________ _________ 75 01-Sep-2021 10:20:08 "S1" 68 02-Sep-2021 10:20:08 "S2" 63 03-Sep-2021 10:20:08 "S3" 72 04-Sep-2021 10:20:08 "S4" 0 NaT <missing> 62 07-Sep-2021 10:20:09 "S6"

Convert Variables to Tables

You can convert variables that have other data types to tables. Cell arrays and structures are other types of containers that can store arrays that have different data types. So you can convert cell arrays and structures to tables. You can also convert an array to a table where the table variables contain columns of values from the array. To convert these kinds of variables, use the , , or functions.

For example, convert an array to a table by using . Arrays do not have column names, so the table has default variable names.

A = 3×3 3 3 1 3 2 2 1 1 3
a2t=3×3 table A1 A2 A3 __ __ __ 3 3 1 3 2 2 1 1 3

You can provide your own table variable names by using the name-value argument.

a2t = array2table(A,"VariableNames",["First","Second","Third"])
a2t=3×3 table First Second Third _____ ______ _____ 3 3 1 3 2 2 1 1 3

Read Table from File

It is common to have a large quantity of tabular data in a file such as a CSV (comma-separated value) file or an Excel® spreadsheet. To read such data into a table, use the function.

For example, the CSV file is a sample file that is distributed with MATLAB. The file contains data for a set of electrical power outages. The first line of has column names. The rest of the file has comma-separated data values for each outage. The first few lines are shown here.

Region,OutageTime,Loss,Customers,RestorationTime,Cause SouthWest,2002-02-01 12:18,458.9772218,1820159.482,2002-02-07 16:50,winter storm SouthEast,2003-01-23 00:49,530.1399497,212035.3001,,winter storm SouthEast,2003-02-07 21:15,289.4035493,142938.6282,2003-02-17 08:14,winter storm West,2004-04-06 05:44,434.8053524,340371.0338,2004-04-06 06:10,equipment fault MidWest,2002-03-16 06:18,186.4367788,212754.055,2002-03-18 23:23,severe storm ...

To read and store the data in a table, you can use . It reads numeric values, dates and times, and strings into table variables that have appropriate data types. Here, and are numeric arrays. The and variables are arrays because recognizes the date and time formats of the text in those columns of the input file. To read the rest of the text data into string arrays, specify the name-value argument.

outages = readtable("outages.csv","TextType","string")
outages=1468×6 table Region OutageTime Loss Customers RestorationTime Cause ___________ ________________ ______ __________ ________________ _________________ "SouthWest" 2002-02-01 12:18 458.98 1.8202e+06 2002-02-07 16:50 "winter storm" "SouthEast" 2003-01-23 00:49 530.14 2.1204e+05 NaT "winter storm" "SouthEast" 2003-02-07 21:15 289.4 1.4294e+05 2003-02-17 08:14 "winter storm" "West" 2004-04-06 05:44 434.81 3.4037e+05 2004-04-06 06:10 "equipment fault" "MidWest" 2002-03-16 06:18 186.44 2.1275e+05 2002-03-18 23:23 "severe storm" "West" 2003-06-18 02:49 0 0 2003-06-18 10:54 "attack" "West" 2004-06-20 14:39 231.29 NaN 2004-06-20 19:16 "equipment fault" "West" 2002-06-06 19:28 311.86 NaN 2002-06-07 00:51 "equipment fault" "NorthEast" 2003-07-16 16:23 239.93 49434 2003-07-17 01:12 "fire" "MidWest" 2004-09-27 11:09 286.72 66104 2004-09-27 16:37 "equipment fault" "SouthEast" 2004-09-05 17:48 73.387 36073 2004-09-05 20:46 "equipment fault" "West" 2004-05-21 21:45 159.99 NaN 2004-05-22 04:23 "equipment fault" "SouthEast" 2002-09-01 18:22 95.917 36759 2002-09-01 19:12 "severe storm" "SouthEast" 2003-09-27 07:32 NaN 3.5517e+05 2003-10-04 07:02 "severe storm" "West" 2003-11-12 06:12 254.09 9.2429e+05 2003-11-17 02:04 "winter storm" "NorthEast" 2004-09-18 05:54 0 0 NaT "equipment fault" ⋮

Import Table Using Import Tool

Finally, you can interactively preview and import data from spreadsheets or delimited text files by using the Import Tool. There are two ways to open the Import Tool.

  • MATLAB Toolstrip: On the Home tab, in the Variable section, click Import Data.

  • MATLAB command prompt: Enter , where is the name of a text or spreadsheet file.

For example, open the sample file by using and to get the path to the file.

The Import Tool shows you a preview of the six columns from . To import the data as a table, follow these steps.

  1. In the Imported Data section, select Table as the output type.

  2. Click Import Selection (near the upper-right corner). The new table, named , appears in your workspace.

See Also

| | | | | Import Tool

Related Topics

Sours: https://it.mathworks.com/help/matlab/matlab_prog/create-a-table.html
  1. Amazon peppa pig dvd
  2. Segway ninebot charging
  3. Russian navy shirts
  4. Stepside flatbed

varfun

Main Content

Description

example

applies the function separately to each variable of the table or timetable and returns the results in the table or timetable .

The function must take one input argument and return arrays with the same number of rows each time it is called. The th variable in the output argument, , is equal to .

If is a timetable and aggregates data over groups of rows, then assigns the first row time from each group of rows in as the corresponding row time in . To return as a table without row times, specify as .

example

applies the function separately to each variable of the table or timetable with additional options specified by one or more pair arguments.

For example, you can specify which variables to pass to the function.

Examples

collapse all

Apply Element-wise Function

Define and apply an element-wise function to the variables of a table to square all the elements.

Define a table containing numeric variables.

A = table([0.71;-2.05;-0.35;-0.82;1.57],[0.23;0.12;-0.18;0.23;0.41])
A=5×2 table Var1 Var2 _____ _____ 0.71 0.23 -2.05 0.12 -0.35 -0.18 -0.82 0.23 1.57 0.41

Define the anonymous function to find the square of an input.

Apply the function to all the variables of table .

B=5×2 table Fun_Var1 Fun_Var2 ________ ________ 0.5041 0.0529 4.2025 0.0144 0.1225 0.0324 0.6724 0.0529 2.4649 0.1681

The variables of have names based on the function and the variable names from .

Apply Function that Returns Scalar From Vector

Compute the mean of each variable in a 5-by-2 table.

Define a table containing numeric variables.

A = table([0.71;-2.05;-0.35;-0.82;1.57],[0.23;0.12;-0.18;0.23;0.41])
A=5×2 table Var1 Var2 _____ _____ 0.71 0.23 -2.05 0.12 -0.35 -0.18 -0.82 0.23 1.57 0.41

Define the anonymous function to find the mean of an input.

uses an existing MATLAB® function to define the operation.

Apply the function to all the variables of table .

B=1×2 table mean_Var1 mean_Var2 _________ _________ -0.188 0.162

is a table containing the average value from each variable. To return a numeric vector instead of a table, you can use .

Apply Function to Groups Within Variables

Compute the group-wise means of variables in a table, , and return them as rows in a table, .

Create a table where one variable defines groups.

A = table({'test2';'test1';'test2';'test3';'test1'},... [0.71;-2.05;-0.35;-0.82;1.57],[0.23;0.12;-0.18;0.23;0.41])
A=5×3 table Var1 Var2 Var3 _________ _____ _____ {'test2'} 0.71 0.23 {'test1'} -2.05 0.12 {'test2'} -0.35 -0.18 {'test3'} -0.82 0.23 {'test1'} 1.57 0.41

Define the anonymous function to find the mean of an input.

uses an existing MATLAB® function to define the operation.

Apply the function to each group of data defined by .

B = varfun(func,A,'GroupingVariables','Var1')
B=3×4 table Var1 GroupCount mean_Var2 mean_Var3 _________ __________ _________ _________ {'test1'} 2 -0.24 0.265 {'test2'} 2 0.18 0.025 {'test3'} 1 -0.82 0.23

contains a variable called to indicate the number of entries from table in that group.

Apply Function to Groups Within Timetable Variables

Create a timetable containing sample data. The row times of the timetable also define groups.

dt = datetime(2016,1,1)+days([0 1 1 2 3 3])'; A = timetable(dt,[0.71;-2.05;-0.35;-0.82;1.57;0.09],... [0.23;0.12;-0.18;0.23;0.41;0.02],...'VariableNames',{'x''y'})
A=6×2 timetable dt x y ___________ _____ _____ 01-Jan-2016 0.71 0.23 02-Jan-2016 -2.05 0.12 02-Jan-2016 -0.35 -0.18 03-Jan-2016 -0.82 0.23 04-Jan-2016 1.57 0.41 04-Jan-2016 0.09 0.02

Compute the group-wise means of the variables in the timetable. returns as a timetable because is a timetable. When you specify the row times as the grouping variable, you cannot specify any variable as another grouping variable.

B = varfun(@mean,A,'GroupingVariables','dt')
B=4×3 timetable dt GroupCount mean_x mean_y ___________ __________ ______ ______ 01-Jan-2016 1 0.71 0.23 02-Jan-2016 2 -1.2 -0.03 03-Jan-2016 1 -0.82 0.23 04-Jan-2016 2 0.83 0.215

Input Arguments

collapse all

— Function
function handle

Function, specified as a function handle. You can define the function in a file or as an anonymous function. If corresponds to more than one function file (that is, if represents a set of overloaded functions), MATLAB® determines which function to call based on the class of the input arguments.

Use the name-value pair argument, if the function take one input argument and returns arrays with a different numbers of rows each time it is called. Otherwise, must return arrays with the same number of rows.

Example: computes the square of each element of an input.

— Input table
table | timetable

Input table, specified as a table or a timetable.

Name-Value Arguments

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

Example: uses only the second variable in as an input to .

— Specifiers for selecting variables of to pass to
positive integer | vector of positive integers | character vector | cell array of character vectors | string array | logical vector | function handle

Specifiers for selecting variables of to pass to , specified as the comma-separated pair consisting of and a positive integer, vector of positive integers, character vector, cell array of character vectors, string array, logical vector, or a function handle.

If you specify as a function handle, then it must return a logical scalar, and passes only the variables in where the function returns ().

— One or more variables in that define groups of rows
positive integer | vector of positive integers | character vector | cell array of character vectors | string array | logical vector

One or more variables in that define groups of rows, specified as the comma-separated pair consisting of and a positive integer, vector of positive integers, character vector, cell array of character vectors, string array, or logical vector.

The value of specifies which table variables are the grouping variables, not their data types. A grouping variable can be numeric, or have data type , , , , , or .

Rows in that have the same grouping variable values belong to the same group. applies to each group of rows within each of the variables of , rather than to each entire variable.

If any grouping variable contains s or missing values (such as s, undefined categorical values, or missing strings), then the corresponding rows do not belong to any group, and are excluded from the output.

Row labels can be grouping variables. You can group on row labels alone, on one or more variables in , or on row labels and variables together.

  • If is a table, then the labels are row names.

  • If is a timetable, then the labels are row times.

The output, , has one row for each group when you specify or . When you specify or , the sizes of the outputs from determine how many rows of correspond to each group.

— Format of
(default) | | |

Format of , specified as the comma-separated pair consisting of and either the value , , , or .

returns a table with one variable for each variable in (or each variable specified with ). For grouped computation, , also contains the grouping variables.

allows you to use a function that returns values of different sizes or data types for the different variables in . However, for ungrouped computation, must return arrays with the same number of rows each time it is called. For grouped computation, must return values with the same number of rows each time it is called for a given group.

If is a table, then this is the default output format.

returns a timetable with one variable for each variable in (or each variable specified with ). For grouped computation, also contains the grouping variables.

creates the row times of from the row times of . If the row times assigned to do not make sense in the context of the calculations performed using , then specify the output format as .

If is a timetable, then this is the default output format.

concatenates the values into a vector. must return a scalar with the same data type each time it is called.

returns as a cell array. allows you to use a function that returns values of different sizes or data types.

— Function to call if fails
function handle

Function to call if fails, specified as the comma-separated pair consisting of and a function handle. Define this function so that it rethrows the error or returns valid outputs for function .

MATLAB calls the specified error-handling function with two input arguments:

  • A structure with these fields:

    Error identifier.

    Error message text.

    Index of the variable for which the error occurred.

    Name of the variable for which the error occurred.

  • The set of input arguments to function at the time of the error.

For example,

function [A, B] = errorFunc(S, varargin) warning(S.identifier, S.message) A = NaN; B = NaN;

Output Arguments

collapse all

— Output table
table | timetable

Output table, returned as a table or a timetable. can store metadata such as descriptions, variable units, variable names, and row names. For more information, see the Properties sections of or .

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function supports tall arrays with the limitations:

  • The input must always return a tall array.

  • Supported name-value pairs are:

    • — Cannot be specified as a function handle.

    • — Value can be , , , or only.

  • When the input array is a tall timetable and is , the specified function must return an array with the same size in the first dimension as the input. Specify as when the input function is a reduction function such as .

For more information, see Tall Arrays.

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

  • The function handle input, , must be constant.

  • While function handles can be inputs to itself, they cannot be inputs to your entry point functions. Specify within the code meant for code generation. For more information, see Function Handle Limitations for Code Generation (MATLAB Coder).

  • The values for all name-value arguments must be constant.

  • The name-value argument is not supported for code generation.

  • Variable-size input arguments are not supported.

  • Grouping variables cannot have duplicate values in generated code.

  • You cannot specify the value of as if you specify the name-value argument and the function returns a different data type for each variable specified by .

  • If the input is a timetable and you specify , then the output is always an irregular timetable.

  • If you specify groups and the number of groups is not known at compile time, and that number is zero, then empty double variables in the output might have sizes of 1-by-0 in generated code. In MATLAB, such variables have sizes of 0-by-0.

Introduced in R2013b

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web site

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

Sours: https://www.mathworks.com/help/matlab/ref/varfun.html

Tables

Main Content

Arrays in tabular form whose named columns can have different types

is a data type suitable for column-oriented or tabular data that is often stored as columns in a text file or in a spreadsheet. Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size with the one restriction that each variable must have the same number of rows. For more information, see Create Tables and Assign Data to Them or watch Tables and Categorical Arrays.

Functions

expand all

Create Tables and Convert Type

Read and Write Files

Basic Import and Export

Define Import Rules

Parquet Files

Summary Information and Stacked Plot

Print summary of table, timetable, or categorical array
Number of table rows
Number of table variables
Determine if input is table
Determine if input is table or timetable
Get top rows of table, timetable, or tall array
Get bottom rows of table, timetable, or tall array
Stacked plot of several variables with common x-axis

Sort, Rearrange, and Customize

Sort

Rearrange Variables

Add variables to table or timetable
Rename variables in table or timetable
Move variables in table or timetable
Delete variables from table or timetable
Split multicolumn variables in table or timetable
Combine table or timetable variables into multicolumn variable
Subscript into table or timetable by variable type
Convert table or timetable variables to specified data type

Reshape

Reorient table or timetable so that rows become variables
Stack data from input table or timetable into one variable in output table or timetable
Unstack data from single variable into multiple variables
Invert nested table-in-table hierarchy in tables or timetables

Customize Properties

Add custom properties to table or timetable
Remove custom properties from table or timetable

Join and Set Operations

Join Using Key Variables

Combine two tables or timetables by rows using key variables
Inner join between two tables or timetables
Outer join between two tables or timetables

Set Operations

Set union of two arrays
Set intersection of two arrays
Array elements that are members of set array
Set difference of two arrays
Set exclusive OR of two arrays

Apply Functions to Table Contents

Live Editor Tasks

Join TablesCombine two tables using key variables in the Live Editor
Stack Table VariablesCombine values from multiple table variables into one table variable in the Live Editor
Unstack Table VariablesDistribute values from one table variable to multiple table variables in the Live Editor

Topics

Create Tables and Assign Data to Them

There are several ways to create tables and assign data to them. You can create tables from input arrays, preallocate tables and fill them in later, or import tables from text files or spreadsheets.

Access Data in Tables

Indexing into tables with parentheses, dot notation, and curly braces accesses table data in different ways. You can use indexing to create a table that is a subset of a larger table or to create an array from data in a table.

Plots That Support Tables

Create plots by passing tables directly to plotting functions.

Calculations on Tables

This example shows how to perform calculation on tables.

Advantages of Using Tables

Use tables to store mixed-type data conveniently, access data with numeric or named indexing, and to store metadata.

Changes to DimensionNames Property in R2016b

Tables can raise compatibility warnings, and change dimension names, when you modify the DimensionNames property.

Featured Examples

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web site

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

Sours: https://www.mathworks.com/help/matlab/tables.html

Table matlab

What are Tables and How are They Used in MATLAB

Welcome to using tables in MATLAB! In this video, we’ll define what a table is in MATLAB, how to import external table data into MATLAB from programs like Excel, and how to perform basic functions on the table using MATLAB.

Table arrays store column-oriented or tabular data, such as columns from a text file or spreadsheet.  Tables store each piece of column-oriented data in a variable which may contain different types of data.  For instance, tables may contain numerical data, alphanumerical or text strings, or categorical data.  In this video, we will focus on working with numerical and alphanumerical data.  

Tables are often found in formats such as spreadsheets or delimited-value files.  You’re probably familiar with tables in programs like Excel.  You can import, analyze, and extract table data in MATLAB without having to manually recreate a table from Excel.  Let’s look at an example.

Here, we have an Excel table with the average summer highs at MathWorks locations in North America.  You’ll see we have three different data types in the table: text strings, categorical, and numerical.  For this video, we will focus on working with alphanumeric and numerical data.

Let’s get this table imported into MATLAB.  

To import a table into MATLAB, click on “Import Data” in the top toolbar.

Navigate to where your table is located, select it, and click Open.

You’ll see that MATLAB is able to determine the table elements.  First, you’ll see the name of the table at the top based on the file name.  Second, you’ll see the table headers; these are called variable names in MATLAB.  You can adjust the row of variable names using the drop-down menu at the top.  Third, you’ll see the data types.  In this example, you’ll see locations represented as text data, time zones represented as categorical data, and temperatures represented as numerical data. 

If you want to change any data in the table, you can do so by double-clicking the corresponding cell .

If you want to change the data type of any variable, use the drop-down menu.

Once you are satisfied with the data you want to import, click Import Selection.  In MATLAB, you’ll see the table in the Workspace.

At any point, you can make changes to the table, by double-clicking on the table in the workspace to open the variable editor, selecting any of the cells, and making any necessary changes to its value.  You’ll notice that as you make any changes, it will display programmatically in the command window.

By right-clicking on aAny variable, you can sort the data as if you were in Excel, delete data, or export data into a separate table.  You can also add metadata to each variable.  

To obtain a high-level overview of table data, you can use the summary function to view a quick analysis of the table data by column.  For instance, we see there are three MathWorks locations in the Pacific Standard Time Zone, and the median average temperature in July of the MathWorks North America locations is 82 degrees.

You can do more than just analyze data using tables in MATLAB.  

You can use dot-indexing to perform functions on a single variable.  For example, if we want to find the mean (average) temperature of the North America locations in August, it can be easily done using the mean function.

Let’s assign meanaugtemp to equal the mean of August temperatures.  And you’ll see the average temperature in August of the North American locations is 81.5 degrees.

What if you want to focus on a specific variable of the table?  You can use curly braces ({}) to extract data from one variable into a single array.  For instance, let’s extract the July temperatures for further analysis.  We can extract the variable with the following syntax: SampleTable{1:5, ‘July’}

You can also concatenate the data further by extracting multiple variables.  If we wanted to extract July and August temperatures for further analysis, we would use the following syntax: SampleTable{1:5, ‘July’ ‘August’}.  This extracts the data into a single array.

If you want to extract specific variables of a table into a new table, you can do so with the following syntax using paranthesis: define the new table name = SampleTable(1:5, ‘July’ ‘August’) 

You can even add variables to a table using functions.  For instance, if we wanted to calculate the mean of each location’s summer temperature, we would have to add each average temperature – June, July, and August – and then divide by three.  In MATLAB, we would use the following syntax: SampleTable.meantemp = (SampleTable.June + SampleTable.July + SampleTable.August)/3.  We’ll see that it adds the new variable to the end of the table and performs the calculation.

There are many other functions you can perform on tables variables.  The MATLAB help documentation on tables and variables has lots of information, examples, and live scripts you can download to practice.  To access the help documentation, click on the question mark icon in the top right.

In this video, we covered how to define a table and the types of data tables contain, how to perform an analysis of the data, and how to perform basic functions.  Take advantage of MATLAB tools and functionalities to perform everything from high-level analysis to complex functions on external table data such as Excel spreadsheets or tabular data.  If you’re ready to take the next step using tables in MATLAB, we have more videos on importing Excel spreadsheets, performing complex table functions, and using categorical data in tables.  

Sours: https://www.mathworks.com/videos/introducing-tables-and-categorical-arrays-79924.html

.

You will also be interested:

.



1459 1460 1461 1462 1463