Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Working with Java Arrays

Introduction

You can pass singular Sun Java objects to and from methods or you may 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 software) or, under certain circumstances, a MATLAB cell array. This section describes how to create and manipulate Java arrays in MATLAB. Later sections will describe how to use MATLAB cell arrays in calls to Java methods.

How MATLAB Software Represents the Java Array

The term Java array refers to any array of Java objects returned from a call to a Java class constructor or method. You may also construct a Java array within MATLAB using the javaArray function. The structure of a Java array is significantly different from that 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, it may be helpful to keep the following differences in mind as you work with Java arrays.

Representing More Than One Dimension

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 may want to 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 is the way the same array is represented to you in MATLAB. Note that single-dimension arrays are represented as a column vector.

Figure: Java arrays and MATLAB representations

Array Indexing

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 software indexing style of y(1) through y(N). Thus, if you have a Java array of 10 elements, the seventh element is obtained using y(7), and not y[6] as you use when writing a Java language program.

The Shape of the Java Array

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 of this, an array of arrays, does not necessarily hold to this rectangular form. Each individual lower level array may have a different length.

Such an array structure is pictured below. This is an array of three underlying arrays of different lengths. The term ragged is 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.

Figure showing ragged arrangement of three arrays of different lengths

Interpreting the Size of a Java Array

When the MATLAB size function is applied to a simple Java array, the number of rows returned is the length of the Java array and 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:

illustration of the application of the size function to a Java array of arrays

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

Interpreting the Number of Dimensions of a Java Arrays

For Java arrays, whether they are simple one-level arrays or multilevel, the MATLAB ndims function always returns a value of 2 to indicate the number of dimensions in the array. This is a measure of the number of dimensions in the top-level array, which always equals 2.

Creating an Array of Objects in MATLAB Software

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.

Using the javaArray Function

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. You must 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. (You are more likely to use primitive types of double than instances of the java.lang.Double class, but in this context, it affords us a simple example.)

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 just 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]

Another Way to Create a Java Array

You can also 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.

matlabArray(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, javaArray(4,5). All other elements of the array receive the empty matrix.

javaArray(4,5) = java.lang.Double(0)
javaArray =
java.lang.Double[][]:
     []     []     []     []     []
     []     []     []     []     []
     []     []     []     []     []
     []     []     []     []    [0]

This example first creates a scalar MATLAB array, and then successfully modifies it to be two-dimensional.

matlabArray = 0;
matlabArray(4,5) = 0

matlabArray =

     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0

When you try this with a Java array, you get an error message. Similarly, you cannot create an array of Java arrays from a Java array, and so forth.

javaArray = java.lang.Double(0);
javaArray(4,5) = java.lang.Double(0);
??? Index exceeds Java array dimensions.

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:

row3_col4 = dblArray(3,4)
row3_col4 = 
34.0

In a Java language program, this is 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.

currentItem = myMenuObj.menuItemArray(3)

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 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, matlabArray (3) returns a single element of the matrix.

matlabArray = [11 12 13 14 15; 21 22 23 24 25; ...
               31 32 33 34 35; 41 42 43 44 45]
matlabArray =
    11    12    13    14    15
    21    22    23    24    25
    31    32    33    34    35
    41    42    43    44    45

matlabArray(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 matlabArray shown above, 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 is a useful feature of MATLAB because 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.

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 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.

linearArray = dblArray(:)
linearArray = 
java.lang.Double[]:
    [11]
    [12]
    [13]
    [14]
    [15]
    [21]
    [22]
     .
     .
     .

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.

last2rows = dblArray(3:end, :)
last2rows =
java.lang.Double[][]:
    [31]    [32]    [33]    [34]    [35]
    [41]    [42]    [43]    [44]    [45]

Assigning to a Java Array

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 quite 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]

You use the same syntax to assign to an element in an object's data field. Continuing with the myMenuObj example shown in Accessing Elements of a Java Array, you assign to the third menu item in menuItemArray as follows.

myMenuObj.menuItemArray(3) = java.lang.String('Save As...');

Using Single Subscript Indexing for Array Assignment

You can use a single-array subscript to index into a Java array structure that has more than one dimension. Refer to Using Single Subscript Indexing to Access Arrays 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 example below 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]

Assigning to a Linear Array

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 statements below 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]

Assigning the Empty Matrix

When working with MATLAB arrays, you can assign the empty matrix, (i.e., the 0-by-0 array denoted by []) to an element of the array. For Java arrays, you can also assign [] to array elements. This stores the NULL value, rather than a 0-by-0 array, in the Java array element.

Subscripted Deletion

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, matlabArray. Thus, the fourth column is completely eliminated from the matrix. This changes its dimensions from 4-by-5 to 4-by-4.

matlabArray = [11 12 13 14 15; 21 22 23 24 25; ...
               31 32 33 34 35; 41 42 43 44 45]
matlabArray =
    11    12    13    14    15
    21    22    23    24    25
    31    32    33    34    35
    41    42    43    44    45

matlabArray(:,4) = []
matlabArray =
    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.

Concatenating Java 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 software, 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:3     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]
    [4]    [6]    [8]

% Construct a 2-by-2 array of java.lang.Double.
d2 = javaArray('java.lang.Double',2,2);
for m = 1:3     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]
    [10]    [12]

% 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]
    [4]    [6]    [8]    [10]    [12]

Creating a New Array Reference

Because Java arrays in MATLAB software 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]

Creating a Copy of a Java Array

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]
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS