External Interfaces/API    

Accessing Elements of a Java Array

You can access elements of a Java object array by using the MATLAB array indexing syntax, A(row,col). For example, to access the element of array dblArray located at row 3, column 4, use

In Java, this would be dblArray[2][3].

You can also use MATLAB array indexing syntax to access an element in an object's data field. Suppose that myMenuObj is an instance of a window menu class. This user-supplied class has a data field, menuItemArray, which is a Java array of java.awt.menuItem. To get element 3 of this array, use the following command.

Using Single Subscript Indexing to Access Arrays

Elements of a MATLAB matrix are most commonly referenced using both row and column subscripts. For example, you use x(3,4) to reference the array element at the intersection of row 3 and column 4. Sometimes it is more advantageous to use just a single subscript. MATLAB provides this capability (see the section on Advanced Indexing in the Using MATLAB manual).

Indexing into a MATLAB matrix using a single subscript references one element of the matrix. Using the MATLAB matrix shown here, matlabArray(3) returns a single element of the matrix.

Indexing this way into a Java array of arrays references an entire subarray of the overall structure. Using the dblArray Java array, that looks the same as matlabArray shown above, dblArray(3) returns the 5-by-1 array that makes up the entire third row.

This is a useful feature of MATLAB as it allows you to specify an entire array from a larger array structure, and then manipulate it as an object.

Using the Colon Operator

Use of the MATLAB colon operator (:) is supported in subscripting Java array references. This operator works just the same as when referencing the contents of a MATLAB array. Using the Java array of java.lang.Double objects shown here, the statement dblArray(2,2:4) refers to a portion of the lower level array, dblArray(2). A new array, row2Array, is created from the elements in columns 2 through 4.

You also can use the colon operator in single-subscript indexing, as covered in Using Single Subscript Indexing to Access Arrays. By making your subscript a colon rather than a number, you can convert an array of arrays into one linear array. The following example converts the 4-by-5 array dblArray into a 20-by-1 linear array.

This works the same way on an N-dimensional Java array structure. Using the colon operator as a single subscripted index into the array produces a linear array composed of all of the elements of the original array.

Using END in a Subscript

You can use the end keyword in the first subscript of an access statement. The first subscript references the top-level array in a multilevel Java array structure.

The following example displays data from the third to the last row of Java array dblArray.


  Creating an Array of Objects Within MATLAB Assigning to a Java Array