External Interfaces Previous page   Next Page

Creating an Array of Objects Within MATLAB

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.

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 would create with the Java code.

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 will probably be 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.)

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.

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.

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.

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

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


Previous page  Working with Java Arrays Accessing Elements of a Java Array Next page

© 1994-2005 The MathWorks, Inc.