Indexing into Function Call Results - MATLAB & Simulink (original) (raw)

Main Content

This topic describes how to dot index into temporary variables created by function calls. A temporary variable is 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 calls myFunction with the argument x, and then returns the prop property of the result. You can invoke any type of function (anonymous, local, nested, or private) in this way.

Example

Consider the function:

function y = myStruct(x) y = struct("Afield",x); end

This function creates a structure with one field, named Afield, 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:

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:

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 clear S

Supported Syntaxes

MATLAB supports dot indexing into function call results, as infoo(arg).prop. Other forms of indexing into function call results (with parentheses such as foo(arg)(2) or with curly braces such as foo(arg){2}) are not supported. Successful commands must meet the criteria:

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.

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:

See Also

function | subsref

Topics