The Dot (.) Indexing

This method of dot indexing is similar to indexing a function from a class definition. We first call a given function with required parameters and then, index its various local variables (properties) using the . indexing. See the syntax of the same below:

function out = square(var)

out = struct(“prop”, var.^2);

end
square(x).prop;

Here, we used dummy function that calculates the square of any given number or vector. When the function is called, we then use the (.) indexing and get the value of the square which is stored as a key : value pair in a struct.

This method can be used when you do not want to want to create unnecessary output variables. This dot indexing will directly extract the required value from the temporary variable prop, which was created by the function call and thus, is not stored in the MATLAB workspace. Now, let us see some examples of the same.

Example 1

We shall use the square function as given in the syntax above and illustrate it with a specific case.

Matlab




% Code
square([1,2,3,4]).val
  
%function
function k = square(var)
  
%creating a struct to access the value as a property 
k = struct('val',var.^2);
end


Here, we create a square function which computes the square of a vector and instead of accessing it by the traditional storing in variable way, we use the function call indexing (dot indexing) to obtain the value.

Output:

 

Here, we obtained the square of passed vector without storing it into any variable.

The working of the above code can be understood from another approach where we use a variable to hold the value temporarily, let us see how.

Indexing into Function Call Results in MATLAB

MATLAB provides the option to return an array, vector, struct, etc. as the function return value. This means that the user can return an array/vector from a function call’s result. Naturally, there is a need to access those arrays/vectors and use them further in a MATLAB workspace. 

In this article, we shall see how to index function results in a MATLAB script with the help of various examples and methods.

Similar Reads

The Dot (.) Indexing

This method of dot indexing is similar to indexing a function from a class definition. We first call a given function with required parameters and then, index its various local variables (properties) using the . indexing. See the syntax of the same below:...

Using a Temporary Variable Instead

...

Conclusion

What we did in the previous example, can be done with the help of a temporary variable. See the code below to understand....