Main Content

Indexing into Function Call Results

This topic describes how to dot index into temporary variables created by function calls. Atemporary variableis created when the result of a function call is used as an intermediate variable in a larger expression. The result of the function call in the expression is temporary because the variable it creates exists only briefly, and is not stored in the MATLAB®workspace after execution. An example is the expressionmyFunction(x).prop, which callsmyFunctionwith the argumentx, and then returns thepropproperty of the result. You can invoke any type of function (anonymous, local, nested, or private) in this way.

Example

Consider the function:

functiony = myStruct(x) y = struct(“ Afield”,X);end

This function creates a structure with one field, named远处, and assigns a value to the field. You can invoke the function and create a structure with a field containing the value 1 with the command:

myStruct(1)
ans = struct with fields: Afield: 1

However, if you want to return the field value directly, you can index into the function call result with the command:

Mystruct(1).Field
ans = 1

After this command executes, the temporary structure created by the commandmyStruct(1)no longer exists, and MATLAB returns only the field value. Conceptually, this usage is the same as creating the structure, indexing into it, and then deleting it:

S = struct(“ Afield”,1); S.Afield clearS

Supported Syntaxes

MATLAB supports dot indexing into function call results, as infoo(arg).prop。其他形式的索引到函数调用结果(带有括号,例如foo(arg)(2)or with curly braces such asfoo(arg){2}不支持)。万博1manbetx成功的命令必须满足the criteria:

  • The function is invoked with parentheses, as infoo(arg1,arg2,...)

  • The function returns a variable for which dot indexing is defined, such as a structure, table, or object.

  • The dot indexing subscript is valid.

MATLAB always attempts to apply the dot indexing operation to the temporary variable, even if the function returns a variable for which dot indexing is not defined. For example, if you try to index into the matrix created bymagic(3), then you get an error.

magic(3).field
Dot indexing is not supported for variables of this type.

You can add more indexing commands onto the end of an expression as long as the temporary variables can continue to be indexed. For example, consider the expression:

table(rand(10,2)).Var1(3,:)
In this expression, you index into a table to get the matrix it contains, and then index into the matrix to get the third row:

  • table(rand(10,2))creates a table with one variable namedVar1。The variable contains a 10-by-2 matrix.

  • table(rand(10,2)).Var1returns the 10-by-2 matrix contained inVar1

  • table(rand(10,2)).Var1(3,:)returns the third row in the matrix contained inVar1

See Also

|

相关话题