Main Content

Indexing into Function Call Results

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 expression myFunction(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:

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).Afield
ans =

     1

After this command executes, the temporary structure created by the command myStruct(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 in foo(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:

  • The function is invoked with parentheses, as in foo(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 by magic(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 named Var1. The variable contains a 10-by-2 matrix.

  • table(rand(10,2)).Var1 returns the 10-by-2 matrix contained in Var1.

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

See Also

|

Related Topics