Documentation |
On this page… |
---|
How MATLAB Represents the Java Array Creating an Array of Objects in MATLAB Accessing Elements of a Java Array |
You can pass singular Java^{®} objects to and from methods or you can pass them in an array, providing the method expects them in that form. This array must either be a Java array (returned from another method call or created within the MATLAB^{®}) or, under certain circumstances, a MATLAB cell array. This section describes how to create and manipulate Java arrays in MATLAB. Later sections describe how to use MATLAB cell arrays in calls to Java methods.
The term Java array refers to any array of Java objects returned from a call to a Java class constructor or method. You can also construct a Java array within MATLAB using the javaArray function. The structure of a Java array is different from the structure of a MATLAB matrix or array. MATLAB hides these differences whenever possible, allowing you to operate on the arrays using the usual MATLAB command syntax. Just the same, keep in mind the following differences as you work with Java arrays.
An array in the Java language is strictly a one-dimensional structure because it is measured only in length. If you want to work with a two-dimensional array, you can create an equivalent structure using an array of arrays. To add further dimensions, you add more levels to the array, making it an array of arrays of arrays, and so on. You can use such multilevel arrays when working in MATLAB, as it is a matrix and array-based programming language.
MATLAB makes it easy for you to work with multilevel Java arrays by treating them like the matrices and multidimensional arrays that are a part of the language itself. You access elements of an array of arrays using the same MATLAB syntax that you use if you are handling a matrix. If you add more levels to the array, MATLAB can access and operate on the structure as if it is a multidimensional MATLAB array.
The left side of the following figure shows Java arrays of one, two, and three dimensions. To the right of each representation is the same array represented in MATLAB. Single-dimension arrays are represented as column vectors.
Java array indexing is different than MATLAB array indexing. Java array indices are zero-based, MATLAB array indices are one-based. In Java programming, you access the elements of array y of length N using y[0] through y[N-1]. When working with this array in MATLAB, you access these same elements using the MATLAB indexing style of y(1) through y(N). Thus, if you have a Java array of ten elements, the seventh element is obtained using y(7), and not y[6] as you use when writing a Java language program.
A Java array can be different from a MATLAB array in its overall shape. A two-dimensional MATLAB array maintains a rectangular shape, as each row is of equal length and each column of equal height. The Java counterpart, an array of arrays, does not necessarily hold to this rectangular form. Each individual lower level array might have a different length.
The following picture shows an array of three underlying arrays of different lengths. The terms jagged or ragged are commonly used to describe this arrangement of array elements as the array ends do not match up evenly. When a Java method returns an array with this type of structure, it is stored in a cell array by MATLAB.
Calling the MATLAB size function on a Java array returns the length of the Java array. The number of columns is always 1.
Determining the size of a Java array of arrays is not so simple. The potentially ragged shape of an array returned from a Java method makes it impossible to size the array in the same way as for a rectangular matrix. In a ragged Java array, there is no one value that represents the size of the lower-level arrays.
When the size function is applied to a Java array of arrays, the resulting value describes the top level of the specified array. For the Java array:
size(A) returns the dimensions of the highest array level of A. The highest level of the array has a size of 3-by-1.
size(A)
ans = 3 1
To find the size of a lower-level array, say the five-element array in row 3, refer to the row explicitly.
size(A(3))
ans = 5 1
You can specify a dimension in the size command using the following syntax. However, you will probably find this useful only for sizing the first dimension, dim=1, as this will be the only non-unary dimension.
m = size(X,dim) size(A, 1)
ans = 3
The MATLAB ndims function always returns a value of 2 for the number of dimensions in a Java array. This is a measure of the number of dimensions in the top-level array, which always equals 2.
To call a Java method that has one or more arguments defined as an array of Java objects, you must, under most circumstances, pass your objects in a Java array. You can construct an array of objects in a call to a Java method or constructor. Or you can create the array within MATLAB.
The MATLAB javaArray function lets you create a Java array structure that can be handled in MATLAB as a single multidimensional array. You specify the number and size of the array dimensions along with the class of objects you intend to store in it. Using the one-dimensional Java array as its primary building block, MATLAB then builds an array structure that satisfies the dimensions requested in the javaArray command.
To create a Java object array, use the MATLAB javaArray function, which has the following syntax:
A = javaArray('element_class', m, n, p, ...)
The first argument is the 'element_class' string, which names the class of the elements in the array. Specify the fully qualified name (package and class name). The remaining arguments (m, n, p, ...) are the number of elements in each dimension of the array.
An array that you create with javaArray is equivalent to the array that you create with the Java code.
A = new element_class[m][n][p]...;
The following command builds a Java array of four lower-level arrays, each capable of holding five objects of the java.lang.Double class.
dblArray = javaArray('java.lang.Double',4,5);
The javaArray function does not deposit any values into the array elements that it creates. You must do this separately. The following MATLAB code stores objects of the java.lang.Double type in the Java array dblArray that was created.
for m = 1:4 for n = 1:5 dblArray(m,n) = java.lang.Double((m*10) + n); end end dblArray
dblArray = java.lang.Double[][]: [11] [12] [13] [14] [15] [21] [22] [23] [24] [25] [31] [32] [33] [34] [35] [41] [42] [43] [44] [45]
You also can create an array of Java objects using syntax that is more typical to MATLAB. For example, the following syntax creates a 4-by-5 MATLAB array of type double and assigns zero to each element of the array.
matlabArr(4,5) = 0;
You use similar syntax to create a Java array in MATLAB, except that you must specify the Java class name. The value being assigned, 0 in this example, is stored in the final element of the array, javaArr(4,5). All other elements of the array receive the empty matrix.
javaArr(4,5) = java.lang.Double(0)
javaArr = java.lang.Double[][]: [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [0]
Note: You cannot change the dimensions of an existing Java array as you can with a MATLAB array. The same restriction exists when working with Java arrays in the Java language. See the following example. |
This example first creates a scalar MATLAB array, and then successfully modifies it to be two-dimensional.
matlabArr = 0; matlabArr(4,5) = 0
matlabArr = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
When you try this technique with a Java array, you get an error message.
javaArr = java.lang.Double(0); javaArr(4,5) = java.lang.Double(0);
Index exceeds Java array dimensions.
Similarly, you cannot create an array of Java arrays from 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 at row 3, column 4, use:
row3_col4 = dblArray(3,4)
row3_col4 = 34.0
To access this element in a Java language program, use dblArray[2][3].
You also can use MATLAB array indexing syntax to access an element in the data field of an object. 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.
currentItem = myMenuObj.menuItemArray(3)
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 Linear Indexing in MATLAB Mathematics).
Indexing into a MATLAB matrix using a single subscript references one element of the matrix. Using the MATLAB matrix shown here, matlabArr (3) returns a single element of the matrix.
matlabArr = [11 12 13 14 15; 21 22 23 24 25; ...
31 32 33 34 35; 41 42 43 44 45]
matlabArr = 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35 41 42 43 44 45
matlabArr(3)
ans = 31
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 matlabArr, dblArray(3) returns the 5-by-1 array that makes up the entire third row.
row3 = dblArray(3)
row3 = java.lang.Double[]: [31] [32] [33] [34] [35]
This feature allows you to specify an entire array from a larger array structure, and then manipulate it as an object.
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.
dblArray
dblArray = java.lang.Double[][]: [11] [12] [13] [14] [15] [21] [22] [23] [24] [25] [31] [32] [33] [34] [35] [41] [42] [43] [44] [45]
row2Array = dblArray(2,2:4)
row2Array = java.lang.Double[]: [22] [23] [24]
You also can use the colon operator in single-subscript indexing, as covered in Single Subscript Indexing. 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.
linearArray = dblArray(:)
linearArray = java.lang.Double[]: [11] [12] [13] [14] [15] [21] [22] . . .
This method also works 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.
Note: Java and MATLAB arrays are stored differently in memory. This is reflected in the order they are given in a linear array. Java array elements are stored in an order that matches the rows of the matrix (linearArray elements 11, 12, 13, ...). MATLAB array elements are stored in an order that matches the columns (elements 11, 21, 31, ...). |
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.
Note: Using end on lower-level arrays is not valid due to the potentially ragged nature of these arrays (see The Shape of the Java Array). In this case, there is no consistent end value to be derived. |
The following example displays data from the third to the last row of Java array dblArray.
last2rows = dblArray(3:end, :)
last2rows = java.lang.Double[][]: [31] [32] [33] [34] [35] [41] [42] [43] [44] [45]
When you access an element of a java.lang.Object array, MATLAB converts the element to a MATLAB type, according to the table in Conversion of Java Object Return Types. MATLAB does not convert elements of any other type of Java array.
For example, if a java.lang.Object array contains a java.lang.Double element, MATLAB converts the element to MATLAB double. But MATLAB does not convert a java.lang.Double element in a java.lang.Double array; MATLAB returns it as java.lang.Double.
You assign values to objects in a Java array in essentially the same way as you do in a MATLAB array. Although Java and MATLAB arrays are structured differently, you use the same command syntax to specify which elements you want to assign to. See Introduction for more information on Java and MATLAB array differences.
The following example deposits the value 300 in the dblArray element at row 3, column 2. In a Java language program, this is dblArray[2][1].
dblArray(3,2) = java.lang.Double(300)
dblArray = java.lang.Double[][]: [11] [ 12] [13] [14] [15] [21] [ 22] [23] [24] [25] [31] [300] [33] [34] [35] [41] [ 42] [43] [44] [45]
Use the same syntax to assign to an element to the data field of an object. Continuing with the myMenuObj example shown in Accessing Elements of a Java Array, assign to the third menu item in menuItemArray as follows.
myMenuObj.menuItemArray(3) = java.lang.String('Save As...');
You can use a single-array subscript to index into a Java array structure that has more than one dimension. Refer to Single Subscript Indexing for a description of this feature as used with Java arrays.
You can use single-subscript indexing to assign values to an array as well. The following example assigns a one-dimensional Java array, onedimArray, to a row of a two-dimensional Java array, dblArray. Start out by creating the one-dimensional array.
onedimArray = javaArray('java.lang.Double', 5); for k = 1:5 onedimArray(k) = java.lang.Double(100 * k); end
Since dblArray(3) refers to the 5-by-1 array displayed in the third row of dblArray, you can assign the entire, similarly dimensioned, 5-by-1 onedimArray to it.
dblArray(3) = onedimArray
dblArray = java.lang.Double[][]: [ 11] [ 12] [ 13] [ 14] [ 15] [ 21] [ 22] [ 23] [ 24] [ 25] [100] [200] [300] [400] [500] [ 41] [ 42] [ 43] [ 44] [ 45]
You can assign a value to every element of a multidimensional Java array by treating the array structure as if it were a single linear array. This entails replacing the single, numerical subscript with the MATLAB colon operator. If you start with the dblArray array, you can initialize the contents of every object in the two-dimensional array with the following statement.
dblArray(:) = java.lang.Double(0)
dblArray = java.lang.Double[][]: [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0]
You can use the MATLAB colon operator as you would when working with MATLAB arrays. The following statements assign given values to each of the four rows in the Java array, dblArray. Remember that each row actually represents a separate Java array in itself.
dblArray(1,:) = java.lang.Double(125); dblArray(2,:) = java.lang.Double(250); dblArray(3,:) = java.lang.Double(375); dblArray(4,:) = java.lang.Double(500)
dblArray = java.lang.Double[][]: [125] [125] [125] [125] [125] [250] [250] [250] [250] [250] [375] [375] [375] [375] [375] [500] [500] [500] [500] [500]
When working with MATLAB arrays, you can assign the empty matrix, (that is, the 0-by-0 array denoted by []) to an element of the array. For Java arrays, you also can assign [] to array elements. This stores the NULL value, rather than a 0-by-0 array, in the Java array element.
When you assign the empty matrix value to an entire row or column of a MATLAB array, you find that MATLAB actually removes the affected row or column from the array. In the example below, the empty matrix is assigned to all elements of the fourth column in the MATLAB matrix, matlabArr. Thus, the fourth column is eliminated from the matrix. This changes its dimensions from 4-by-5 to 4-by-4.
matlabArr = [11 12 13 14 15; 21 22 23 24 25; ...
31 32 33 34 35; 41 42 43 44 45]
matlabArr = 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35 41 42 43 44 45
matlabArr(:,4) = []
matlabArr = 11 12 13 15 21 22 23 25 31 32 33 35 41 42 43 45
You can assign the empty matrix to a Java array, but the effect is different. The next example shows that, when the same operation is performed on a Java array, the structure is not collapsed; it maintains its 4-by-5 dimensions.
dblArray(:,4) = []
dblArray = java.lang.Double[][]: [125] [125] [125] [] [125] [250] [250] [250] [] [250] [375] [375] [375] [] [375] [500] [500] [500] [] [500]
The dblArray data structure is actually an array of five-element arrays of java.lang.Double objects. The empty array assignment placed the NULL value in the fourth element of each of the lower-level arrays.
You can concatenate arrays of Java objects in the same way as arrays of other types. Java objects, however, can only be catenated along the first or second axis. To understand how scalar Java objects are concatenated in MATLAB, see Concatenating Java Objects.
Use either the cat function or the square bracket ([]) operators. This example horizontally concatenates two Java arrays: d1 and d2.
% Construct a 2-by-3 array of java.lang.Double. d1 = javaArray('java.lang.Double',2,3); for m = 1:2 for n = 1:3 d1(m,n) = java.lang.Double(n*2 + m-1); end end d1
d1 = java.lang.Double[][]: [2] [4] [6] [3] [5] [7]
% Construct a 2-by-2 array of java.lang.Double. d2 = javaArray('java.lang.Double',2,2); for m = 1:2 for n = 1:2 d2(m,n) = java.lang.Double((n+3)*2 + m-1); end end d2
d2 = java.lang.Double[][]: [8] [10] [9] [11]
% Concatenate the two along the second dimension.
d3 = cat(2,d1,d2)
d3 = java.lang.Double[][]: [2] [4] [6] [ 8] [10] [3] [5] [7] [ 9] [11]
Because Java arrays in MATLAB are references, assigning an array variable to another variable results in a second reference to the array.
Consider the following example where two separate array variables reference a common array. The original array, origArray, is created and initialized. The statement newArrayRef = origArray creates a copy of this array variable. Changes made to the array referred to by newArrayRef also show up in the original array.
origArray = javaArray('java.lang.Double', 3, 4); for m = 1:3 for n = 1:4 origArray(m,n) = java.lang.Double((m * 10) + n); end end origArray
origArray = java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [31] [32] [33] [34]
% Make a copy of the array reference
newArrayRef = origArray;
newArrayRef(3,:) = java.lang.Double(0);
origArray
origArray = java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [ 0] [ 0] [ 0] [ 0]
You can create an entirely new array from an existing Java array by indexing into the array to describe a block of elements, or subarray, and assigning this subarray to a variable. The assignment copies the values in the original array to the corresponding cells of the new array.
As with the example in section Creating a New Array Reference, an original array is created and initialized. But, this time, a copy is made of the array contents rather than copying the array reference. Changes made using the reference to the new array do not affect the original.
origArray = javaArray('java.lang.Double', 3, 4); for m = 1:3 for n = 1:4 origArray(m,n) = java.lang.Double((m * 10) + n); end end origArray
origArray = java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [31] [32] [33] [34]
% ----- Make a copy of the array contents -----
newArray = origArray(:,:);
newArray(3,:) = java.lang.Double(0);
origArray
origArray = java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [31] [32] [33] [34]