® MATLAB Builder for Java™ The Language of Technical Computing Computation Visualization Programming User’s Guide Version 1
How to Contact The MathWorks Web Newsgroup www.mathworks.com/contact_TS.html Technical Support www.mathworks.com comp.soft-sys.matlab Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.com info@mathworks.com 508-647-7000 (Phone) 508-647-7001 (Fax) The MathWorks, Inc.
Contents Getting Started 1 What Is MATLAB Builder for Java? . . . . . . . . . . . . . . . . . . Support for MATLAB Features in Java . . . . . . . . . . . . . . . . Known Issue in Data Returned by toArray Referencing Sparse Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the Deployment Tool . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 Creating a Java Component . . . . . . . . . . . . . . . . . . . . . . . . Using the Command-Line Interface . . . . . . . . . .
How Does MATLAB Builder for Java Handle Data? . . . Understanding the API Data Conversion Classes . . . . . . . Automatic Conversion to MATLAB Types . . . . . . . . . . . . . . Understanding Function Signatures Generated by Java Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Returning Data from MATLAB to Java . . . . . . . . . . . . . . . . 2-4 2-4 2-5 ................ 2-9 What Happens in the Package Process? . . . . . . . . . . . . . .
Handling Data Conversion Between Java and MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Calling MWArray Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28 3-28 Using MWArray Classes 4 Guidelines for Working with MWArray Classes . . . . . . . Overview of the MWArray API . . . . . . . . . . . . . . . . . . . . . . . Understanding the MWArray Base Class . . . . . . . . . . . . . . Constructing Numeric Arrays . . . . . . . . . . . . . . . . . . . . . . .
Reference Information for Java 6 Requirements for MATLAB Builder for Java . . . . . . . . . System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limitations and Restrictions . . . . . . . . . . . . . . . . . . . . . . . . Settings for Environment Variables (Development Machine) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 6-2 6-2 MATLAB Builder for Java Graphical User Interface . . 6-7 Data Conversion Rules . . . . . . . . . . . . . . . . .
Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2 ................................. A-3 Sample Applications (Java) . . . . . . . . . . . . . . . . . . . . . . . . .
viii Contents
1 Getting Started What Is MATLAB Builder for Java? (p. 1-2) Brief description of what the product does and how it works Creating a Java Component (p. 1-5) Step-by-step procedure to create and package a Java™ component that encapsulates MATLAB® code Developing an Application (p. 1-12) Step-by-step procedure to access the component in an application Deploying an Application (p. 1-14) What you have to do to support end users who run applications using your components Example: Magic Square (p.
1 Getting Started What Is MATLAB Builder for Java? MATLAB Builder for Java (also called Java Builder) is an extension to MATLAB Compiler. Use Java Builder to wrap MATLAB functions into one or more Java classes that make up a Java component, or package. Each MATLAB function is encapsulated as a method of a Java class and can be invoked from within a Java application.
What Is MATLAB Builder for Java? Using the Deployment Tool The Deployment Tool provides a graphical user interface to Java Builder.
1 Getting Started Use the Deployment Tool to perform the following tasks: 1-4
Creating a Java Component Creating a Java Component To create a component you need to write M-code (or use existing code) and then create a project in MATLAB Builder for Java that encapsulates the code. In general, the steps are as follows: 1 Write, test, and save the MATLAB code to be used as the basis for the Java component. 2 Set the environment variables that are required on a development machine. See “Settings for Environment Variables (Development Machine)” on page 6-2.
1 Getting Started The .ctf is a component technology file, which is required to support components that encapsulate MATLAB functions when running them on a user machine that does not have the MATLAB desktop installed. 6 Test the component and rebuild it as needed. You probably want to test your component before using it in an application or before preparing it for use by others. After testing the component on your development platform, you can reopen the project if necessary and proceed to the next step.
Creating a Java Component Using the Command Line to Create Java Components Action to Perform mcc Option to Use Description Create a class encapsulating one or more M-files. -W java: Tells Java Builder to generate a Java component that contains a class that encapsulates the specified files. Syntax mcc -W 'java:component_name[,class_name]' file1 [file2...fileN] component_name is a fully qualified package name for your component. The name is a period-separated list.
1 Getting Started Using the Command Line to Create Java Components (Continued) Action to Perform mcc Option to Use Description Add additional classes to a Java component. class{...} Used with -W java:. Tells Java Builder to create class_name, which encapsulates one or more M-files that are specified in a comma-separated list. Syntax class{class_name:file1 [file2...fileN]} Example mcc -W 'java:com.mycompany.mycomponent,myclass' foo.m bar.m class{myclass2:foo2.m,bar2.
Creating a Java Component Using the Command Line to Create Java Components (Continued) Action to Perform mcc Option to Use Description Simplify the command-line input for components. -B Tells Java Builder to replace a specified file with the command-line information it contains. Syntax mcc -B 'bundlefile'[:arg1, arg2, ..., argN] Example Suppose a myoptions file contains -W 'java:mycomponent,myclass' In this case, mcc -B 'myoptions' foo.m bar.
1 Getting Started Using the Command Line to Create Java Components (Continued) Action to Perform mcc Option to Use Description Control how each Java class uses the MCR. -S Tells Java Builder to create a single MCR when the first Java class is instantiated. This MCR is reused and shared among all subsequent class instances within the component, resulting in more efficient memory usage and eliminating the MCR startup cost in each subsequent class instantiation.
Creating a Java Component Note All of these command-line examples produce the following files: mycomponent.jar (component jar file) mycomponent.ctf (component ctf file) Notice that the component name used to create these files is derived from the last item on the period-separated list that specifies the fully qualified name of the class.
1 Getting Started Developing an Application 1 If the component is not already installed on the machine where you want to develop your application, unpack and install the component as follows: a. Copy the package that was created in the last step in “Creating a Java Component” on page 1-5. b. If the package is a self-extracting executable, paste the package in a directory on the development machine, and run it. If the package is a .zip file, unzip and extract the contents to the development machine.
Developing an Application • To manually convert to one of the standard MATLAB data types, use MWArray classes in the package com.mathworks.toolbox,javabuilder. See Chapter 4, “Using MWArray Classes” for an introduction to the classes and see com.mathworks.toolbox.javabuilder.MWArray (available online only) for reference information for this class library. • If you pass them as Java data types, they are automatically converted. 7 Build and test the Java application as you would any application.
1 Getting Started Deploying an Application To deploy your application you must make sure that the installer you create for the application takes care of supporting the components created by MATLAB Builder for Java. In general, this means that the MCR must be installed on the target machine, in addition to the application files. Users must also set paths and environment variables correctly. See “Deploying to End Users” in the MATLAB Compiler documentation.
Example: Magic Square Example: Magic Square This example shows you how to: • Access the online examples provided with MATLAB Builder for Java. • Use MATLAB Builder for Java to encapsulate a simple MATLAB function in a Java component. • Use the MWArray class library to handle data conversion in a sample application. About the Examples The examples for MATLAB Builder for Java are in matlabroot\toolbox\javabuilder\Examples.
1 Getting Started matlabroot\toolbox\javabuilder\Examples\MagicSquareExample This procedure assumes that you are working on Windows and your work directory is D:\Work. b. At the MATLAB command prompt, change directory to the new MagicSquareExample subdirectory in your work directory. 3 Write the makesqr function as you would any MATLAB function.
Example: Magic Square When you create a new project, the Deployment Tool dialog box shows the folders that are part of the project. By default the top folder represents a Java class belonging to the component. By default the class name is the same as the project name. Note When a new project first opens, the folders in the project are empty. 6 Enter the settings for the project. a. Right-click the top folder, which represents the Java class you are going to create, and select Rename Class. b.
1 Getting Started 8 Access the component in a Java application. The sample application for this example is in MagicSquareExample\MagicDemoJavaApp\getmagic.java. getmagic.java /* getmagic.java * This file is used as an example for the MATLAB * Builder for Java product. * * Copyright 2001-2006 The MathWorks, Inc. */ /* Necessary package imports */ import com.mathworks.toolbox.javabuilder.*; import magicsquare.*; /* * getmagic class computes a magic square of order N.
Example: Magic Square System.out.println("Magic square of order " + n.toString()); /* Create new magic object */ theMagic = new magic(); /* Compute magic square and print result */ result = theMagic.makesqr(1, n); System.out.println(result[0]); } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { /* Free native resources */ MWArray.disposeArray(n); MWArray.disposeArray(result); if (theMagic != null) theMagic.
1 Getting Started MATLAB function, nargout, in the method being called. The second input argument is the input specified in the function declaration statement of the makesqr M-file. Note The previous calling syntax is not the only way that you can call the makesqr method. When Java Builder encapsulates makesqr.m, it overloads the function, creating several signatures by which you can call the makesqr method. This lets you specify optional arguments when calling from Java.
Example: Magic Square b. On UNIX, execute this command: javac -classpath .:matlabroot/toolbox/javabuilder/jar/javabuilder.jar: ./distrib/magicsquare.jar getmagic.java 10 Run the application. If you used the Deployment Tool to create it, you can use the following commands to run the getmagic.class file: On Windows, type java -classpath .;matlabroot\toolbox\javabuilder\jar\javabuilder.jar; .\distrib\magicsquare.jar -Djava.library.path=matlabroot\bin\win32;.
1 Getting Started When you run the program you pass an argument representing the dimension for the magic square. In this example, the value for the dimension is 5. The program converts the number passed on the command line to a scalar double value, creates an instance of class magic, and calls the makesqr method on that object. The method computes the square using the MATLAB magic function.
Understanding the Magic Square Example Understanding the Magic Square Example The Magic Square example shows the following aspects of writing an application using components created by MATLAB Builder for Java: • “Importing Classes” on page 1-23 • “Creating an Instance of the Class” on page 1-23 • “Calling Class Methods from Java” on page 1-23 Importing Classes You must import the MATLAB libraries and your own Java classes into your code. Use the Java import function to do this.
1 Getting Started where n is an instance of an MWArray class. See the following code fragment for the declaration of n: n = new MWNumericArray(Double.valueOf(args[0], MWClassID.
For More Information For More Information Understanding concepts needed to use MATLAB Builder for Java Chapter 2, “Concepts” Writing Java applications that can access Java methods that encapsulate M-code Chapter 3, “Programming” Using the MWArray API to handle data conversion Chapter 4, “Using MWArray Classes” Sample applications that access methods developed in MATLAB Chapter 5, “Sample Applications (Java)” Reference information about automatic data conversion rules “Data Conversion Rules” on pag
1 1-26 Getting Started
2 Concepts A component created by MATLAB Builder for Java is a stand-alone Java package (.jar file). The package contains one or more Java classes that encapsulate M-code. The classes provide methods that are callable directly from Java code. To use MATLAB Builder for Java you create a project, which specifies the M-code to be used in the components that you want to create. Java Builder supports data conversion between Java types and MATLAB types.
2 2-2 Concepts What Happens in the Build Process? (p. 2-9) Details about the process of building a Java component What Happens in the Package Process? (p. 2-10) Details about the packaging process How Does Component Deployment Work? (p.
What Is a Project? What Is a Project? A Java Builder project contains information about the files and settings needed by MATLAB Builder for Java to create a deployable Java component. A project specifies information about classes and methods, including the MATLAB functions to be included. • “Classes and Methods” on page 2-3 • “Naming Conventions” on page 2-3 Classes and Methods Java Builder transforms MATLAB functions that are specified in the component’s project to methods belonging to a Java class.
2 Concepts How Does MATLAB Builder for Java Handle Data? To enable Java applications to exchange data with MATLAB methods they invoke, Java Builder provides an API, which is implemented as the com.mathworks.toolbox.javabuilder.MWArray package. This package provides a set of data conversion classes derived from the abstract class, MWArray. Each class represents a MATLAB data type.
How Does MATLAB Builder for Java Handle Data? Overview of Classes and Methods in the Data Conversion Class Hierarchy The root of the data conversion class hierarchy is the MWArray abstract class. The MWArray class has the following subclasses representing the major MATLAB types: MWNumericArray, MWLogicalArray, MWCharArray, MWCellArray, and MWStructArray. Each subclass stores a reference to a native MATLAB array of that type.
2 Concepts class before it is passed to the method. Java Builder can convert any Java string, numeric type, or any multidimensional array of these types to an appropriate MWArray type, using its data conversion rules. See “Data Conversion Rules” on page 6-10 for a list of all the data types that are supported along with their equivalent types in MATLAB.
How Does MATLAB Builder for Java Handle Data? Understanding MATLAB Function Signatures As background, recall that the generic MATLAB function has the following structure: function [Out1, Out2, ..., varargout]=foo(In1, In2, ..., varargin) To the left of the equal sign, the function specifies a set of explicit and optional return arguments. To the right of the equal sign, the function lists explicit input arguments followed by one or more optional arguments. Each argument represents a MATLAB type.
2 Concepts Return data is not converted to a Java type. If you choose to use a Java type, you must convert to that type using the toArray method of the MWArray subclass to which the return data belongs.
What Happens in the Build Process? What Happens in the Build Process? Note MATLAB Builder for Java uses the JAVA_HOME variable to locate the Java Software Development Kit (SDK) on your system. The compiler uses this variable to set the version of the javac.exe command it uses during compilation. To create a component, Java Builder does the following: 1 Generates Java code to implement your component. The files are as follows: myclass.
2 Concepts What Happens in the Package Process? The packaging process creates a self-extracting executable (on Windows platforms) or a .zip file (on non-Windows platforms). The package contains at least the following: • The Java Builder component • The .ctf file for the component • The MCR Installer (if the Install MCR option was selected when the component was built) Note The packaging process is not available when using mcc directly.
How Does Component Deployment Work? How Does Component Deployment Work? There are two kinds of deployment: • Installing components and setting up support for them on a development machine so that they can be accessed by a developer who seeks to use them in writing a Java application. To accomplish this kind of deployment, create a package, using the GUI, as described in “Creating a Java Component” on page 1-5. • Deploying support for the components when they are accessed at run time on an end-user machine.
2 2-12 Concepts
3 Programming To access a Java component built and packaged by MATLAB Builder for Java, you must first unpack and install components so you can use them on a particular machine. Then you perform the following programming tasks: Import Classes (p. 3-2) How to reference the classes Creating an Instance of the Class (p. 3-3) Sample code for instantiating a class that encapsulates MATLAB code Passing Arguments to and from Java (p. 3-6) How to match up data types between MATLAB and Java Handling Errors (p.
3 Programming Import Classes To use a component generated by MATLAB Builder for Java, you must do the following: • Import MATLAB libraries with the Java import function, for example: import com.mathworks.toolbox.javabuilder.*; • Import the component classes created by Java Builder, for example: import componentname.*; or import componentname.
Creating an Instance of the Class Creating an Instance of the Class As with any Java class, you need to instantiate the classes you create with MATLAB Builder for Java before you can use them in your program. Suppose you build a component named MyComponent with a class named MyClass.
3 Programming Object[] y = null; try { cls = new myclass(); y = cls.myprimes(1, new Double((double)n)); return (double[])((MWArray)y[0]).getData(); } finally { MWArray.disposeArray(y); if (cls != null) cls.dispose(); } } } The import statements at the beginning of the program import packages that define all the classes that the program requires. These classes are defined in javabuilder.* and mycomponent.*; the latter defines the class myclass.
Creating an Instance of the Class myprimes Function The code for myprimes is as follows: function p = myprimes(n) % MYPRIMES Returns the primes between 0 and n. % P = MYPRIMES(N) Returns the primes between 0 and n. % This file is used as an example for the MATLAB % Builder for Java product. % Copyright 2001-2006 The MathWorks, Inc.
3 Programming Passing Arguments to and from Java When you invoke a method on a MATLAB Builder for Java component, the input arguments received by the method must be in the MATLAB internal array format. You can either convert them yourself within the calling program, or pass the arguments as Java data types, which are then automatically converted by the calling mechanism. To convert them yourself, use instances of the MWArray classes; in this case you are using manual conversion.
Passing Arguments to and from Java Code Fragment: Passing an MWArray. This example constructs an MWNumericArray of type MWClassID.DOUBLE. The call to myprimes passes the number of outputs, 1, and the MWNumericArray, x: x = new MWNumericArray(n, MWClassID.DOUBLE); cls = new myclass(); y = cls.myprimes(1, x); Java Builder converts the MWNumericArray object to a MATLAB scalar double to pass to the M-function.
3 Programming Here is another example: result = theFourier.plotfft(3, data, new Double(interval)); In this Java statement, the third argument is of type java.lang.Double. According to conversion rules, the java.lang.Double automatically converts to a MATLAB 1-by-1 double array. Code Fragment: Passing a Java Double Object The example calls the myprimes method with two arguments. The first specifies the number of arguments to return. The second is an object of class java.lang.
Passing Arguments to and from Java double Adata = 24; MWNumericArray A = new MWnumericArray(Adata); System.out.println("Array A is of type " + A.classID()); Java Builder converts the input argument to an instance of MWNumericArray, with a ClassID property of MWClassID.DOUBLE. This MWNumericArray object is the equivalent of a MATLAB 1-by-1 double array.
3 Programming y = sum([varargin{:}]); This function returns the sum of the inputs. The inputs are provided as a varargin argument, which means that the caller can specify any number of inputs to the function. The result is returned as a scalar double.
Passing Arguments to and from Java M-function in the order in which they appear in the array. Here is an example of how you might use the mysum method in a Java program: public double getsum(double[] vals) throws MWException { myclass cls = null; Object[] x = {vals}; Object[] y = null; try { cls = new myclass(); y = cls.mysum(1, x); return ((MWNumericArray)y[0]).getDouble(1); } finally { MWArray.disposeArray(y); if (cls != null) cls.
3 Programming Object[] y = null; try { x = new Object[vals.length]; for (int i = 0; i < vals.length; i++) x[i] = new MWNumericArray(vals[i], MWClassID.DOUBLE); cls = new myclass(); y = cls.mysum(1, x); return ((MWNumericArray)y[0]).getDouble(1); } finally { MWArray.disposeArray(x); MWArray.disposeArray(y); if (cls != null) cls.dispose(); } } This version of getsum takes an array of Object as input and converts each value to a double array.
Passing Arguments to and from Java varargout{i} = rand(1, i); end This function returns a list of random double vectors such that the length of the ith vector is equal to i.
3 Programming return ret; } finally { MWArray.disposeArray(y); if (cls != null) cls.dispose(); } } The getrandvectors method returns a two-dimensional double array with a triangular structure. The length of the ith row equals i. Such arrays are commonly referred to as jagged arrays. Jagged arrays are easily supported in Java because a Java matrix is just an array of arrays. Handling Return Values The previous examples used the fact that you knew the type and dimensionality of the output argument.
Passing Arguments to and from Java try { cls = new myclass(); y = cls.myprimes(1, new Double((double)n)); Object a = ((MWArray)y[0]).toArray(); if (a instanceof double[][]) { double[][] x = (double[][])a; /* (do something with x...) */ } else if (a instanceof float[][]) { float[][] x = (float[][])a; /* (do something with x...) */ } else if (a instanceof int[][]) { int[][] x = (int[][])a; /* (do something with x...) */ } else if (a instanceof long[][]) { long[][] x = (long[][])a; /* (do something with x...
3 Programming } else if (a instanceof byte[][]) { byte[][] x = (byte[][])a; /* (do something with x...) */ } else { throw new MWException( "Bad type returned from myprimes"); } } This example uses the toArray method (see “Methods to Copy, Convert, and Compare MWArrays” on page 4-49) to return a Java primitive array representing the underlying MATLAB array.
Passing Arguments to and from Java MWClassID clsid = ((MWArray)y[0]).classID(); if (!clsid.isNumeric() || ((MWArray)y[0]).numberOfDimensions() != 2) { throw new MWException("Bad type returned from myprimes"); } if (clsid == MWClassID.DOUBLE) { double[][] x = (double[][])((MWArray)y[0]).toArray(); /* (do something with x...) */ } else if (clsid == MWClassID.SINGLE) { float[][] x = (float[][])((MWArray)y[0]).toArray(); /* (do something with x...) */ } else if (clsid == MWClassID.INT32 || clsid == MWClassID.
3 Programming { short[][] x = (short[][])((MWArray)y[0]).toArray(); /* (do something with x...) */ } else if (clsid == MWClassID.INT8 || clsid == MWClassID.UINT8) { byte[][] x = (byte[][])((MWArray)y[0]).toArray(); /* (do something with x...) */ } } finally { MWArray.disposeArray(y); if (cls != null) cls.
Handling Errors Handling Errors Errors that occur during execution of an M-function or during data conversion are signaled by a standard Java exception. This includes MATLAB run-time errors as well as errors in your M-code. In general, there are two types of exceptions in Java: checked exceptions and unchecked exceptions. Handling Checked Exceptions Checked exceptions must be declared as thrown by a method using the Java language throws clause. Java Builder components support one checked exception: com.
3 Programming public Object[] myprimes(int nargout, Object n) throws MWException { (implementation omitted) } Any method that calls myprimes must do one of two things: • Catch and handle the MWException. • Allow the calling program to catch it. The following two sections provide examples of each. Code Fragment: Handling an Exception in the Called Function The getprimes example shown here uses the first of these methods.
Handling Errors if (cls != null) cls.dispose(); } } Note that in this case, it is the programmer’s responsibility to return something reasonable from the method in case of an error. The finally clause in the example contains code that executes after all other processing in the try block is executed. This code executes whether or not an exception occurs or a control flow statement like return or break is executed.
3 Programming cls.dispose(); } } Handling Unchecked Exceptions Several types of unchecked exceptions can also occur during the course of execution. Unchecked exceptions are Java exceptions that do not need to be explicitly declared with a throws clause. The MWArray API classes all throw unchecked exceptions. All unchecked exceptions thrown by MWArray and its subclasses are subclasses of java.lang.RuntimeException. The following exceptions can be thrown by MWArray: • java.lang.RuntimeException • java.
Handling Errors y = cls.myprimes(1, new Double((double)n)); return (double[])((MWArray)y[0]).getData(); } /* Catches the exception thrown by anyone */ catch (Exception e) { System.out.println("Exception: " + e.toString()); return new double[0]; } finally { MWArray.disposeArray(y); if (cls != null) cls.
3 Programming System.out.println("Exception in MATLAB call: " + e.toString()); return new double[0]; } /* Catches all other exceptions */ catch (Exception e) { System.out.println("Exception: " + e.toString()); return new double[0]; } finally { MWArray.disposeArray(y); if (cls != null) cls.dispose(); } } The order of the catch clauses here is important. Because MWException is a subclass of Exception, the catch clause for MWException must occur before the catch clause for Exception.
Managing Native Resources Managing Native Resources When your code accesses Java classes created by MATLAB Builder for Java, your program uses native resources, which exist outside the control of the Java Virtual Machine (JVM). Specifically, each MWArray data conversion class is a wrapper class that encapsulates a MATLAB mxArray. The encapsulated MATLAB array allocates resources from the native memory heap.
3 Programming heap, MWArray objects should be explicitly freed as soon as possible by the application that creates them. Using the dispose Method The best technique for freeing resources for classes created by MATLAB Builder for Java is to call the dispose method explicitly. Any Java object, including an MWArray object, has a dispose method. The MWArray classes also have a finalize method, called a finalizer, that calls dispose.
Managing Native Resources The MWArray class provides two disposal methods: dispose and disposeArray. The disposeArray method is more general in that it disposes of either a single MWArray or an array of arrays of type MWArray. Code Fragment: Use try-finally to Ensure Resources Are Freed Typically, the best way to call the dispose method is from a finally clause in a try-finally block.
3 Programming Handling Data Conversion Between Java and MATLAB The call signature for a method that encapsulates a MATLAB function uses one of the MATLAB data conversion classes to pass arguments and return output. When you call any such method, all input arguments not derived from one of the MWArray classes are converted by Java Builder to the correct MWArray type before being passed to the MATLAB method. For example, consider the following Java statement: result = theFourier.
Handling Data Conversion Between Java and MATLAB MWNumericArray A = new MWnumericArray(Adata, MWClassID.INT16); System.out.println("Array A is of type " + A.
3 3-30 Programming
4 Using MWArray Classes The following topics explain how to use the data conversion classes in the com.mathworks.toolbox.javabuilder.MWArray package. Guidelines for Working with MWArray Classes (p. 4-2) How to use the MWArray API to handle various kinds of data Using Class Methods (p.
4 Using MWArray Classes Guidelines for Working with MWArray Classes Overview of the MWArray API The MWArray Java API is a class hierarchy that represents the major MATLAB array types. The root class is MWArray, which has the following subclasses: • MWNumericArray • MWLogicalArray • MWCharArray • MWCellArray • MWStructArray These subclasses provide constructors and factory methods for creating new MATLAB arrays from standard Java types and objects.
Guidelines for Working with MWArray Classes Method Overrides Implemented by MWArray To ensure integration with Java programs, MWArray provides overrides for java.lang.Object methods and implements the required Java interfaces as needed. The following table provides more information about the overrides. Overrides Method in MWArray Base Class Override Description equals Overrides Object.equals to provide a logical equality test for two MWArrays.
4 Using MWArray Classes Java Interfaces Implemented by MWArray Interface Cloneable Method in MWArray Base Class Description of Method clone Produces a new MWArray object that contains a deep copy of the underlying MATLAB array. (public method) Comparable compareTo (public method) Serializable writeObject readObject (private methods) Allows comparisons of MWArrays for order. Internally, this method does a byte-wise comparison of the native buffer.
Guidelines for Working with MWArray Classes Method Usage columnIndex() Returns the column index (second dimension) of each element in the array. Call this method to get an array of column indices for the nonzero elements of a sparse array. dispose() Frees the native resources associated with the underlying MATLAB array. disposeArray(Object) Calls dispose on all MWArray instances contained in the input. get(int) Returns the elements at the specified one-based offset.
4 4-6 Using MWArray Classes Method Usage maximumNonZeros() Returns the current allocated capacity of nonzero elements for a sparse array. numberOfDimensions() Returns the number of dimensions in the array. numberOfElements() Returns the number of elements in the array. numberOfNonZeros() Returns the current number of nonzero elements for a sparse array. rowIndex() Returns the row index (first dimension) of each element in the array.
Guidelines for Working with MWArray Classes Method Usage sharedCopy() Creates a new MWArray instance that represents a shared copy of the underlying MATLAB array. A shared copy points to the same underlying MATLAB array as the original. Changing the data in a shared copy also changes the original array. toArray() Returns an array containing a copy of the data in the underlying MATLAB array as an array of Java types. The returned array has the same dimensionality as the underlying MATLAB array.
4 Using MWArray Classes Constructor Usage MWNumericArray() Empty double array MWNumericArray (MWClassID) Empty array of type specified by MWClassID 4-8 MWNumericArray(type, MWClassID) Real array of type specified by MWClassID MWNumericArray(type) Real array with type determined from default conversion rules MWNumericArray(type, type, MWClassID) Complex array of type specified by MWNumericArray(type, type) Complex array with type determined from default conversion rules MWClassID
Guidelines for Working with MWArray Classes Supported Data Types. In the previous table, type represents supported Java types. MWNumericArray supports the following Java primitive types: • double • float • byte • short • int • long • boolean The following object types are also supported: • Subclasses of java.lang.Number • Subclasses of java.lang.String • Subclasses of java.lang.Boolean In addition to supporting scalar values of the types listed, general N-dimensional arrays of each type are also supported.
4 Using MWArray Classes New Integer(2), MWClassID.INT32); MWNumericArray a4 = new MWNumericArray("1.0", "2.0", MWClassID.INT32); Constructing Matrices The next group of statements constructs a 2-by-2 double matrix with the following values: [1 2 3 4] double[][] x1 = {{1.0, 2.0}, {3.0, 4.0}}; int[][] x2 = {{1, 2}, {3, 4}}; Double[][] x3 = {{new Double(1.0), new Double(2.0)}, {new Double(3.0), new Double(4.0)}}; String[][] x4 = {{"1.0", "2.0'}, {"3.0", "4.
Guidelines for Working with MWArray Classes Constructing Jagged Arrays The previous examples constructed rectangular Java arrays and used these arrays to initialize MATLAB arrays. Multidimensional arrays in Java are implemented as arrays of arrays, which means that it is possible to construct a Java array in which each row can have a different number of columns. Such arrays are commonly referred to as jagged arrays.
4 Using MWArray Classes MWNumericArray a1 = new MWNumericArray a2 = new MWNumericArray a3 = new MWClassID.DOUBLE); MWNumericArray a4 = new MWNumericArray(1.0); MWNumericArray(1, MWClassID.DOUBLE); MWNumericArray(new Double(1.0), MWNumericArray("1.0", MWClassID.DOUBLE); In general, it is most efficient to supply an argument that causes the desired array to be created using the default conversion rules. Some types require coercion to produce the correct MATLAB array.
Guidelines for Working with MWArray Classes Factory Method Usage newInstance(int[], Object, MWClassID) Real numeric array of specified type. Values are initialized with supplied arrays. newInstance(int[], Object, Object, MWClassID) Complex numeric array of specified type. Values are initialized with supplied arrays. newSparse(int[], int[], Object, int, int, int, MWClassID) Real sparse numeric matrix of specified type, dimensions, and maximum nonzeros.
4 Using MWArray Classes Factory Method Usage newSparse(int[], int[], Object, Object, MWClassID) Complex sparse numeric matrix of specified type. Values are initialized with supplied row, column, and data arrays. Maximum nonzeros and dimensions are computed from input data. newSparse(int, int, int, MWClassID, MWComplexity) Sparse numeric matrix with specified type, complexity, dimensions, and maximum nonzeros. Values are initialized to 0.
Guidelines for Working with MWArray Classes MWNumericArray.newInstance(dims, MWNumericArray a2 = MWNumericArray.newInstance(dims, MWNumericArray a3 = MWNumericArray.newInstance(dims, MWNumericArray a4 = MWNumericArray.newInstance(dims, x1, MWClassID.DOUBLE); x2, MWClassID.DOUBLE); x3, MWClassID.DOUBLE); x4, MWClassID.DOUBLE); Similarly, the 2-by-2 matrix example can be rewritten as follows: double[] x1 = {1.0, 3.0, 2.0, 4.0}; int[] x2 = {1, 3, 2, 4}; Double[] x3 = {new Double(1.0), new Double(3.
4 Using MWArray Classes 0 0 -1 2 ] Calling newSparse. The call to newSparse passes three arrays: an array of matrix data (x), an array containing the row indices of x (rowindex), and an array of column indices of x (colindex). The number of rows (4) and columns (4) are also passed, as well as the type (MWClassID.DOUBLE): double[] x = { 2.0, -1.0, -1.0, 2.0, -1.0, -1.0, 2.0, -1.0, -1.0, 2.
Guidelines for Working with MWArray Classes Note Numeric sparse matrices are supported only for type double. Attempting to construct a sparse numeric matrix with any other type results in an exception being thrown. Accessing MWNumericArray Elements The MWNumericArray class provides methods for accessing and modifying array data in the form of get and set methods. The following table lists the get and set methods. Method Usage gettype(int) Returns the real part of the element at the one-based index.
4 Using MWArray Classes Method Usage setImag(int, type) Replaces the imaginary part of the element at the one-based index with the supplied value setImag(int[], type) Replaces the imaginary part of the element at the one-based index array with the supplied value In these method calls, type represents one of the following supported Java types of MWNumericArray: • double • float • byte • short • int • long • Boolean • Subclass of java.lang.Number • Subclass of java.lang.String • Subclass of java.lang.
Guidelines for Working with MWArray Classes Examples of Using set. The following examples construct the 2-by-2 matrix of the previous example using the set method. The first example uses a single index: int[] dims = {2, 2}; MWNumericArray a = MWNumericArray.newInstance(dims, MWClassID.DOUBLE, MWComplexity.REAL); int index = 0; double[] values = {1.0, 3.0, 2.0, 4.0}; for (int index = 1; index <= 4; index++) a.
4 Using MWArray Classes a.set(index, 2.0); else if (index[1] == index[0]+1 || index[1] == index[0]-1) a.set(index, -1.0); } } The example allocates the 4-by-4 sparse matrix with a capacity of 10 nonzero elements. Initially, the array has no nonzero elements. The for loops set the array’s values using an index array. Sparse arrays allocate storage only for the nonzero elements that are assigned.
Guidelines for Working with MWArray Classes System.out.print("] = " + a.getDouble(dims)); if (a.complexity() == MWComplexity.COMPLEX) System.out.print(" + "+a.getImagDouble(dims)+"i"); System.out.print("\n"); } } The next example sums the real parts of all the elements in a numeric array and returns the result as a double value: public double sumElements(MWNumericArray a) { double sum = 0.0; int n = a.numberOfElements(); for (int i = 1; i <= n; i++) sum = sum + a.
4 Using MWArray Classes for (index[0] = 1; index[0] <= dims[0]; index[0]++) sum += row[index[0]-1]*b.getDouble(index); result[i][index[0]] = sum; } } return result; } Working with Logical Arrays The MWLogicalArray class provides a Java interface to a MATLAB logical array. MWLogicalArrays can be dense or sparse. Constructing an MWLogicalArray The MWLogicalArray class provides a set of constructors and factory methods for creating logical arrays. The following table lists the supplied constructors.
Guidelines for Working with MWArray Classes These examples construct a scalar logical array initialized to false: MWLogicalArray MWLogicalArray MWLogicalArray MWLogicalArray a1 a2 a3 a4 = = = = new new new new MWLogicalArray(false); MWLogicalArray(0); MWLogicalArray("false"); MWLogicalArray(new Boolean(false)); As with MWNumericArray, MWLogicalArrays can be constructed with multidimensional Java arrays.
4 Using MWArray Classes Factory Method Usage newInstance(int[], Object) New logical array. Values are initialized with supported data. newSparse(int[], int[], Object, int, int, int) Sparse logical matrix of specified dimensions and maximum nonzeros. Values are initialized with supplied row, column, and data arrays. newSparse(int[], int[], Object, int, int) Sparse logical matrix of specified dimensions. Values are initialized with supplied row, column, and data arrays.
Guidelines for Working with MWArray Classes MWLogicalArray MWLogicalArray MWLogicalArray MWLogicalArray a1 a2 a3 a4 = = = = MWLogicalArray.newInstance(dims, MWLogicalArray.newInstance(dims, MWLogicalArray.newInstance(dims, MWLogicalArray.newInstance(dims, x1); x2); x3); x4); Accessing MWLogicalArray Elements The MWLogicalArray class provides methods for accessing and modifying array data in the form of get and set methods. The following table lists the get and set methods.
4 Using MWArray Classes double, float, byte, short, int, long, java.lang.Boolean, subclasses of java.lang.Number, and java.lang.String. Examples of Using set and get Methods. This example constructs a random sparse logical matrix with a specified fraction of nonzero elements: MWLogicalArray getRandomSparse(int m, int n, double fillFactor) { if (m < 0 || n < 0) throw new IllegalArgumentException( "Dimensions must be positive"); if (fillFactor < 0.0 || fillFactor > 1.
Guidelines for Working with MWArray Classes Constructing an MWCharArray The MWCharArray class provides a set of constructors and factory methods for creating logical arrays. The following table lists the supplied constructors. Constructor Usage MWCharArray() Empty char array MWCharArray(type) char array with values initialized with supplied data Here, type represents supported Java types. MWCharArray supports the following Java types: char, java.lang.Character, and java.lang.String.
4 Using MWArray Classes Constructing an N-Dimensional Character Array. You can create a multidimensional char array using a multidimensional array of either char or java.lang.Character, or by using an array of java.lang.
Guidelines for Working with MWArray Classes The a1, a2, and a3 arrays constructed all contain a 2-by-14 MATLAB char array. The column count of the array is equal to the largest string length in the input array. Rows with fewer characters than the maximum are Null padded. Arrays with larger numbers of dimensions are handled similarly. This behavior parallels the way that MWNumericArray and MWLogicalArray handle jagged arrays.
4 Using MWArray Classes new Character('g') }; int[] dims = {1, MWCharArray a1 = MWCharArray a2 = MWCharArray a3 = 8}; MWCharArray.newInstance(dims, x1); MWCharArray.newInstance(dims, x2); MWCharArray.newInstance(dims, x3); Constructing a Two-Dimensional Character Array.
Guidelines for Working with MWArray Classes Method Usage set(int, Object) Replaces the element at the one-based index with the supplied value (inherited from MWArray). set(int[], Object) Replaces the element at the one-based index array with the supplied value (inherited from MWArray). set(int, char) Replaces the element at the one-based index with the supplied char value. set(int[], char) Replaces element at the one-based index array with the supplied char value. The get methods return a java.
4 Using MWArray Classes Using MWCellArray Constructors The MWCellArray class provides the following constructors: Constructor Usage MWCellArray() Empty cell array. MWCellArray(int[]) New cell array with specified dimensions. All cells are initialized to empty. MWCellArray(gint, int) New cell matrix with specified number of rows and columns. Constructing a cell array is a two-step process.
Guidelines for Working with MWArray Classes Here, each cell is initialized with a Java array, and default conversion rules are used to create the MATLAB array for each cell. Constructing an MWCellArray Containing Complex Arrays. The next example creates a helper function that constructs a cell array containing a list of complex double arrays. The real and imaginary parts of each cell are passed in the re and im arrays, respectively.
4 Using MWArray Classes if (x != null) x.dispose(); throw new MWException(e.getMessage()); } } This method creates a new MWCellArray of the necessary size. Next, the code loops over the number of elements in the supplied arrays. For each loop iteration, a temporary MWNumericArray, x, is created for the current cell and initialized with the contents of re[k-1] and im[k-1] (the loop variable, k, is one-based).
Guidelines for Working with MWArray Classes Method Usage set(int, Object) Replaces the element at the one-based index with the supplied value (inherited from MWArray). set(int[], Object) Replaces the element at the one-based index array with the supplied value (inherited from MWArray). The set methods replace the cell at the specified index with the supplied value. The cell value can be passed as any supported Java type or as an MWArray instance.
4 Using MWArray Classes } } finally { if (c != null) c.dispose(); } } This method loops through the array and prints the type of each cell. The temporary array returned by getCell is disposed of after it is used. The finally clause ensures that the array is disposed of before exiting, in the case of an exception. MWCellArray also overrides the MWArray.get methods. In this case, a Java array is returned that represents a conversion of the underlying cell, as would be returned by toArray. Using get.
Guidelines for Working with MWArray Classes index[1] = 2; double[][] x12 = (double[][])a.get(index); index[0] = 2; boolean[][] x22 = (boolean[][])a.get(index); index[1] = 1; int[][] x21 = (int[][])a.get(index); As with set, default conversion rules are applied (same rules as apply to toArray). In this example, the default rules are fine. In the case where complex arrays, other cell arrays, or struct arrays are stored in the cell array, it is recommended to use getCell to return an MWArray instance.
4 Using MWArray Classes Using Class Methods Use MWArray classes to construct data types as needed in your Java code.
Using Class Methods Example. Construct an empty MWArray object: MWArray A = new MWArray(); Methods to Create and Destroy an MWArray Use these methods to destroy an object of class MWArray or any of its child classes. Method Description “dispose” on page 4-39 Frees the native MATLAB array contained by this array. “disposeArray” Frees all native MATLAB arrays contained in the input on page 4-40 object. dispose.
4 Using MWArray Classes disposeArray. This method destroys any native MATLAB arrays contained in the input object and frees the memory occupied by them. This is a static method of the class and thus does not need to be invoked in reference to an instance of the class.
Using Class Methods Method Description “classID” on page 4-41 Returns the MATLAB type of the array. “getDimensions” on page 4-42 Returns the size of each dimension of the array. “isEmpty” on page 4-42 Tests if the array has no elements. “numberOfDimensions” on page 4-43 Returns the number of dimensions of the array. “numberOfElements” on page 4-43 Returns the total number of elements in the array.
4 Using MWArray Classes When run, the example displays this output: Class of A is int32 getDimensions. This method returns a one-dimensional int array containing the size of each dimension of the MWArray object. The prototype for the getDimensions method is as follows: public int[] getDimensions() Input Parameters None Example — Getting Array Dimensions of an MWArray int[] dimA = A.getDimensions(); System.out.
Using Class Methods Example — Testing for an Empty MWArray Display a message if array object A is an empty array. Otherwise, display the contents of A: if (A.isEmpty()) System.out.println("Matrix A is empty"); else System.out.println("A = " + A.toString()); When run, the example displays the contents of A: A = 1 7 13 2 8 14 3 9 15 4 10 16 5 11 17 6 12 18 numberOfDimensions. This method returns the number of dimensions of the array object.
4 Using MWArray Classes The prototype for the numberOfElements method is as follows: public int numberOfElements() Input Parameters None Example — Getting the Number of MWArray Elements Display the number of elements in array object A: System.out.println("Matrix A has " + A.
Using Class Methods get. This method returns the element located at the specified one-based offset or index array in the array object. The element is returned as an Object. To get the element at a specific index, use one of the following: public Object get(int index) public Object get(int[] index) Use the first syntax (int index) to return the element at the specified one-based offset in the array, accessing elements in column-wise order.
4 Using MWArray Classes Example — Getting an MWArray Value with get Retrieve element (2, 4) from array object A: int[] index = {2, 4}; Object d_out = A.get(index); System.out.println("Data read from A(2,4) is " + d_out.toString()); When run, the example displays this output: Data read from A(2,4) is 10 getData. This method returns all elements of the MWArray object. Elements are returned in a one-dimensional array, in column-wise order. Elements are returned as type Object.
Using Class Methods System.out.println(); When run, the example displays this output: Data read from matrix A is: 1 7 13 2 8 14 3 9 15 4 10 16 5 11 17 6 12 18 set. This method replaces the element at a specified index in the MWArray object with the input element.
4 Using MWArray Classes Exceptions The set method throws the following exception: IndexOutOfBoundsException The specified index parameter is invalid. Example — Setting an MWArray Value Modify the data in element (2, 4) of MWArray object A: int[] index = {2, 4}; A.set(index, 555); Object d_out = A.get(index); System.out.println("Data read from A(2,4) is " + d_out.toString()); When run, the example displays this output: Data read from A(2,4) is 555 toArray.
Using Class Methods Example — Getting an MWArray with toArray Create and display a copy of MWArray object A: int[][] x = (int[][]) A.toArray(); int[] dimA = A.getDimensions(); System.out.println("Matrix A is:"); for (int i = 0; i < dimA[0]; i++) { for (int j = 0; j < dimA[1]; j++) System.out.print(" " + x[i][j]); System.out.
4 Using MWArray Classes Method Description “sharedCopy” on page 4-53 Creates and returns a shared copy of this array. “toString” on page 4-54 Returns a string representation of the array. clone. This method creates and returns a deep copy of the MWArray object. Because clone allocates a new array, any changes made to this new array are not reflected in the original.
Using Class Methods When run, the example displays this output: Clone of matrix A is: 1 2 3 4 7 8 9 10 13 14 15 16 5 11 17 6 12 18 compareTo. This method compares the MWArray object with the input object. It returns a negative integer, zero, or a positive integer if the MWArray object is less than, equal to, or greater than the specified object, respectively. The prototype for the compareTo method is as follows: public int compareTo(Object obj) See the compareTo method in interface java.lang.
4 Using MWArray Classes equals. This method indicates the MWArray object is equal to the input object. The equals method of the MWArray class overrides the equals method of class Object. The prototype for the equals method is as follows: public boolean equals(Object object) Input Parameters object Array to compare this MWArray object to Example — Comparing MWArrays with equals Create a shared copy of the MWArray object and then compare it to the original object.
Using Class Methods Example — Getting an MWArray Hash Code Obtain the hash code for MWArray object A: System.out.println("Hash code for matrix A is " + A.hashCode()); When run, the example displays this output: Hash code for matrix A is 456687478 sharedCopy. This method creates and returns a shared copy of the array. The shared copy points to the underlying original MATLAB array. Any changes made to the copy are reflected in the original.
4 Using MWArray Classes toString. This method returns a string representation of the array. The toString method of the MWArray class overrides the toString method of class Object. The prototype for the toString method is as follows: public java.lang.String toString() Input Parameters None Example — Converting an MWArray to a String Display the contents of MWArray object A: System.out.println("A = " + A.
Using Class Methods Method Description “maximumNonZeros” on page 4-57 Returns the allocated capacity of a sparse array. If the underlying array is nonsparse, this method returns the same value as numberOfElements(). “numberOfNonZeros” on page 4-58 Returns the number of nonzero elements in a sparse array. If the underlying array is nonsparse, this method returns the same value as numberOfElements().
4 Using MWArray Classes Input Parameters None Example — Testing an MWArray for Sparseness Test the MWArray object A created previously for sparseness: if (A.isSparse()) System.out.println("Matrix A is sparse"); When run, the example displays this output: Matrix A is sparse columnIndex. This method returns an array containing the column index of each element in the underlying MATLAB array.
Using Class Methods rowIndex. This method returns an array containing the row index of each element in the underlying MATLAB array. The prototype for the rowIndex method is as follows: public int[] rowIndex() Input Parameters None Example — Getting the Row Indices of a Sparse MWArray Get the row indices of the elements of the sparse array: System.out.print("Row indices are: "); int[] rowidx = A.rowIndex(); for (int i = 0; i < 5; i++) System.out.print(rowidx[i] + " "); System.out.
4 Using MWArray Classes Example — Getting the Maximum Number of Nonzeros in an MWArray Display the maximum number of nonzeros for this array: System.out.println("Maximum number of nonzeros for matrix A is " + A.maximumNonZeros()); When run, the example displays this output: Maximum number of nonzeros for matrix A is 10 numberOfNonZeros. This method returns the number of nonzero elements in a sparse array. If the underlying array is nonsparse, this method returns the same value as numberOfElements.
Using Class Methods • “Methods to Create and Destroy an MWNumericArray” on page 4-63 • “Methods to Get and Set the Real Parts of an MWNumericArray” on page 4-75 • “Methods to Get and Set the Imaginary Parts of an MWNumericArray” on page 4-79 • “Methods to Copy, Convert, and Compare MWNumericArrays” on page 4-87 • “Methods to Use on Sparse MWNumericArrays” on page 4-90 • “Methods to Return Special Constant Values” on page 4-90 Constructing an MWNumericArray Use the tables in this section to construct an MW
4 Using MWArray Classes Example — Constructing an Empty Numeric Array Object Create an empty scalar of type int64: MWNumericArray A = new MWNumericArray(MWClassID.INT64); System.out.println("A = " + A); When you run this example, the results are as follows: A = [] Constructing a Real or Complex Numeric Scalar.
Using Class Methods A nonnumeric array type was specified. Example — Constructing an Integer Array Object Construct a scalar numeric array of type MWClassID.INT16: double AReal = 24; MWNumericArray A = new MWNumericArray(AReal, MWClassID.INT16); System.out.println("Array A of type " + A.
4 Using MWArray Classes MWClassID classid) The type javatype can be any of the following: • double • float • long • int • short • byte • boolean • Object Example — Constructing a Real Array of a Specific Type Construct a 3-by-6 real array of type MWClassID.SINGLE: double[][] AData = {{ 1, 2, 3, 4, 5, 6}, { 7, 8 , 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; MWNumericArray A = new MWNumericArray(AData, MWClassID.SINGLE); System.out.
Using Class Methods MWNumericArray A = new MWNumericArray(AReal, AImag, MWClassID.DOUBLE); System.out.println("Array A of type " + A.classID() + " = \n" + A); When run, the example displays this output: Array A of type double = 1.0e+002 * 0.2420 + 0.0500i -0.0700 + 0.3100i 1.1300 + 0.2700i Methods to Create and Destroy an MWNumericArray In addition to the MWNumericArray constructor, you can use the newInstance and newSparse methods to construct a numeric array.
4 Using MWArray Classes To construct an uninitialized real or complex numeric array, use the following: newInstance(int[] dims, MWClassID classid, MWComplexity cmplx) To construct and initialize a real numeric array, use newInstance(int[] dims, Object rData, MWClassID classid) To construct and initialize a complex numeric array, use newInstance(int[] dims, Object rData, Object iData, MWClassID classid) Input Parameters dims Array of nonnegative dimension sizes classId MWClassID representing the MATLAB
Using Class Methods • short[] • byte[] • boolean[] • One-dimensional arrays of any subclass of java.lang.Number • One-dimensional arrays of java.lang.Boolean Exceptions The newInstance method throws the following exceptions: NegativeArraySizeException The specified dims parameter is negative. ArrayStoreException The array type is nonnumeric. Example — Constructing a Numeric Array Object with newInstance Construct a 3-by-6 real numeric array using the newInstance method.
4 Using MWArray Classes When run, the example displays this output: A = 1 7 13 2 8 14 3 9 15 4 10 16 5 11 17 6 12 18 newSparse. This method constructs a real or complex sparse MWNumericArray, with the specified number of rows and columns and maximum nonzero elements, and initializes the array with the supplied data. This is a static method of the class and thus does not need to be invoked in reference to an instance of the class.
Using Class Methods newSparse(int[] rowindex, int[] colindex, Object realData, int rows, int cols, int nzmax, MWClassID classid) Constructing a Sparse Matrix of Complex Numbers To construct a complex sparse array from an existing nonsparse two-dimensional array, use newSparse(Object realData, Object imagData, MWClassID classid) To construct and initialize a new complex sparse array, use newSparse(int[] rowindex, int[] colindex, Object realData, Object imagData, MWClassID classid) To construct and initia
4 Using MWArray Classes Row and column index arrays are used to construct the sparse array such that the following holds true, with space allocated for nzmax nonzeros: S(rowIndex(k), columnIndex(k)) = realData(k) + imagData(k)*i If you assign multiple values to a single rowIndex and colIndex pair, then the element at that index is assigned the sum of these values.
Using Class Methods Exceptions The newSparse method throws the following exceptions: NegativeArraySizeException Row or column size is negative. IndexOutOfBoundsException The specified index parameter is invalid.
4 Using MWArray Classes (1,4) (2,5) 16.0000 +41.0000i 0 + 2.0000i Example — Using newSparse with Row and Column Indices Construct a sparse MWNumericArray from vector Adata: double[] Adata = { 0, 10, 0, 0, 40, 50, 60, 0, 0, 90}; int[] ri = {1, 1, 1, 1, 1, 2, 2, 2, 2, 2}; int[] ci = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5}; MWNumericArray A = MWNumericArray.newSparse(ri, ci, Adata, MWClassID.DOUBLE); System.out.println("A = " + A.
Using Class Methods System.out.println("A = " + A.toString()); When run, the example displays this output: (2,1) (2,2) (1,5) (2,5) 50 60 40 250 dispose. MWNumericArray inherits this method from the MWArray class. disposeArray. MWNumericArray inherits this method from the MWArray class. Methods to Return Information About an MWNumericArray Use these methods to return information about an object of class MWNumericArray. Method Description “classID” on page 4-72 Returns the MATLAB type of this array.
4 Using MWArray Classes classID. MWNumericArray inherits this method from the MWArray class. complexity. This method returns the complexity of the MWNumericArray object as either MWComplexity.REAL for a real array, or MWComplexity.COMPLEX for a complex array.
Using Class Methods Input Parameters value double value to test for finiteness Example — Testing for Finite Array Values Test x for finiteness: double x = 25; if (MWNumericArray.isFinite(x)) System.out.println("The input value is finite"); When run, the example displays this output: The input value is finite isInf. This method tests for infinity in a machine-independent manner. This is a static method of the class and does not need to be invoked in reference to an instance of the class.
4 Using MWArray Classes Test x for infinity: double x = 1.0 / 0.0; if (MWNumericArray.isInf(x)) System.out.println("The input value is infinite"); When run, the example displays this output: The input value is infinite isNaN. This method tests for NaN (Not a Number) in a machine-independent manner. This is a static method of the class and does not need to be invoked in reference to an instance of the class.
Using Class Methods numberOfDimensions. MWNumericArray inherits this method from the MWArray class. numberOfElements. MWNumericArray inherits this method from the MWArray class. Methods to Get and Set the Real Parts of an MWNumericArray Use these methods to get and set real values in an object of class MWNumericArray. Method Description “get” on page 4-76 Returns the element at the specified offset as an Object.
4 Using MWArray Classes The following syntax applies to all the above methods except getData and toArray. Calling Syntax.
Using Class Methods Use either of the following prototypes for the getDouble method, where index can be of type int or int[]: public double getDouble(int index) public double getDouble(int[] index) getFloat. This method returns the real part of the MWNumericArray element located at the specified one-based index or index array. The return value is given type float.
4 Using MWArray Classes Use either of the following prototypes for the getShort method, where index can be of type int or int[]: public short getShort(int index) public short getShort(int[] index) getByte. This method returns the real part of the MWNumericArray element located at the specified one-based index or index array. The return value is given type byte.
Using Class Methods System.out.println("Setting A(2, 3) to a new value ..."); A.set(idx, 555); System.out.println(""); System.out.println("A(2, 3) is now " + A.get(idx).toString()); When run, the example displays this output: A(2, 3) is 9.0 Setting A(2, 3) to a new value ... A(2, 3) is now 555.0 set. MWNumericArray inherits the following methods from the MWArray class.
4 Using MWArray Classes Method Description “getImagFloat” on page 4-84 Returns the imaginary part at the specified offset as a float value. “getImagLong” on page 4-84 Returns the imaginary part at the specified offset as a long value. “getImagInt” on page 4-84 Returns the imaginary part at the specified offset as an int value. “getImagShort” on page 4-84 Returns the imaginary part at the specified offset as a short value.
Using Class Methods In the case where index is of type int, the valid range for index is 1 <= index <= N, where N is the total number of elements in the array. In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWNumericArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension. Exceptions.
4 Using MWArray Classes System.out.println(A.toString()); Here is the complex array that is displayed: 2.0000 + 6.0000i 8.0000 + 7.0000i 14.0000 + 1.0000i 3.0000 + 5.0000i 9.0000 + 1.0000i 15.0000 + 1.0000i 4.0000 + 14.0000i 10.0000 + 23.0000i 16.0000 + 9.0000i Now, use get and getImag to read the real and imaginary parts of the element at index (2, 3): int[] index = {2, 3}; System.out.println("The real part of A(2,3) = " + A.get(index)); System.out.println("The imaginary part of A(2,3) = " + A.
Using Class Methods System.out.println("The real data in matrix A is:"); x = (double[]) A.getData(); for (int i = 0; i < x.length; i++) System.out.print(" " + x[i]); System.out.println(); System.out.println(); System.out.println("The imaginary data in matrix A is:"); x = (double[]) A.getImagData(); for (int i = 0; i < x.length; i++) System.out.print(" " + x[i]); System.out.println(); When run, the example displays this output: The real data in matrix A is: 2.0 8.0 14.0 3.0 9.0 15.0 4.0 10.0 16.
4 Using MWArray Classes System.out.println("The imaginary part of A(2,3) = " + A.getImagDouble(index)); When run, the example displays this output: The real part of A(2,3) = 10.0 The imaginary part of A(2,3) = 23.0 getImagFloat. This method returns the imaginary part of the MWNumericArray element located at the specified one-based index or index array. The return value is given type float.
Using Class Methods Use either of the following prototypes for the getImagShort method, where index can be of type int or int[]: public short getImagShort(int index) public short getImagShort(int[] index) getImagByte. This method returns the imaginary part of the MWNumericArray element located at the specified one-based index or index array. The return value is given type byte.
4 Using MWArray Classes Exceptions These methods throw the following exception: IndexOutOfBoundsException The specified index parameter is invalid. toImagArray. This method returns an array containing a copy of the imaginary data in the underlying MATLAB array. The prototype for the toImagArray method is public Object toImagArray() The array that is returned has the same dimensionality as the MATLAB array. The elements of this array are converted according to default conversion rules.
Using Class Methods When run, the example displays this output: The imaginary part of matrix A is: 6.0 5.0 14.0 7.0 1.0 23.0 1.0 1.0 9.0 Methods to Copy, Convert, and Compare MWNumericArrays Use these methods to copy, convert, and compare objects of class MWNumericArray. Method Description “clone” on page 4-87 Creates and returns a deep copy of this array. “compareTo” on page 4-88 Compares this array with the specified array for order.
4 Using MWArray Classes Input Parameters None Exceptions The clone method throws the following exception: java.lang.CloneNotSupportedException The object’s class does not implement the Cloneable interface. Example — Cloning a Numeric Array Object Create a 3-by-6 array of type double: double[][] AData = {{ 1, 2, 3, 4, 5, 6}, { 7, 8 , 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; MWNumericArray A = new MWNumericArray(AData, MWClassID.DOUBLE); Create a clone of the MWNumericArray object A: Object C = A.
Using Class Methods equals. MWNumericArray inherits this method from the MWArray class. hashcode. MWNumericArray inherits this method from the MWArray class. sharedCopy. This method creates and returns a shared copy of the MWNumericArray object. The shared copy points to the underlying original MATLAB array. Any changes made to the copy are reflected in the original. The sharedCopy method of MWNumericArray overrides the sharedCopy method of class MWArray.
4 Using MWArray Classes Methods to Use on Sparse MWNumericArrays Use these methods to return information on sparse arrays of type MWNumericArray. All are inherited from class MWArray. Operations on sparse arrays of type MWNumericArray are currently supported only for the double type. Method Description “newSparse” on page 4-66 Constructs a real sparse numeric matrix with the specified number of rows and columns and maximum nonzero elements, and initializes the array with the supplied data.
Using Class Methods Method Description “getEps” on page 4-91 Get the value represented by EPS (floating-point relative accuracy) in MATLAB. “getInf” on page 4-91 Get the value represented by INF (infinity) in MATLAB. “getNaN” on page 4-92 Get the value represented by NaN (Not a Number) in MATLAB. getEps. This method returns the MATLAB concept of EPS, which stands for the floating-point relative accuracy.
4 Using MWArray Classes Exceptions None getNaN. This method returns the MATLAB concept of NaN, which stands for "Not a Number".
Using Class Methods MWLogicalArray() Constructing an Initialized Logical Scalar or Array. Use this constructor syntax to create a MWLogicalArray scalar or array that represents the primitive Java type javatype: MWLogicalArray(javatype array) The value of array is set to true if the argument is nonzero, and false otherwise.
4 Using MWArray Classes Method Description “newInstance” on page 4-94 Constructs a logical array with the specified dimensions. “newSparse” on page 4-95 Constructs a sparse logical matrix from the supplied full matrix. “dispose” on page 4-98 Frees the native MATLAB array contained by this array. “disposeArray” on page 4-98 Frees all native MATLAB arrays contained in the input object. newInstance.
Using Class Methods Exceptions The newInstance method throws the following exceptions: NegativeArraySizeException The specified dims parameter is negative. ArrayStoreException The specified data is nonnumeric or non-Boolean. Example — Constructing a Logical Array Object with newInstance Construct a 1-by-5 logical array using the newInstance method. Note that data in the Java array must be stored in a column-wise order so that it will be in row-wise order in the final MWLogicalArray object.
4 Using MWArray Classes To construct a sparse logical matrix with no nonzero elements, use the following: public static MWLogicalArray newSparse(int rows, int cols, int nzmax) To construct a sparse logical matrix from a supplied full matrix, use the following: public static MWLogicalArray newSparse(Object data) To specify what data is assigned to each element, use the following: public static MWLogicalArray newSparse(int[] rowindex, int[] colindex, Object data) To specify the number of rows and columns
Using Class Methods S(rowIndex(k), colIndex(k)) = data(k) rows and cols Number of rows and columns in the matrix nzmax Maximum number of nonzero elements Valid types for the data parameter are as follows: • double[] • float[] • long[] • int[] • short[] • byte[] • boolean[] • One-dimensional arrays of any subclass of java.lang.Number • One-dimensional arrays of java.lang.Boolean • One-dimensional arrays of java.lang.
4 Using MWArray Classes The specified index parameter is invalid. ArrayStoreException Incompatible array type or invalid array data Example — Constructing a Sparse Logical Array Object Create a sparse array of logical values using the newSparse method: boolean[] Adata = {true, true, false, false, true}; int[] ri = {1, 1, 1, 1, 1}; int[] ci = {1, 2, 3, 4, 5}; MWLogicalArray A = MWLogicalArray.newSparse(ri, ci, Adata); System.out.println(A.
Using Class Methods Method Description “getDimensions” on page 4-100 Returns an array containing the size of each dimension of this array. “isEmpty” on page 4-100 Tests whether the array has no elements. “numberOfDimensions” on page 4-100 Returns the number of dimensions of this array. “numberOfElements” on page 4-100 Returns the total number of elements in this array. classID. This method returns the MATLAB type of the MWLogicalArray object.
4 Using MWArray Classes When run, the example displays this output: Class of A is logical getDimensions. MWLogicalArray inherits this method from the MWArray class. isEmpty. MWLogicalArray inherits this method from the MWArray class. numberOfDimensions. MWLogicalArray inherits this method from the MWArray class. numberOfElements. MWLogicalArray inherits this method from the MWArray class.
Using Class Methods getBoolean. This method returns the element located at the specified one-based index of the MWLogicalArray object. To get the element at a specific index, use one of the following: public boolean getBoolean(int index) public boolean getBoolean(int[] index) Use the first syntax (int index) to return the element at the specified one-based offset in the array, accessing elements in column-wise order.
4 Using MWArray Classes Example — Getting a Boolean Value from a Logical Array boolean[][] Adata = {{true, false, false}, {false, true, false}}; MWLogicalArray A = new MWLogicalArray(Adata); int[] index = {2, 2}; System.out.println("A(2,2) is " + A.getBoolean(index)); When run, the example displays this output: A(2,2) = true set. This method returns the element located at the specified one-based index of the MWLogicalArray object.
Using Class Methods In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWLogicalArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension. Exceptions The set method throws the following exception: IndexOutOfBoundsException The specified index parameter is invalid.
4 Using MWArray Classes Setting A(2,3) to true Array element A(2,3) is true toArray. MWLogicalArray inherits this method from the MWArray class. Methods to Copy, Convert, and Compare MWLogicalArrays Use these methods to copy, convert, and compare objects of class MWLogicalArray. Method Description “clone” on page 4-104 Creates and returns a deep copy of this array. “compareTo” on page 4-105 Compares this array with the specified array for order.
Using Class Methods public Object clone() Input Parameters None Exceptions The clone method throws the following exception: java.lang.CloneNotSupportedException The object’s class does not implement the Cloneable interface. Example — Cloning a Logical Array Object Create a clone of MWLogicalArray object A: boolean[][] Adata = {{true, false, false}, {false, true, false}}; MWLogicalArray A = new MWLogicalArray(Adata); Object C = A.clone(); System.out.println("Clone of logical matrix A is:"); System.out.
4 Using MWArray Classes hashCode. MWLogicalArray inherits this method from the MWArray class. sharedCopy. This method creates and returns a shared copy of the MWLogicalArray object. The shared copy points to the underlying original MATLAB array. Any changes made to the copy are reflected in the original. The sharedCopy method of MWLogicalArray overrides the sharedCopy method of class MWArray.
Using Class Methods Methods to Use on Sparse MWLogicalArrays Use these methods to return information on sparse arrays of type MWLogicalArray. All are inherited from class MWArray. Method Description “isSparse” on page 4-55 Tests whether the array is sparse. “columnIndex” on page 4-56 Returns an array containing the column index of each nonzero element in the underlying MATLAB array.
4 Using MWArray Classes Constructing an MWCharArray Use the tables in this section to construct an MWCharArray from a particular Java data type. See the examples in this section for more help. Constructing an Empty Character Array.
Using Class Methods char[] chArray2 = {'W', 'o', 'r', 'l', 'd'}; MWCharArray A = new MWCharArray(chArray1); System.out.println("The string in MWCharArray1 is \"" + A + "\""); Construct a second MWCharArray from a String object: String str = new String(chArray2); MWCharArray A2 = new MWCharArray(str); System.out.
4 Using MWArray Classes To construct a MWCharArray object with the specified dimensions, use public static MWCharArray newInstance(int[] dims) The elements of the array are all initialized to zero. To construct a MWCharArray object with the specified dimensions and initialized with the supplied data, use public static MWCharArray newInstance(int[] dims, Object data) Input Parameters dims Array of dimension sizes. Each dimension size must be nonnegative.
Using Class Methods disposeArray. MWCharArray inherits this method from the MWArray class. Methods to Return Information About an MWCharArray Use these methods to return information about an object of class MWCharArray. Method Description “classID” on page 4-111 Returns the MATLAB type of this array. “getDimensions” on page 4-112 Returns an array containing the size of each dimension of this array. “isEmpty” on page 4-112 Tests whether the array has no elements.
4 Using MWArray Classes When run, the example displays this output: The class of A is char getDimensions. MWCharArray inherits this method from the MWArray class. isEmpty. MWCharArray inherits this method from the MWArray class. numberOfDimensions. MWCharArray inherits this method from the MWArray class. numberOfElements. MWCharArray inherits this method from the MWArray class. Methods to Get and Set Data in the MWCharArray Use these methods to get and set values in an object of class MWCharArray.
Using Class Methods getChar. This method returns the character located at the specified one-based index of the MWCharArray object. To get the element at a specific index, use one of public char getChar(int index) public char getChar(int[] index) Use the first syntax (int index) to return the element at the specified one-based offset in the array, accessing elements in column-wise order. Use the second syntax (int[] index) to return the element at the specified array of one-based indices.
4 Using MWArray Classes Example — Getting Character Array Data with getChar Use getChar to display the string stored in MWCharArray object A: char[] chArray = {'H', 'e', 'l', 'l', 'o'}; MWCharArray A = new MWCharArray(chArray); for (int i = 1; i <= 5; i++) System.out.print(A.getChar(i)); When run, the example displays this output: Hello set. This method replaces the character located at the specified one-based offset in the MWCharArray object with the specified char value.
Using Class Methods In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWCharArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension. Exceptions The set method throws the following exception: IndexOutOfBoundsException The specified index parameter is invalid.
4 Using MWArray Classes toArray. MWCharArray inherits this method from the MWArray class. Methods to Copy, Convert, and Compare MWCharArrays Use these methods to copy, convert, and compare objects of class MWCharArray. Method Description “clone” on page 4-116 Creates and returns a deep copy of this array. “compareTo” on page 4-117 Compares this array with the specified array for order. “equals” on page 4-117 Indicates whether some other array is equal to this one.
Using Class Methods Example — Cloning a Character Array Object Create a clone of MWCharArray object A: char[] chArray = {'H', 'e', 'l', 'l', 'o'}; MWCharArray A = new MWCharArray(chArray); Object C = A.clone(); System.out.println("Clone of matrix A is:"); System.out.println(C.toString()); When run, the example displays this output: Clone of matrix A is: Hello compareTo. MWCharArray inherits this method from the MWArray class. equals. MWCharArray inherits this method from the MWArray class. hashCode.
4 Using MWArray Classes Example — Making a Shared Copy of a Character Array Object Create a shared copy of MWCharArray object A: char[] chArray = {'H', 'e', 'l', 'l', 'o'}; MWCharArray A = new MWCharArray(chArray); Object S = A.sharedCopy(); System.out.print("Shared copy of matrix A is \"" + S.toString() + "\""); When run, the example displays this output: Shared copy of matrix A is "Hello" toString. MWCharArray inherits this method from the MWArray class.
Using Class Methods To construct an MWStructArray object with the specified dimensions and field names, use MWStructArray(int[] dims, java.lang.String[] fieldnames) To construct an MWStructArray object with the specified number of rows and columns, and field names, use MWStructArray(int rows, int cols, java.lang.String[] fieldnames) Input Parameters dims Array of dimension sizes. Each dimension size must be nonnegative. fieldnames Array of field names rows Number of rows in the array.
4 Using MWArray Classes The second example creates a 1-by-2 MWStructArray object with fields f1, f2, and f3: int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); System.out.println("Structure array S: " + S); When run, the example displays this output: Structure array S: 1x2 struct array with fields: f1 f2 f3 Methods to Destroy an MWStructArray To destroy the arrays, use either dispose or disposeArray.
Using Class Methods Example — Disposing of a Structure Array Object int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); System.out.println("Structure array S: " + S); System.out.println("Now disposing of array S\n"); S.dispose(); System.out.println("Structure array S: " + S); When run, the example displays this output: Structure array S: 1x2 struct array with fields: f1 f2 f3 Now disposing of array S Structure array S: [] disposeArray.
4 Using MWArray Classes Method Description “numberOfDimensions” on page 4-123 Returns the number of dimensions of this array. “numberOfElements” on page 4-123 Returns the total number of elements in this array. “numberOfFields” on page 4-123 Returns the number of fields in this array. classID. This method returns the MATLAB type of this array. The classID method of MWStructArray overrides the classID method of class MWArray.
Using Class Methods public java.lang.String[] fieldNames() Input Parameters None Example — Getting the Field Names of a Structure Array Create an MWStructArray object with three fields and display the field names: int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); String[] str = S.fieldNames(); System.out.print("The structure has the fields: "); for (int i=0; i
4 Using MWArray Classes public int numberOfFields() Input Parameters None Example — Getting the Number of Fields in a Structure Array Create an MWStructArray object with three fields and display the number of fields: int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); String[] str = S.fieldNames(); System.out.println("There are " + S.numberOfFields() + " fields in this structure.
Using Class Methods Method Description “getField” on page 4-128 Returns a shared copy of the element at the specified one-based offset and field name in this array as an MWArray instance. “set” on page 4-129 Replaces the element at the specified one-based offset in this array with the specified element. “toArray” on page 4-131 Returns an array containing a copy of the data in the underlying MATLAB array. The returned array has the same dimensionality as the MATLAB array. get.
4 Using MWArray Classes index Index of the requested element in the MWStructArray In the case where index is of type int, the valid range for index is 1 <= index <= N, where N is the total number of elements in the array. In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWStructArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension.
Using Class Methods Structure data S(1,1).f2 is 555 getData. This method returns a one-dimensional array containing a copy of the data in the underlying MATLAB array. The getData method of MWStructArray overrides the getData method of class MWArray. The prototype for the getData method is public Object getData() getData returns a one-dimensional array of elements stored in column-wise order.
4 Using MWArray Classes MWArray[] x = (MWArray[]) S.getData(); for (int i = 0; i < x.length; i++) System.out.print(" " + x[i]); When run, the example displays this output: Data read from structure array S: 15 30 45 60 75 90 getField. This method returns a shared copy of the element at the specified one-based index array and field name in this array as an MWArray instance.
Using Class Methods Field name of the requested element index Index of the requested element in the MWStructArray In the case where index is of type int, the valid range for index is 1 <= index <= N, where N is the total number of elements in the array. In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWStructArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension.
4 Using MWArray Classes second syntax (int[] index) to return the element at the specified array of one-based indices. The first syntax offers better performance than the second. Input Parameters fieldname Field name of the requested element index Index of the requested element in the MWStructArray In the case where index is of type int, the valid range for index is 1 <= index <= N, where N is the total number of elements in the array.
Using Class Methods Example — Setting Values in a Structure Array int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); Integer[] val = new Integer[25]; for (int i = 0; i < 6; i++) val[i] = new Integer(i * 15); for (int i = 0; i < 2; i++) for (int j = 0; j < sfields.length; j++) S.set(sfields[j], i+1, val[j + (i * 3)]); // Use getData to get data from the structure. System.out.
4 Using MWArray Classes Input Parameters None Example — Getting Structure Array Data with toArray int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); Integer[] val = new Integer[25]; for (int i = 0; i < 6; i++) val[i] = new Integer(i * 15); for (int i = 0; i < 2; i++) for (int j = 0; j < sfields.length; j++) S.set(sfields[j], i+1, val[j + (i * 3)]); Object[][][] x = (Object[][][]) S.toArray(); System.out.println(); System.out.
Using Class Methods Method Description “clone” on page 4-133 Creates and returns a deep copy of this array. “compareTo” on page 4-134 Compares this array with the specified array for order. “equals” on page 4-134 Indicates whether some other array is equal to this one. “hashCode” on page 4-134 Returns a hash code value for the array. “sharedCopy” on page 4-134 Creates and returns a shared copy of this array. “toString” on page 4-135 Returns a string representation of the array. clone.
4 Using MWArray Classes Example — Cloning a Structure Array Object Create an MWStructArray object and then a clone of that object: int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); Object C = S.clone(); System.out.println("Clone of structure S is:"); System.out.println(C.toString()); When run, the example displays this output: Clone of structure S is: 1x2 struct array with fields: f1 f2 f3 compareTo.
Using Class Methods Input Parameters None Example — Making a Shared Copy of a Structure Array Object Create an MWStructArray object and then a shared copy of that object: int[] sdims = {1, 2}; String[] sfields = {"f1", "f2", "f3"}; MWStructArray S = new MWStructArray(sdims, sfields); Object C = S.sharedCopy(); System.out.println("Shared copy of structure S is:"); System.out.println(C.
4 Using MWArray Classes Constructing an MWCellArray Use the tables in this section to construct an MWCellArray from a particular Java data type. See the examples at the end of this section for more help: Constructing an Empty Cell Array.
Using Class Methods Example — Constructing an Empty Cell Array Object This first example creates an empty MWCellArray object: MWCellArray C = new MWCellArray(); System.out.println("C = " + C.
4 Using MWArray Classes Method Description “dispose” on page 4-138 Frees the native MATLAB array contained by this array. “disposeArray” on page 4-138 Frees all native MATLAB arrays contained in the input object. dispose. This method frees the native MATLAB array contained by this array. The dispose method of MWCellArray overrides the dispose method of class MWArray.
Using Class Methods Method Description “classID” on page 4-139 Returns the MATLAB type of this array. “getDimensions” on page 4-139 Returns an array containing the size of each dimension of this array. “isEmpty” on page 4-140 Tests whether the array has no elements. “numberOfDimensions” on page 4-140 Returns the number of dimensions of this array. “numberOfElements” on page 4-140 Returns the total number of elements in this array. classID. This method returns the MATLAB type of this array.
4 Using MWArray Classes isEmpty. MWCellArray inherits this method from the MWArray class. numberOfDimensions. MWCellArray inherits this method from the MWArray class. numberOfElements. MWCellArray inherits this method from the MWArray class. Methods to Get and Set Data in the MWCellArray Use these methods to get and set values in an object of class MWCellArray. Method Description “get” on page 4-140 Returns the element at the specified offset as an Object.
Using Class Methods Use the first syntax (int index) to return the element at the specified one-based offset in the array, accessing elements in column-wise order. Use the second syntax (int[] index) to return the element at the specified array of one-based indices. The first syntax offers better performance than the second.
4 Using MWArray Classes C.set(index, val); Object x = C.get(index); System.out.println("Cell data C(1,3) is " + x.toString()); When run, the example displays this output: Cell data C(1,3) is 15 getCell. This method returns a shared copy of the element at the specified one-based offset in this array as an MWArray instance.
Using Class Methods Exceptions The getCell method throws the following exception: IndexOutOfBoundsException The specified index parameter is invalid. getData. This method returns a one-dimensional array containing a copy of the data in the underlying MATLAB array. The getData method of MWCellArray overrides the getData method of class MWArray. The prototype for the getData method is as follows: public Object getData() getData returns a one-dimensional array of elements stored in column-wise order.
4 Using MWArray Classes System.out.println("Data read from cell array C: \n"); MWArray[] x = (MWArray[]) C.getData(); for (int i = 0; i < x.length; i++) System.out.println(x[i]); System.out.println(); When run, the example displays this output: Data read from cell array C: 0 0 0 set. This method replaces the element at the specified one-based offset in this array with the specified element. The set method of MWCellArray overrides the set method of class MWArray.
Using Class Methods index Index of the requested element in the MWCellArray In the case where index is of type int, the valid range for index is 1 <= index <= N, where N is the total number of elements in the array. In the case where index is of type int[], each element of the index vector is an index along one dimension of the MWCellArray object. The valid range for any index is 1 <= index[i] <= N[i], where N[i] is the size of the ith dimension.
4 Using MWArray Classes toArray. This method returns an array containing a copy of the data in the underlying MATLAB array. The prototype for the toArray method is as follows: public Object[] toArray() toArray returns an array with the same dimensionality as the MATLAB array. Each element in the returned array is converted to a Java array when you call MWArray.toArray() on the corresponding cell.
Using Class Methods Methods to Copy, Convert, and Compare MWCellArrays Use these methods to copy, convert, and compare objects of class MWCellArray. Method Description “clone” on page 4-147 Creates and returns a deep copy of this array. “compareTo” on page 4-148 Compares this array with the specified array for order. “equals” on page 4-148 Indicates whether some other array is equal to this one. “hashCode” on page 4-148 Returns a hash code value for the array.
4 Using MWArray Classes Exceptions The clone method throws the following exception: IndexOutOfBoundsException The specified index parameter is invalid. Example — Cloning a Cell Array Object Create an MWCellArray object and then a clone of that object: int[] cdims = {1, 3}; MWCellArray C = new MWCellArray(cdims); Object X = C.clone(); System.out.println("Clone of cell array C is:"); System.out.println(X.
Using Class Methods public Object sharedCopy() Input Parameters None Example — Making a Shared Copy of a Cell Array Object Create an MWCellArray object and then a shared copy of that object: int[] cdims = {1, 3}; MWCellArray C = new MWCellArray(cdims); Object X = C.sharedCopy(); System.out.println("Shared copy of cell array C is:"); System.out.println(X.toString()); When run, the example displays this output: Shared copy of cell array C is: [] [] [] toString.
4 Using MWArray Classes CHAR. CHAR represents MATLAB array type char. DOUBLE. DOUBLE represents MATLAB array type double. FUNCTION. FUNCTION represents MATLAB array type function. Note MATLAB function arrays are not supported in the current release. INT8. INT8 represents MATLAB array type int8. INT16. INT16 represents MATLAB array type int16. INT32. INT32 represents MATLAB array type int32. INT64. INT64 represents MATLAB array type int64. LOGICAL. LOGICAL represents MATLAB array type logical. OBJECT.
Using Class Methods UINT32. UINT32 represents MATLAB array type uint32. UINT64. UINT64 represents MATLAB array type uint64. UNKNOWN. UNKNOWN represents MATLAB empty array type. Example — Specifying an MWClassID Value Construct a scalar numeric array of type MWClassID.INT16: double AReal = 24; MWNumericArray A = new MWNumericArray(AReal, MWClassID.INT16); System.out.println("Array A of type " + A.
4 Using MWArray Classes The prototype for hashCode is as follows: public final int hashCode() isNumeric. This method tests if this type is numeric. The prototype for isNumeric is as follows: public boolean isNumeric() toString. This method returns a string representation of the property. The toString method of MWClassID overrides the toString method of class java.lang.Object. The prototype for toString is as follows: public final java.lang.
Using Class Methods Example – Determining the Complexity of an Array Determine whether matrix A is real or complex. The complexity method of MWNumericArray returns an enumeration of type MWComplexity. double AReal = 24; double AImag = 5; MWNumericArray A = new MWNumericArray(AReal, AImag); System.out.println("A is a " + A.complexity() + " matrix"); When run, the example displays this output: A is a complex matrix Methods of MWComplexity toString.
4 Using MWArray Classes 4-154
5 Sample Applications (Java) Note The examples for MATLAB Builder for Java are in matlabroot\toolbox\javabuilder\Examples. In addition to these examples, see “Example: Magic Square” on page 1-15 for a simple example that gets you started using MATLAB Builder for Java. Plot Example (p. 5-2) How to encapsulate a MATLAB function that draws a plot given two input arguments Spectral Analysis Example (p. 5-8) How to create a class that has two methods Matrix Math Example (p.
5 Sample Applications (Java) Plot Example The purpose of the example is to show you how to do the following: • Use MATLAB Builder for Java to convert a MATLAB function (drawplot) to a method of a Java class (plotter) and wrap the class in a Java component (plotdemo). • Access the component in a Java application (createplot.java) by instantiating the plotter class and using the MWArray class library to handle data conversion.
Plot Example plot(x,y); This code is already in your work directory in PlotExample\PlotDemoComp\drawplot.m. 4 Specify a Java component as follows: a. While in MATLAB, issue the following command to open the Deployment Tool dialog box: deploytool b. Create a new project with these settings: Field Value Component name plotdemo Class name plotter Show verbose output Selected c. Add the computefft.m and plotfft.m M-files to the project. d. Save the project. 5 Build the component.
5 Sample Applications (Java) The program listing is shown here. createplot.java /* createplot.java * This file is used as an example for the MATLAB * Builder for Java product. * * Copyright 2001-2006 The MathWorks, Inc. */ /* Necessary package imports */ import com.mathworks.toolbox.javabuilder.*; import plotdemo.*; /* * createplot class demonstrates plotting x-y data into * a MATLAB figure window by graphing a simple parabola.
Plot Example x.set(i, i); y.set(i, i*i); } /* Create new plotter object */ thePlot = new plotter(); /* Plot data */ thePlot.drawplot(x, y); } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { /* Free native resources */ MWArray.disposeArray(x); MWArray.disposeArray(y); if (thePlot != null) thePlot.dispose(); } } } The program does the following: • Creates two arrays of double values, using MWNumericArray to represent the data needed to plot the equation.
5 Sample Applications (Java) • Uses a try-catch block to catch and handle any exceptions. 7 Compile the createplot application using javac. a. On Windows, execute the following command: javac -classpath .;matlabroot\java\jar\toolbox\javabuilder.jar; .\distrib\plotdemo.jar createplot.java b. On UNIX, execute this command: javac -classpath .:matlabroot/java/jar/toolbox/javabuilder.jar: ./distrib/plotdemo.jar createplot.java 8 Run the application. To run the createplot.
Plot Example Note The supported JRE version is 1.5.0. To find out what JRE you are using, refer to the output of 'version -java' in MATLAB or refer to the jre.cfg file in matlabroot/sys/java/jre/ or mcrroot/sys/java/jre/.
5 Sample Applications (Java) Spectral Analysis Example The purpose of the example is to show you the following: • How to use MATLAB Builder for Java to create a component (spectralanalysis) containing a class that has a private method that is automatically encapsulated. • How to access the component in a Java application (powerspect.java), including use of the MWArray class hierarchy to represent data. Note For complete reference information about the MWArray class hierarchy, see the com.mathworks.
Spectral Analysis Example powerspect = []; return; end if (interval <= 0) error('Sampling interval must be greater then zero'); return; end fftData = fft(data); freq = (0:length(fftData)-1)/(length(fftData)*interval); powerSpect = abs(fftData)/(sqrt(length(fftData))); plotfft.m function PlotFFT(fftData, freq, powerSpect) %PLOTFFT Computes and plots the FFT and power spectral density. % [FFTDATA, FREQ, POWERSPECT] = PLOTFFT(DATA, INTERVAL) % Computes the FFT and power spectral density of the input data.
5 Sample Applications (Java) 2 If you have not already done so, set the environment variables that are required on a development machine. See “Settings for Environment Variables (Development Machine)” on page 6-2. 3 Write the M-code that you want to access. This example uses computefft.m and plotfft.m, which are already in your work directory in SpectraExample\SpectraDemoComp. 4 Specify a Java component as follows: a.
Spectral Analysis Example 6 Write source code for an application that accesses the component. The sample application for this example is in SpectraExample\SpectraDemoJavaApp\powerspect.java. The program listing is shown here. powerspect.java /* powerspect.java * This file is used as an example for the MATLAB * Builder for Java product. * * Copyright 2001-2006 The MathWorks, Inc. */ /* Necessary package imports */ import com.mathworks.toolbox.javabuilder.*; import spectralanalysis.
5 Sample Applications (Java) * Sampling interval = 0.01 */ int[] dims = {1, nSamples}; data = MWNumericArray.newInstance(dims, MWClassID.DOUBLE, MWComplexity.REAL); for (int i = 1; i <= nSamples; i++) { double t = (i-1)*interval; double x = Math.sin(2.0*Math.PI*15.0*t) + Math.sin(2.0*Math.PI*40.0*t) + Math.random(); data.set(i, x); } /* Create new fourier object */ theFourier = new fourier(); /* Compute power spectral density and plot result */ result = theFourier.
Spectral Analysis Example The program does the following: • Constructs an input array with values representing a random signal with two sinusoids at 15 and 40 Hz embedded inside of it • Creates an MWNumericArray array that contains the data, as shown: data = MWNumericArray.newInstance(dims, MWClassID.DOUBLE, MWComplexity.
5 Sample Applications (Java) .;matlabroot\java\jar\toolbox\javabuilder.jar; .\distrib\spectralanalysis.jar -Djava.library.path=matlabroot\bin\win32;.\distrib powerspect • On UNIX, execute the powerspect class file as follows: java -classpath .:matlabroot/java/jar/toolbox/javabuilder.jar: ./distrib/spectralanalysis.jar -Djava.library.path=matlabroot/bin/./distrib powerspect % where = glux86 gluxa64 sol2 Note The supported JRE version is 1.5.0.
Spectral Analysis Example 5-15
5 Sample Applications (Java) Matrix Math Example The purpose of the example is to show you the following: • How to assign more than one MATLAB function to a component class. • How to manually handle native memory management. • How to access the component in a Java application (getfactor.java) by instantiating Factor and using the MWArray class library to handle data conversion. Note For complete reference information about the MWArray class hierarchy, see the com.mathworks.toolbox.javabuilder package.
Matrix Math Example %CHOLESKY Cholesky factorization of A. % L = CHOLESKY(A) returns the Cholesky factorization of A. % This file is used as an example for the MATLAB % Builder for Java product. % Copyright 2001-2006 The MathWorks, Inc. L = chol(A); ludecomp.m function [L,U] = ludecomp(A) %LUDECOMP LU factorization of A. % [L,U] = LUDECOMP(A) returns the LU factorization of A. % This file is used as an example for the MATLAB % Builder for Java product.
5 Sample Applications (Java) b. At the MATLAB command prompt, cd to the new MatrixMathExample subdirectory in your work directory. 2 If you have not already done so, set the environment variables that are required on a development machine. See “Settings for Environment Variables (Development Machine)” on page 6-2. 3 Write the MATLAB functions as you would any MATLAB function.
Matrix Math Example getfactor.java /* getfactor.java * This file is used as an example for the MATLAB * Builder for Java product. * * Copyright 2001-2006 The MathWorks, Inc. */ /* Necessary package imports */ import com.mathworks.toolbox.javabuilder.*; import factormatrix.*; /* * getfactor class computes cholesky, LU, and QR * factorizations of a finite difference matrix * of order N. The value of N is passed on the * command line.
5 Sample Applications (Java) if (n <= 0) { System.out.println("Error: must input a positive integer"); return; } /* * Allocate matrix. If second input is "sparse" * allocate a sparse array */ int[] dims = {n, n}; if (args.length > 1 && args[1].equals("sparse")) a = MWNumericArray.newSparse(dims[0], dims[1],n+2*(n-1), MWClassID.DOUBLE, MWComplexity.REAL); else a = MWNumericArray.newInstance(dims,MWClassID.DOUBLE, MWComplexity.
Matrix Math Example result = theFactor.cholesky(1, a); System.out.println("Cholesky factorization:"); System.out.println(result[0]); MWArray.disposeArray(result); /* Compute LU factorization and print results. */ result = theFactor.ludecomp(2, a); System.out.println("LU factorization:"); System.out.println("L matrix:"); System.out.println(result[0]); System.out.println("U matrix:"); System.out.println(result[1]); MWArray.disposeArray(result); /* Compute QR factorization and print results.
5 Sample Applications (Java) creates an instance of the class factor. The following statements call the methods that encapsulate the MATLAB functions: result = theFactor.cholesky(1, a); ... result = theFactor.ludecomp(2, a); ... result = theFactor.qrdecomp(2, a); ... 10 Compile the getfactor application using javac. cd to the matlabroot\work\factormatrix directory. • On Windows, execute the following command: javac -classpath .;matlabroot\java\jar\toolbox\javabuilder.jar; .\distrib\factormatrix.
Matrix Math Example • On UNIX, execute the getfactor class file as follows: java -classpath .:matlabroot/java/jar/toolbox/javabuilder.jar: ./distrib/factormatrix.jar -Djava.library.path=matlabroot/bin/./distrib getfactor 4 % where = glux86 gluxa64 sol2 Note The supported JRE version is 1.5.0. To find out what JRE you are using, refer to the output of 'version -java' in MATLAB or refer to the jre.cfg file in matlabroot/sys/java/jre/ or mcrroot/sys/java/jre/.
5 Sample Applications (Java) 0 0 0 1.5000 0 0 -1.0000 1.3333 0 0 -1.0000 1.2500 QR factorization: Q matrix: -0.8944 -0.3586 0.4472 -0.7171 0 0.5976 0 0 -0.1952 -0.3904 -0.5855 0.6831 0.1826 0.3651 0.5477 0.7303 R matrix: -2.2361 0 0 0 -0.4472 1.9124 -1.4639 0 0 -0.5976 1.9518 0.9129 1.7889 -1.6733 0 0 To run the same program for a sparse matrix, use the same command and add the string sparse to the command line: java (...
Matrix Math Example (1,1) (1,2) (2,2) (2,3) (3,3) (3,4) (4,4) 1.4142 -0.7071 1.2247 -0.8165 1.1547 -0.8660 1.1180 LU factorization: L matrix: (1,1) 1.0000 (2,1) -0.5000 (2,2) 1.0000 (3,2) -0.6667 (3,3) 1.0000 (4,3) -0.7500 (4,4) 1.0000 U matrix: (1,1) (1,2) (2,2) (2,3) (3,3) (3,4) (4,4) 2.0000 -1.0000 1.5000 -1.0000 1.3333 -1.0000 1.2500 QR factorization: Q matrix: (1,1) 0.8944 (2,1) -0.4472 (1,2) 0.3586 (2,2) 0.7171 (3,2) -0.5976 (1,3) 0.1952 (2,3) 0.3904 (3,3) 0.
5 Sample Applications (Java) (4,3) (1,4) (2,4) (3,4) (4,4) R matrix: (1,1) (1,2) (2,2) (1,3) (2,3) (3,3) (2,4) (3,4) (4,4) -0.6831 0.1826 0.3651 0.5477 0.7303 2.2361 -1.7889 1.6733 0.4472 -1.9124 1.4639 0.5976 -1.9518 0.9129 Understanding the getfactor Program The getfactor program takes one or two arguments from standard input. The first argument is converted to the integer order of the test matrix.
6 Reference Information for Java Requirements for MATLAB Builder for Java (p. 6-2) Software requirements for using MATLAB Builder for Java MATLAB Builder for Java Graphical User Interface (p. 6-7) Details about the windows, dialog boxes, menus, and buttons Data Conversion Rules (p. 6-10) Details about the way that MATLAB Builder for Java handles data Programming Interfaces Generated by Java Builder (p.
6 Reference Information for Java Requirements for MATLAB Builder for Java • “System Requirements” on page 6-2 • “Limitations and Restrictions” on page 6-2 • “Settings for Environment Variables (Development Machine)” on page 6-2 System Requirements System requirements and restrictions on use for MATLAB Builder for Java are as follows: • All requirements for the MATLAB Compiler; see “Installation and Configuration” in the MATLAB Compiler documentation. • Java Development Kit (JDK) 1.
Requirements for MATLAB Builder for Java • “Java CLASSPATH Variable” on page 6-4 • “Native Library Path Variables” on page 6-6 JAVA_HOME Variable Java Builder uses the JAVA_HOME variable to locate the Java Software Development Kit (SDK) on your system. It also uses this variable to set the versions of the javac.exe and jar.exe files it uses during the build process. Note If you do not set JAVA_HOME, Java Builder assumes that \jdk\bin is on the system path.
6 Reference Information for Java setenv JAVA_HOME /java/jdk/j2sdk1.5.0 Alternatively, you can add jdk_directory\bin to the system path. Java CLASSPATH Variable To build and run a Java application that encapsulates MATLAB the system needs to find .jar files containing the MATLAB libraries and the class and method definitions that you have developed and built with Java Builder. To tell the system how to locate the .
Requirements for MATLAB Builder for Java Note For matlabroot substitute the MATLAB root directory on your system. Type matlabroot to see this directory name. To set your CLASSPATH variable on your development machine, enter the following command at the DOS command prompt: set CLASSPATH=.;C:\matlabroot\toolbox\javabuilder\jar\javabuilder.jar; C:\mycomponent\mycomponent.jar Alternatively, if the Java SDK is installed, you can specify the class path on the Java command line as follows. javac -classpath .
6 Reference Information for Java javac -classpath .:/matlabroot/toolbox/javabuilder/jar/javabuilder.jar: /mycomponent/mycomponent.jar usemyclass.java where usemyclass.java is the file to be compiled. Native Library Path Variables The operating system uses the native library path to locate native libraries that are needed to run your Java class.
MATLAB Builder for Java Graphical User Interface MATLAB Builder for Java Graphical User Interface Use the MATLAB Builder for Java graphical user interface (GUI) to create Java classes that encapsulate your M-file functions. You can build and package Javacomponents that support the classes you create.
6 Reference Information for Java Note that the Deployment Tool window can be docked or undocked. The Deployment Tool toolbar has the following icons. Toolbar Icons Name of Toolbar Icon 6-8 Icon Click to... New Project Create a new deployment project. Open Project View projects and select one to open. Save Project Save the current project, including all files and settings.
MATLAB Builder for Java Graphical User Interface Toolbar Icons (Continued) Name of Toolbar Icon Icon Click to... Remove Remove the selected class folder or the selected files from the project. Build Build the components specified by the project, displaying the build process in the Deployment Tool Output pane. Package Create a self-extracting executable (Windows) or .zip file (UNIX) that contains the files needed to use the component in an application. Settings Change settings for the project.
6 Reference Information for Java Data Conversion Rules • “Java to MATLAB Conversion” on page 6-10 • “MATLAB to Java Conversion” on page 6-12 • “Unsupported MATLAB Array Types” on page 6-13 Java to MATLAB Conversion The following table lists the data conversion rules for converting Java data types to MATLAB types. Note The conversion rules apply to scalars, vectors, matrices, and multidimensional arrays of the types listed.
Data Conversion Rules Java to MATLAB Conversion Rules (Continued) Java Type MATLAB Type java.lang.Float single java.lang.Byte int8 java.lang.Integer int32 java.lang.Long int64 java.lang.Short int16 java.lang.Number double Note Subclasses of java.lang.Number not listed above are converted to double. java.lang.Boolean logical java.lang.Character char java.lang.String char Note A Java string is converted to a 1-by-N array of char with N equal to the length of the input string.
6 Reference Information for Java MATLAB to Java Conversion The following table lists the data conversion rules for converting MATLAB data types to Java types. Note The conversion rules apply to scalars, vectors, matrices, and multidimensional arrays of the types listed. MATLAB to Java Conversion Rules MATLAB Type Java Type (Primitive) Java Type (Object) cell N/A Object Note Cell arrays are constructed and accessed as arrays of MWArray.
Data Conversion Rules MATLAB to Java Conversion Rules (Continued) MATLAB Type Java Type (Primitive) Java Type (Object) uint16 short java.lang.shortJava has no unsigned type to represent the uint16 used in MATLAB. Construction of and access to MATLAB arrays of an unsigned type requires conversion. uint32 int java.lang.IntegerJava has no unsigned type to represent the uint32 used in MATLAB. Construction of and access to MATLAB arrays of an unsigned type requires conversion. uint64 long java.lang.
6 Reference Information for Java Programming Interfaces Generated by Java Builder • “APIs Based on MATLAB Function Signatures” on page 6-14 • “Standard API” on page 6-15 • “mlx API” on page 6-17 • “Code Fragment: Signatures Generated for myprimes Example” on page 6-17 APIs Based on MATLAB Function Signatures Java Builder generates two kinds of interfaces to handle MATLAB function signatures. • A standard signature in Java.
Programming Interfaces Generated by Java Builder Typically you use the standard interface when you want to call MATLAB functions that return a single array. In other cases you probably need to use the mlx interface. Standard API The standard calling interface returns an array of one or more MWArray objects. The standard API for a generic function with none, one, more than one, or a variable number of arguments, is shown in the following table.
6 Reference Information for Java by the varargin argument Object in2, ..., Object InN, Object varargin ) Details about the arguments for these samples of standard signatures are shown in the following table. Argument Description Details About this Argument numArgsOut Number of outputs An integer indicating the number of outputs you want the method to return. To return no arguments, omit this argument. The value of numArgsOut must be less than or equal to the MATLAB function nargout.
Programming Interfaces Generated by Java Builder mlx API For a function with the following structure: function [Out1, Out2, ..., varargout] = foo(In1, In2, ..., InN, varargin) Java Builder generates the following API, as the mlx interface: public void foo (List outputs, List inputs) throws MWException; public void foo (Object[] outputs, Object[] inputs) throws MWException; Code Fragment: Signatures Generated for myprimes Example For a specific example, look at the myprimes method.
6 Reference Information for Java { (implementation omitted) } The standard interface specifies inputs to the function within the argument list and outputs as return values. Rather than returning function outputs as a return value, the feval interface includes both input and output arguments in the argument list. Output arguments are specified first, followed by input arguments. See “APIs Based on MATLAB Function Signatures” on page 6-14 for details about the interfaces.
MWArray Class Specification MWArray Class Specification For complete reference information about the MWArray class hierarchy, see com.mathworks.toolbox.javabuilder.MWArray, which is in the matlabroot/help/toolbox/javabuilder/MWArrayAPI/ directory. Note For matlabroot substitute the MATLAB root directory on your system. Type matlabroot to see this directory name.
6 6-20 Reference Information for Java
7 Functions — Alphabetical List
deploytool Purpose Open GUI for MATLAB Builder for Java and MATLAB Compiler Syntax deploytool Description The deploytool command opens the Deployment Tool dialog box, which is the graphical user interface (GUI) for MATLAB Builder for Java and for MATLAB Compiler.
A Examples Use this list to find examples in the documentation.
A Examples Quick Start “Example: Magic Square” on page 1-15 Handling Data “Code Fragment: Passing an MWArray” on page 3-7 “Code Fragment: Passing a Java Double Object” on page 3-8 “Code Fragment: Passing an MWArray” on page 3-8 “Code Fragment: Passing Variable Numbers of Inputs” on page 3-10 “Code Fragment: Passing Array Inputs” on page 3-11 “Code Fragment: Passing a Variable Number of Outputs” on page 3-12 “Code Fragment: Passing Optional Arguments with the Standard Interface” on page 3-13 “Code Fragmen
Handling Memory Handling Memory “Code Fragment: Use try-finally to Ensure Resources Are Freed” on page 3-27 Sample Applications (Java) “Plot Example” on page 5-2 “Spectral Analysis Example” on page 5-8 “Matrix Math Example” on page 5-16 A-3
A A-4 Examples
Index A Index API data conversion classes 3-6 MATLAB Builder for Java 4-1 arguments optional 3-9 standard interface 3-13 optional inputs 3-10 optional outputs 3-12 passing 3-6 array API overview 4-2 array inputs passing 3-11 arrays cell 4-31 constructing 4-32 character 4-26 constructing 4-27 logical 4-22 constructing 4-22 numeric 4-7 constructing 4-7 B build output componentLibInfo.
Index constructing cell arrays 4-32 character arrays 4-27 logical arrays 4-22 mwarrays 4-38 mwcellarrays 4-136 mwchararrays 4-108 mwlogicalarrays 4-92 mwnumericarrays 4-59 mwstructarrays 4-118 numeric arrays 4-7 sparse arrays 4-15 converting characters to MATLAB char array 6-11 converting data 3-7 Java to MATLAB 6-10 MATLAB to Java 6-12 converting strings to MATLAB char array 6-11 create plot example 5-2 creating objects 1-23 3-3 D data conversion 3-7 characters, strings 6-11 Java to MATLAB 6-10 MATLAB to
Index mwnumericarray 4-58 comparing 4-87 constants 4-90 constructors 4-59 converting 4-87 copying 4-87 creating 4-63 disposing 4-63 get information on 4-71 get, set: imaginary 4-79 get, set: real 4-75 sparse 4-90 mwstructarray 4-118 comparing 4-132 constructors 4-118 converting 4-132 copying 4-132 disposing 4-120 get information on 4-121 get, set 4-124 data conversion rules 3-28 deploytool function 7-2 development machine running the application 1-21 dispose 3-26 4-5 mwarray 4-39 mwcellarray 4-138 mwcharar
Index try-finally 3-27 mwstructarray 4-128 getfloat mwnumericarray 4-77 G garbage collection 3-25 get 4-5 mwarray 4-45 mwcellarray 4-34 4-140 mwchararray 4-30 4-112 mwlogicalarray 4-25 4-100 mwnumericarray 4-17 4-76 example 4-20 mwstructarray 4-125 getboolean mwlogicalarray 4-101 getbyte mwnumericarray 4-78 getcell mwcellarray 4-142 getchar mwchararray 4-113 getdata 4-5 mwarray 4-46 mwcellarray 4-37 4-143 mwchararray 4-112 mwlogicalarray 4-100 mwnumericarray 4-76 mwstructarray 4-127 getdimensions 4
Index mwclassid 4-151 mwlogicalarray 4-106 mwnumericarray 4-89 mwstructarray 4-134 I importing classes 1-23 isempty 4-5 mwarray 4-42 mwcellarray 4-140 mwchararray 4-112 mwlogicalarray 4-100 mwnumericarray 4-72 mwstructarray 4-123 isfinite mwnumericarray 4-72 isinf mwnumericarray 4-73 isnan mwnumericarray 4-74 isnumeric mwclassid 4-152 issparse 4-5 mwarray 4-55 J jagged arrays constructing 4-11 Java application running on the development machine 1-21 sample application usemyclass.
Index mwlogicalarray 4-92 comparing 4-104 constructors 4-92 converting 4-104 copying 4-104 creating 4-93 disposing 4-93 get information on 4-98 get, set 4-100 sparse 4-107 mwnumericarray 4-58 comparing 4-87 constants 4-90 constructors 4-59 converting 4-87 copying 4-87 creating 4-63 disposing 4-63 get information on 4-71 get, set: imaginary 4-79 get, set: real 4-75 sparse 4-90 mwstructarray 4-118 comparing 4-132 constructors 4-118 converting 4-132 copying 4-132 disposing 4-120 get information on 4-121 get,
Index mwcellarray 4-34 mwchararray 4-30 mwlogicalarray 4-25 mwnumericarray 4-17 of MWArray 3-8 3-28 multidimensional numeric arrays constructing 4-10 mwarray 4-2 4-38 comparing 4-49 constructors 4-38 converting 4-49 copying 4-49 disposing 4-39 get, set 4-44 Java interfaces 4-3 method overrides 4-3 methods of 4-4 sparse 4-54 MWArray 3-6 4-1 MWArray class library See also Data conversion 1-15 MWarray methods 3-8 3-28 mwarray query return values 3-16 mwarrayget information on 4-40 mwcellarray 4-31 4-135 compa
Index converting 4-104 copying 4-104 creating 4-93 disposing 4-93 get information on 4-98 get, set 4-100 newinstance 4-23 newsparse 4-23 sparse 4-107 mwlogicalarray methods get 4-25 set 4-25 mwnumericarray 4-7 4-58 comparing 4-87 constants 4-90 constructors 4-59 converting 4-87 copying 4-87 creating 4-63 disposing 4-63 get information on 4-71 get, set imaginary 4-79 real 4-75 newinstance 4-12 newsparse 4-12 sparse 4-90 mwnumericarray methods get 4-17 set 4-17 mwstructarray 4-118 comparing 4-132 constructor
Index input 3-10 output 3-12 standard interface 3-13 P passing arguments 3-6 passing array inputs 3-11 passing data matlab to java 2-7 path variable 6-6 platform issues 2-10 3-2 portability 2-10 3-2 programming overview 1-12 project elements of 2-3 setimag mwnumericarray 4-85 setting environment variables 6-2 sharedcopy 4-7 mwarray 4-53 mwcellarray 4-148 mwchararray 4-117 mwlogicalarray 4-106 mwnumericarray 4-89 mwstructarray 4-134 sparse mwlogicalarray 4-107 mwnumericarray 4-90 sparse arrays 4-54 const
Index mwstructarray 4-135 try-finally 3-27 U unchecked exceptions 3-22 usage information data conversion classes 4-1 Index-10 getting started 1-1 sample Java applications 5-1 usemyclass.