varfun
Apply function to table or timetable variables
Description
applies the functionB
= varfun(func
,A
)func
separately to each variable of the table or timetableA
and returns the results in the table or timetableB
.
The functionfunc
must take one input argument and return arrays with the same number of rows each time it is called. Thei
th variable in the output argument,B{:,i}
, is equal tofunc(A{:,i})
.
IfA
is a timetable andfunc
aggregates data over groups of rows, thenvarfun
assigns the first row time from each group of rows inA
as the corresponding row time inB
. To returnB
as a table without row times, specify'OutputFormat'
as'table'
.
applies the functionB
= varfun(func
,A
,Name,Value
)func
separately to each variable of the table or timetableA
with additional options specified by one or moreName,Value
pair arguments.
For example, you can specify which variables to pass to the function.
Examples
Apply Element-wise Function
Define and apply an element-wise function to the variables of a table to square all the elements.
定义一个表包含数值变量。
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 tableVar1 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.
func = @(x) x.^2;
Apply the function to all the variables of tableA
.
B = varfun(func,A)
B=5×2 tableFun_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 ofB
have names based on the function and the variable names fromA
.
Apply Function that Returns Scalar From Vector
Compute the mean of each variable in a 5-by-2 table.
定义一个表包含数值变量。
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 tableVar1 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.
func = @mean;
func
使用现有的MATLAB®函数定义operation.
Apply the function to all the variables of tableA
.
B = varfun(func,A)
B=1×2 tablemean_Var1 mean_Var2 _________ _________ -0.188 0.162
B
is a table containing the average value from each variable. To return a numeric vector instead of a table, you can useB = varfun(func,A,'OutputFormat','uniform')
.
Apply Function to Groups Within Variables
Compute the group-wise means of variables in a table,A
, and return them as rows in a table,B
.
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 tableVar1 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.
func = @mean;
func
使用现有的MATLAB®函数定义operation.
Apply the function to each group of data defined byVar1
.
B = varfun(func,A,'GroupingVariables','Var1')
B=3×4 tableVar1 GroupCount mean_Var2 mean_Var3 _________ __________ _________ _________ {'test1'} 2 -0.24 0.265 {'test2'} 2 0.18 0.025 {'test3'} 1 -0.82 0.23
B
contains a variable calledGroupCount
to indicate the number of entries from tableA
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 timetabledt 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.varfun
returnsB
as a timetable becauseA
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 timetabledt 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
func
—Function
function handle
Function, specified as a function handle. You can define the function in a file or as an anonymous function. Iffunc
corresponds to more than one function file (that is, iffunc
represents a set of overloaded functions), MATLAB®determines which function to call based on the class of the input arguments.
Use the'OutputFormat','cell'
name-value pair argument, if the functionfunc
take one input argument and returns arrays with a different numbers of rows each time it is called. Otherwise,func
must return arrays with the same number of rows.
Example:func = @(x) x.^2;
computes the square of each element of an input.
A
—Input table
table|timetable
Input table, specified as a table or a timetable.
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, whereName
is the argument name andValue
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and encloseName
in quotes.
Example:'InputVariables',2
uses only the second variable inA
as an input tofunc
.
InputVariables
—Specifiers for selecting variables ofA
to pass tofunc
positive integer|vector of positive integers|string array|character vector|cell array of character vectors|pattern
scalar|logical vector|function handle
Specifiers for selecting variables ofA
to pass tofunc
, specified as the comma-separated pair consisting of'InputVariables'
and a positive integer, vector of positive integers, string array, character vector, cell array of character vectors,pattern
scalar, logical vector, or a function handle.
If you specify'InputVariables'
as a function handle, then it must return a logical scalar, andvarfun
passes only the variables inA
where the function returns1
(true
).
GroupingVariables
—One or more variables inA
that define groups of rows
positive integer|vector of positive integers|string array|character vector|cell array of character vectors|pattern
scalar|logical vector
One or more variables inA
that define groups of rows, specified as the comma-separated pair consisting of'GroupingVariables'
and a positive integer, vector of positive integers, string array, character vector, cell array of character vectors,pattern
scalar, or logical vector.
The value of'GroupingVariables'
specifies which table variables are the grouping variables, not their data types. A grouping variable can be numeric, or have data typecategorical
,calendarDuration
,datetime
,duration
,logical
, orstring
.
Rows inA
that have the same grouping variable values belong to the same group.varfun
appliesfunc
to each group of rows within each of the variables ofA
, rather than to each entire variable.
If any grouping variable containsNaN
s or missing values (such asNaT
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 inA
, or on row labels and variables together.
If
A
is a table, then the labels are row names.If
A
is a timetable, then the labels are row times.
The output,B
, has one row for each group when you specify'OutputFormat','uniform'
or'OutputFormat','cell'
. When you specify'OutputFormat','table'
or'OutputFormat','timetable'
, the sizes of the outputs fromfunc
determine how many rows ofB
correspond to each group.
OutputFormat
—Format ofB
'table'
(default) |'timetable'
|'uniform'
|'cell'
Format ofB
, specified as the comma-separated pair consisting of'OutputFormat'
and either the value'uniform'
,'table'
,'timetable'
, or'cell'
.
|
If |
|
If |
|
|
|
|
ErrorHandler
—Function to call iffunc
fails
function handle
Function to call iffunc
fails, specified as the comma-separated pair consisting of'ErrorHandler'
and a function handle. Define this function so that it rethrows the error or returns valid outputs for functionfunc
.
MATLAB calls the specified error-handling function with two input arguments:
A structure with these fields:
identifier
Error identifier.
message
Error message text.
index
Index of the variable for which the error occurred.
name
Name of the variable for which the error occurred.
The set of input arguments to function
func
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
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function supports tall arrays with the limitations:
The
func
input must always return a tall array.Supported name-value pairs are:
'InputVariables'
— Cannot be specified as a function handle or pattern expressions.'GroupingVariables'
— Value cannot be pattern expressions.'OutputFormat'
— Value can be'uniform'
,'table'
,'timetable'
, or'cell'
only.
When the input array is a tall timetable and
'OutputFormat'
is'timetable'
, the specified function must return an array with the same size in the first dimension as the input. Specify'OutputFormat'
as'table'
when the input function is a reduction function such asmean
.
For more information, seeTall Arrays.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The function handle input,
func
, must be constant.While function handles can be inputs to
varfun
itself, they cannot be inputs to your entry point functions. Specifyfunc
within the code meant for code generation. For more information, seeFunction Handle Limitations for Code Generation(MATLAB Coder).The values for all name-value arguments must be constant.
The values of the
'InputVariables'
and'GroupingVariables'
name-value arguments do not support pattern expressions.The
'ErrorHandler'
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
'OutputFormat'
as'cell'
if you specify the'GroupingVariables'
name-value argument and the function returns a different data type for each variable specified by'InputVariables'
.If the input is a timetable and you specify
'GroupingVariables'
, 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.
Version History
Ouvrir l'exemple
Vous possédez une version modifiée de cet exemple. Souhaitez-vous ouvrir cet exemple avec vos modifications ?
Commande MATLAB
Vous avez cliqué sur un lien qui correspond à cette commande MATLAB :
Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.
Select a Web Site
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:.
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.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)