The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Builder™ JA User’s Guide
Revision History
September 2006 Online onlyNew for Version 1.0 (Release 2006b)
March 2007Online onlyRevised for Version 1.1 (Release 2007a)
September 2007 Online onlyRevised for Version 2.0 (Release 2007b)
March 2008Online onlyRevised for Version 2.0.1 (Release 2008a)
October 2008Online onlyRevised for Version 2.0.2 (Release 2008b)
March 2009Online onlyRevised for Version 2.0.3 (Release 2009a)
September 2009 Online onlyRevised for Version 2.0.4 (Release 2009b)
March 2010Online onlyRevised for Version 2.1 (Release 2010a)
Products Work Together
How Does Component Deployment Work?
Limitations of Support
Before You Use MATLAB
Your Role in the Java Application Deployment Process
What You Need to Know
Required Products
Configuring Your Environment
Quick Start: Deploying a Component with the Hello
World Example
About the Hello World Example
Before Running the Hello World Example
The Hello World Example
Building the Java Component
Deploying Hello World O n a Computer with MATLAB,
MATLAB
Installed
Deploying Hello World On a Computer with Only the
MATLAB Compiler Runtime (MCR) Installed (MATLA B
Not Installed)
®
Compiler Extension ......................1-2
®
Compiler and MATLAB®Builder JA
..........................1-2
.............1-3
.............................1-3
®
Builder JA...............1-4
...1-4
............................1-6
.................................1-7
......................1-7
..................................1-10
...................... 1-10
............. 1-10
........................... 1-10
....................... 1-11
®
Compiler, and MATLAB®Builder JA
....................................... 1-13
.................................. 1-14
Deploying a Component with the Magic Square
Example
About This Example
Magic Square Example: MATLAB Programmer Tasks
Magic Square Example: Java Programmer Tasks
Next Steps
........................................ 1-16
............................... 1-16
........................................ 1-36
... 1-16
....... 1-26
v
Writing Deployable MATLAB Code
2
The MATLAB Application Deployment Products .....2-2
Building Your Application w ith the Application
Deployment Products and the D e ploy ment Tool
What Is the Difference Between the Deployment Tool and
the mcc Command Line?
How Does MATLAB
Application?
What You Should Know About the Dependency Analysis
Function (depfun)
Compiling MEX-Files, DLLs, or Shared Lib rari es
The Role of the Component Technology File (CTF
Archive)
.......................................2-7
®
Compiler Software Build My
....................................2-4
...............................2-5
.........................2-4
.......2-6
....2-4
Guidelines for Writing Deployable MATLAB Code
Compiled Applications Do No t Process MATLAB Files at
Runtime
Do Not Rely on Changing Directory or Path to Control the
Execution of MATLAB Files
Use ismcc and isdeployed Functions To Execute
Deployment-Specific Code Paths
Gradually Refactor Applications That Depend o n
Noncompilable Functions
Do Not Create or Use Nonconstant Static State
Variables
Working with MATLAB Data Files Using Load and
Save
Using Load/Save Functions to Process MATLAB Data for
Deployed Applications
....................................... 2-10
....................... 2-11
................... 2-11
......................... 2-12
...................................... 2-12
............................................ 2-14
........................... 2-14
3
.... 2-10
Programming
viContents
About the MATLAB®Builder JA API ................3-3
Understanding the MATLAB®Builder JA API Data
Conversion Classes
Automatic Conversion to MATLAB Types
Understanding Function Signatures Generated by the
MATLAB
Adding Fields to Data Structures and Data Structure
Arrays
Returning Data from MATLAB to Java
®
Builder JA Product .....................3-5
........................................3-6
..............................3-3
..............3-4
................3-7
Importing Classes
Creating an Instance of the Class
What Is an Instance?
Code Fragment: Instantiating a Java Class
Passing Arguments to a nd from Java
Format
Manual Conversion of Data Types
Automatic Conversion to a MATLAB Type
Specifying Optional Arguments
Handling Return Values
Passing Java Objects by Reference
MATLAB Array
Wrappering and Passing Java Objects to MATLAB
Learning About Java Classes and Methods by E xploring
the Javadoc
................................... 3-62
..................................... 3-64
............................ 3-54
................... 3-54
............... 3-54
................................. 3-56
............................ 3-56
.......................... 3-57
................ 3-59
.......................... 3-61
............................. 3-61
................................. 3-61
viiiContents
Sample Java Applications
4
Plot Example ......................................4-2
Purpose
Procedure
.........................................4-2
........................................4-2
Spectral Analysis Example
Purpose
Procedure
Matrix Math Example
Purpose
MATLAB F unctions to Be Encapsulated
Understanding the getfactor Program
Procedure
Phonebook Example
Purpose
Procedure
Buffered Image Creation Example
Purpose
Procedure
Optimization E xample
Purpose
OptimDemo Component
Procedure
.........................................4-8
........................................ 4-10
......................................... 4-17
........................................ 4-19
............................... 4-29
......................................... 4-29
........................................ 4-29
......................................... 4-37
........................................ 4-37
......................................... 4-42
........................................ 4-43
.........................4-8
.............................. 4-17
............................. 4-42
............................ 4-42
............... 4-18
................. 4-19
.................. 4-37
Web A pplication Example
Example Overview
Before You Work this Example
Downloading the Demo Files
Build Your Java Component
Compiling Your Java Code
Generating the Web Archive (WAR) File
Running the Web Deployment Demo
Using the Web Application
................................ 4-53
.......................... 4-53
...................... 4-53
........................ 4-54
........................ 4-55
.......................... 4-55
.......................... 4-57
.............. 4-56
.................. 4-57
ix
Deploying a Java Component Over the Web
5
About the WebFigures Feature ......................5-2
Supported Renderers for WebFigures
.................5-2
Preparing to Implement WebFigures for MATLAB
Builder JA ......................................5-3
Your Role in the WebFigure Deployment Process
What You Need to Know to Implement WebFigures
Required Products
Assumptions About the Examples
Set DISPLAY on UNIX Systems
Quick Start: Implementing a Custom WebFigure
Overview
Setting Up the Web Server
Creating the Default WebFigure
Interacting with the Default WebFigure
Creating a Custom WebFigure
Advanced Configuration of a WebFigure
Overview
How Do WebFigures Work?
Installing WebFigureService
Getting the WebFigure Object from Your Method
Attaching a WebFigu re
Using the WebFigure JSP Tag to Reference a W ebFig u re
Getting an Embeddable String That References a
WebFigure Attached to a Cache
........................................5-9
........................................ 5-16
.................................5-5
....................5-7
.....................5-8
..........................5-9
..................... 5-10
............... 5-11
....................... 5-12
............. 5-16
......................... 5-18
........................ 5-19
............................. 5-21
.................... 5-26
®
........5-3
.....5-5
.....5-9
....... 5-20
.. 5-23
xContents
Working with MATLAB Figures and Images
6
Your Role in Working with Figures and Images ......6-2
Creating an d Modifying a MATLAB Figure
Preparing a MATLAB F igure for Export
...........6-3
...............6-3
Changing the Figure (Optional) ......................6-3
Exporting the Figure
Cleaning Up the Figure Window
Example: Modifying and Exporting Figure Data
...............................6-4
.....................6-4
........6-4
Working with MATLAB Figure and Image Data
For More Comprehensive Examples
Working with Figures
Working with Images
..............................6-6
..............................6-6
..................6-6
......6-6
Creating Scalable Web Applications Using RMI
7
Using Remote Method Invocation (RMI) .............7-2
Before You Use RMI
Running the Client an d Server on a Single Machine
Running the Client and Server on Separate
Machines
Using Native Java with Cell Arrays and Struct
Arrays
Why Use Native Type Cell Arrays and Struct Arrays?
Before You Use Native Type Data Marshalling with Cells
and Structs
TheNativeJavaCellandStructExample
.......................................7-8
..........................................7-9
...............................7-3
.................................... 7-10
............. 7-10
..7-4
....7-9
For More RMI Examples
........................... 7-16
xi
Reference Information for Java
8
Requirements for the MATLAB®Builder JA Product ..8-2
System Require ments
Path M odifications Required for Accessibility
Limitations and Restrictions
Settings for Environment Variables (Development
Machine)
......................................8-3
..............................8-2
...........8-2
........................8-3
Data Conversion Rules
Java to MATLAB Conversion
MATLAB to Java Conversion
Unsupported MATLAB Array Types
Programming Interfaces Generated by the MATLAB
Builder JA Product .............................. 8-12
APIs Based on MATLAB Function Signatures
Standard API
mlx API
Code Fragment: Signatures Generated for the myprimes
Example
MWArray Class Specification
..................................... 8-13
......................................... 8-15
....................................... 8-15
.............................8-8
........................8-8
........................ 8-10
.................. 8-11
....................... 8-17
Function Reference
9
®
.......... 8-12
xiiContents
Examples
A
Hello World (Quick Start) ..........................A-2
Magic Square
.....................................A-2
Using Load and Save ...............................A-2
Importing Classes
InstantiatingaJavaClass
Using MWNumericArray
Handling Data
Automatic Data Conversion
Calling MWArray Methods
Handling Errors
Handling Memory
Supplying Run-Time Configuration Information for
Parallel Computing Toolbox Applications
Ensuring a Consistent GUI Appearance
.................................A-2
..........................A-2
...........................A-2
.....................................A-2
........................A-3
..........................A-3
...................................A-4
.................................A-4
.........A-4
.............A-4
COM Components
Using waitForFigures to Block Execution of a Console
Application
Sample Applications (Java)
Working with WebFigures
Creating and Modifying a MATLAB Figure
Working with Figures
.................................A-4
.....................................A-5
.........................A-5
..........................A-5
...........A-5
..............................A-5
xiii
Working with Images ..............................A-6
Using RMI
........................................A-6
Index
xivContents
Getting Started
• “Product Overview” on page 1-2
®
• “Before You Use MATLAB
• “Quick Start: Deploying a Component with the Hello World Example” on
page 1-10
• “Deploying a Component with the Magic Square Example” on page 1-16
• “Next Steps” on page 1-36
Builder JA” on page 1-4
1
1 Getting Started
Product Overview
MATLAB Compiler Extension
MATLAB®Builder™ JA enables you to create Java™ classes from your
MATLAB® programs. These Java classes can be integrated into Java
programs and deployed royalty-free to desktop computers or Web servers
that do not have MATLAB installed.
When used with MATLAB Compiler™, the builder creates deployable
components that make MATLAB based computations, visualizations, and
graphical user interfaces accessib le to end users of the Java programs.
In this section...
“MATLAB®Compiler Extension” on page 1-2
“How the MATLAB®Compiler and MATLAB®Builder JA Products Work
Together” on page 1-2
“How Does Component Deployment W ork?” on page 1-3
“Limitations of Support” on page 1-3
1-2
When the Java program is deployed to the Web, multiple users can access it
through a Web browser.
The builder encrypts your MATLAB functions and generates a Java wrapper
around them so that they behave just like any other Java class. Java classes
created with MATLAB Builder JA are portable and run on all platforms
supported by MATLAB. See the Platform Roadmap for MATLAB
information.
For information about how MATLAB
Compiler Build Process” on page 1-23.
®
Compiler™ works, see “The MATLAB
®
for more
How the MATLAB Compiler and MATLAB Builder JA
Products Work Together
The MATLAB Compiler product can compile MATLAB files, MEX-files,
MATLAB objects, or other MATLAB code. The MATLAB Builder JA product
®
Product Overview
supports all the features of MATLAB, and adds support for Java™ classes,
Java objects (instances of a class), and methods. Using these products
together, you can generate the following:
• Standalone applications on UNIX
®
,Windows®, and Macintosh®platforms
• C and C++ shared libraries (dynamically linked libraries, or DLLs, on
Microsoft
®
Windows)
• Enterprise Java applications for use on any Java compatible platform
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 w h o seeks to use them
in writing a Java application.
• Deploying support for the components when they are accessed at run time
on an end-user machine.
To accomplish this kind of deployment, you must make sure that the
installer you create for the application takes care of supporting the Java
components on the target machine. In g eneral, this means the MCR must
be installed, on the target machine. You must also install the MATLAB
Builder JA component.
Note Java components created with the MATLAB Builder JA product are
dependentontheversionofMATLABwithwhichtheywerebuilt.
Limitations of Support
MATLAB Builder JA provides a wide variety of support for various Java
types and objects. However, MATLAB (MCOS) objects a re not supported as
inputs or outputs for compiled or deployed functions.
1-3
1 Getting Started
Before You U se MATLAB Builder JA
In this section...
“Your Role in the Java Application Deployment Process” on page 1-4
“What You Need to Know” on page 1-6
“Required Products” on page 1-7
“Configuring Your Environment” on page 1-7
Your Role in the Java Application Deployment Process
Depending on the size of your organization, you may play one role, or many,
in the process of successfully deploying a Java application.
For example, your job may be to analyze user requirements and satisfy them
by writing a program in MATLAB code. Or, your role may be to implement the
infrastructure needed to successfully deploy a Java application to the Web.
In smaller installations, you may find one person responsible for performing
tasks associated with multiple roles.
1-4
The table Application Deployment Roles, Tasks, and References on page 1-5
describes some of the diffe rent roles, or jobs, that MATLAB Builder JA users
typically perform and which tasks they would most likely perform when
running “Deploying a Component with the Magic Square Example” on page
1-16.
Before You Use MATLAB®Builder™ JA
Application Deployment Roles, Tasks, and References
RoleTasks
MATLAB prog rammer
• Understand
end-user business
requirements and
the mathematical
models needed to
support them.
• Write MATLAB code.
• Build an executable
component with
MATLAB tools
(usually with
support from a Java
programmer).
• Package the
component for
distribution to end
users.
• Pass the packaged
component to the
Java programmer
for rollout and
further integration
into the end-user
environment.
References
“Copying the Exam ple
Files” on page 1-18
“Testing the MATLAB
File You Want to
Deploy” on page 1-18
“Creating the
Magic Square Java
Component” on page
1-19
“Packaging the
Magic Square Java
Component (Optional)”
on page 1-21
“Copy the Package You
Created (Optional)” on
page 1-23
Java programmer
• Write Java code
to execute the
Java package built
by the MATLAB
programmer.
• Roll out the packaged
component and
integrate it into
“Gathering Files
Needed for
Deployment” on page
1-26
“Testing the Java
Component in a Java
Application” on page
1-27
1-5
1 Getting Started
Application Deployment Roles, Tasks, and References (Continued)
RoleTasks
the end-user
environment.
• Use the component
in enterprise Java
applications, adding
and modifying code
as needed.
• Address data
conversion issues
that may be
encountered,
according to the end
user’s specifications.
• Ensure the final Java
application executes
reliably in the end
user’s environment.
nal user
Exter
Execu
ted by MATLAB
crea
and J
te the solution
ava programmers.
References
“Distributing the
Component to End
Users” on page 1-32
“Integrating Java
Classes Generated
by MATLAB into a Java
Application” on page
1-33
“Calling Class Methods
from Java” on page 1-34
“Handle Data
Conversion as Needed”
on page 1-34
“Build and Test” on
page 1-35
Run th
appl
scop
edeployed
ication (outside the
e of this document).
1-6
What You Need to Know
The following knowledge is assumed when you use the MATLAB Builder
JA product:
• If your job function is MATLAB programmer, the following is required:
- A basic knowledge of MATLAB, and how to work with cell arrays and
structures
• If your job function is Java programmer, the following is required:
- Exposure to the Java programming language
- Object-oriented programming concepts
Before You Use MATLAB®Builder™ JA
Required Produc
You must install
chapter:
• MATLAB
• MATLAB Compil
• MATLAB Builde
the following products to run the example described in this
Configuring
Configure y
administra
be unnecess
for verifyi
our environment to work with the examples. Consult your system
tor or Java programmer before performing these tasks—some may
ary. Your administrator or programmer is often the best resource
ng, installing, or customizing your Java environment.
ts
er
rJA
Your Envi ron m e n t
VerifyingYourJavaEnvironment
You may al
you have J
MATLAB Bu
1 Open a co
2 Enter the command java -version. If Java is installed, the result looks
like this:
ready be running a compatible version of Java. To find out if
ava installed on your computer, and if it is compatible with the
ilder JA product:
mmand prompt.
java version "version_number"
Java(TM) 2 Runtime Environment, Standard Edition
(build
Java HotSpot(TM) Client VM
3 Enter the command javac -version.
Note Alternately, you may have to enter %JAVA_HOME%\bin\javac
-version
For information on locating environment v ariables, see “Setting Up Your
Java Environment” on page 1-8.
version_number.build_number
(build
if you have the user environment variable JAVA_HOME defined.
version_number.build_number, mixed mode)
1-7
1 Getting Started
If javac is installed, the results should look like this:
javac version_number
If java and javac are installed and the version numbers are at least 1.5, go to
“Deploying a Component with the Magic Square Example” on page 1-16. If
not, go to “Setting Up Your Java Environment” on page 1-8.
Setting Up Your Java Environment
1 Download and install the Java Developer’s Kit (JDK) from Sun
Microsystems™, Inc. if you do not yet have it installed.
The JDK is a collection of Java classes, run-time environment, compiler,
debugger, and usually source code, for a version of Java. The contents of
the JD K collectively make up a Java development environment.
The JDK includes the Java Runtime Environment (JRE), a collection of
compiled classes that makes up the Java virtual machine,astandalone
executor of the Java language, on a specific platform. Ensure your Java
Runtime Environment and JDK are compatible with the Sun Microsystems
JDK Version 1.6.0 before proceeding to the next step.
1-8
2 Set the environment variable JAVA_HOME.ThistellsJavawheretofindyour
installed JDK. from the MATLAB prompt. You can set
JAVA_HOME:
• On Windows platforms:
a Right-click the My Computer icon and select Properties.
b Click the Advanced tab.
c Click Environment Variables.
d In the User Variables area, click New.
e In the New User Variable dialog box, enter JAVA_HOME for Variable
name. Enter the absolute path name where your JDK is installed
for Variable value.Hereisthevalueofatypical
JAVA_HOME
environment variable:
C:\Program Files\Java\JDK1.6.0_03
Before You Use MATLAB®Builder™ JA
Note If JAVA_HOME already exists, select it and click Edit.Enterthe
path name where your JDK is installed.
f Click OK to accept changes.
• On UNIX platforms:
g Open a command prompt.
h Set JAVA_HOME as follows:
set JAVA_HOME=JDK_pathname
3 Verify that MATLAB is reading the correct value of JAVA_HOME.
a At the command prompt, type getenv JAVA_HOME.
b The response from MATLAB should be the path name you set to
JAVA_HOME in “Configuring Your Environment” on page 1-7. If not,
ensure the JDK that MATLAB is pointing to will be compatible to
run this example (at least Java Version 1.5). Consult your system
administrator if you are unsure.
1-9
1 Getting Started
Quick Start: Deploying a Component with the Hello World
Example
In this section...
“About the Hello World Example” on page 1-10
“Before R unning the Hello World Example” on page 1-10
“The Hello World Example” on page 1-10
“Building the Java Component” on page 1-11
“Deploying Hello World On a Computer with MATLAB, MATLAB
Compiler, a nd MATLAB®Builder JA Installed” on page 1-13
“Deploying Hello World On a Computer with Only the MATLAB Compiler
Runtime (MCR) Installed (MATLAB Not Installed)” on page 1-14
®
About th
This sec
For a mo
the Mag
Note T
-end interface to MATLAB Compiler software. For information about
front
how to
iler software, see the
Comp
t the Deployment Tool GUI from the command line, see the
star
rence page.
refe
oreRunningtheHelloWorldExample
Bef
ore running this example, configure your environment. See “Configuring
Bef
ur Environment” on page 1-7 .
Yo
e Hello World Example
Th
o write a function in MATL AB that displays the text
T
ou define the following function and save it as
y
eHelloWorldExample
tion gives a very brief example of MATLAB Builder JA functionality.
re extensive starter example, refer to “Deploying a Component with
ic Square Example” on page 1-16.
he examples here use the Windows
perform these tasks using the command-line interface to MATLAB
mcc reference page. For information about how to
deploytool GUI, a graphical
deploytool
hello world as output,
hello.m.
1-10
Quick Start: Deploying a Component with the Hello World Example
function hello
disp('hello, world');
Building the Java Component
You create a Java application by using the Deployment Tool GUI to build a
Java class that wraps around the sample MATLAB code discussed in “The
Hello World Example” on page 1-10.
To compile or build
hello using the Deployment Tool, use the following
information as you work through this example:
Project name
Class name
Package name
File to compile
helloprj
hellocls
hellopck
hello.m
Note When a component is built, the package name is the same as the
project name, by default. To change the package name, click the
Actions
icon and select Settings.
1 Start MATLAB.
2 Type deploytool at the comman d prompt and press Enter. The
deploytool GUI opens.
3 Crea
te a deployment project using the Deployment Project dialog:
a Type
thenameofyourprojectintheName field.
er the location of the project in the Location field. Alternately,
b Ent
igatetothelocation.
nav
ect the target for the deployment project from the Target drop-down
c Sel
nu.
me
ick OK.
d Cl
1-11
1 Getting Started
Creating a
4 On the Build tab:
Java Project
• If you are building a Java application, click Add class. Type the name
of the class in the Class Name field, designated by the letter “c”:
For this class, add files you want to compile by clicking Add files.To
add another class, click Add class.
Note You may optionally add supporting files. For examples of these
files, see the
deploytool Help. To add these files, in the Shared Resources
and Helper Files area:
a Click Add files/directories
b Click Open to select the file or files.
5 When you complete your changes, click the Build button ().
1-12
Quick Start: Deploying a Component with the Hello World Example
What Is a MATLAB Builder JA Project?
To use the MATLAB Builder JA product, you create a project, which specifies
theMATLABcodetobeusedinthecomponentsthatyouwanttocreate. This
product supports data conversion between Java types and MATLAB types.
For more about projects and their contents, see “Anatomy of a MATLAB
®
Builder JA Project” on page 1-20.
What Is a MATLAB Builder JA Component?
A component created by the MATLAB Builder JA product is a standalone
Java package (
.jar file). The package contains one or more Java classes that
encapsulate MATLAB code. The classes provide methods that are callable
directly from Java code.
Deploying Hello World On a Computer with MATLAB,
MATLAB Compiler, and MATLAB Builder JA Installed
Run H e llo World by entering the following from a system command shell.
1 Before proceeding, ensure you have renamed you package file to hellopck.
When a compon ent is built, the package name is the same as the project
name, by
and sel
2 Navigate to the directory containing the JAR file.
is the operating system and processor type of the local machine
Actions icon
Quick Start: Deploying a Component with the Hello World Example
Note The above command should be entered on one continuous line.
3 If you are running UNIX, set your system path appropriately. See
“Directories Required for Development and Testing” and “Directories
Required for Run-Time Deployment”.
1-15
1 Getting Started
Deploying a Com ponent with the Magic Square Example
In this section...
“About This Example” on page 1-16
“Magic Square Example: MATLAB Programmer Tasks” on page 1-16
“Magic Square Example: Java Programmer Tasks” on page 1-26
About This Example
In this section, you will step through an example of how a simple MATLAB
function can be transformed into a deployable MATLAB Builder JA
component.
The M agic Squa re example s hows you how to create a Java component named
magicsquare which contains the magic class, a .jar file, and other files
needed to deploy your application.
1-16
The class wraps a MATLAB function,
square. A magic square is a matrix containing any number of rows. These
rows, when added horizontally and vertically, equate to the same value.
MATLAB contains a function,
dimension. In this example, you will work with that function.
Note TheexampleshereusetheWindowsdeploytool GUI, a graphical
front-end interface to MATLAB Compiler software. For information about
how to perform these tasks using the command-line interface to MATLAB
Compiler software, see the
magic, that can create magic squares of any
mcc reference page.
makesqr, which computes a magic
Magic Square Example: MATLAB Programmer Tasks
The following tasks are usually performed by the MATLAB programmer.
Deploying a Component with the Magic Square Example
Key Tasks for the MATLAB Programmer
Task
Preparetoruntheexampleby
copying the MATLAB example files
Reference
“Copying the Example Files” on page
1-18
into a work folder.
TesttheMATLABcodetoensureit
is suitable for deployment.
CreateaJavapackage
(encapsulating yo ur MATLAB
“Testing the MATLAB File You
Want to Deploy” on page 1-18
“Creating the Magic Square Java
Component” on page 1-19
codeinaJavaclass)byrunningthe
Build function in
Run the Packaging Tool to bundle
your Java component with the
deploytool.
“Packaging the Magic Square Java
Component (Optional)” on page 1-21
additional files you selected.
Copy the output from the Packaging
Tool (the
distrib folder).
“Copy the Package You Created
(Optional)” on page 1-23
The Magic Square example shows you how to create a Java component
(
magicsquare), which contains the magic class, a .jar file (which includes the
.ctf archive described in “How Does the MATLAB
®
Builder JA Product Use
JAR Files?” on page 1-23), and other files needed to deploy your application.
The class encapsulates a MATLAB function,
makesqr, which computes a
magic square.
The client Java application,
makesqr to a native array and displays it on the screen. When you run the
getmagic application from the command line, you can pass the dimension for
getmagic.java converts the array returned by
the magic square as a command-line argument.
Note The examples for the MATLAB Builder JA product are in
matlabroot\toolbox\javabuilder\Examples. In most examples, Windows
syntax is featured (backslashes, instead of forward slashes). This example
assumes the work folder is on drive
D:.
1-17
1 Getting Started
Copying the Example Files
Preparetoruntheexamplebycopying needed files into your work area as
follows:
1 Navigate to
matlabroot\toolbox\javabuilder\Examples\MagicSquareExample.
matlabroot is the MATLAB root folder (where MATLAB is installed). To
find the value of this variable on your system, type
command prompt.
2 Copy the MagicSquareExample folder to a work area, for example,
D:\javabuilder_examples. Avoid using spaces in your folder
names, if possible. The example files should now reside in
D:\javabuilder_examples\MagicSquareExample.
3 Using a command prompt, navigate to D:\javabuilder_
examples\MagicSquareExample
cd \javabuilder_examples\MagicSquareExample.
by switching to the D: drive and entering
matlabroot at a
1-18
Testing the M ATLAB File You Want to Deploy
Normally you would first create the MATLAB file you w ant to deploy. In this
example, you will test a precreated MATLAB file (
predefined MATLAB function
function y = makesqr(x)
%MAKESQR Magic square of size x.
%Y = MAKESQR(X) returns a magic square of size x.
%This file is used as an example for the MATLAB
%Builder JA product.
%Copyright 2001-2008 The MathWorks, Inc.
y = magic(x);
2 At the command prompt, enter makesqr(5) and view the results. The
output should appear as follows:
makesqr.m)containingthe
Deploying a Component with the Magic Square Example
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Creating the Magic Square Java Component
You create the Magic Square Java application by using the Deployment Tool
GUI to build a Java class that wraps around the sample MATLAB code
discussed in “Testing the MATLAB File You Want to Deploy” on page 1-18.
Use the following information as you work through this example using the
instructions in “Building the Java Component” on page 1-11:
Project Name
Class Name
File to compile
magicsquare
magic
makesqr.m
What Hap p ens in the Build Process.
Note The MATLAB Builder JA product uses the JAVA_HOME variable to
locate the Java Softw are 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, the builder does the following:
Contains a Java class with
methods encapsulating the
MATLAB functions specified
in the project for that class.
mycomponentMCRFactory.java
Java component with first
character of
mycomponent
capitalzed.
myclassremote.java
Contains a remotable
Java class with methods
encapsulating the MATLAB
functions specified in the
project for that clas s.
See Chapter 7, “Creating
Scalable Web Applications
Using RMI”.
package-info.java
Javadoc package
documentation.
2 Compiles the Java code produced in step 1.
3 Generates /distrib and /src subfo lders.
4 Invokes the Jar utility to package the Java class files it has created into a
Java archive file (
mycomponent.jar).
1-20
For information about how MATLAB Compiler works, see “The MATLAB
®
Compiler Build Process” on page 1-23.
Anatomy of a MATLAB Builder JA Project. A builder project contains
information about the files and settings needed by the MATLAB Builder JA
product to create a deployable Java component. A project specifies information
about classes and methods, including the MATLAB functions to be included.
Classes and Methods
The builder transforms MATLAB functions that are specified in the
component’s p roject to methods belonging to a Java class.
Deploying a Component with the Magic Square Example
When creating a component, you must provide one or more class names as
well as a component name. The class name denotes the name of the class
that encapsulates MATLAB functions.
To access the features and operations provided by the MATLAB functions,
instantiate the Java class generated by the builder, and then call the methods
that encapsulate the MATLAB functions.
Note When you add files to a project, you do not have to add any MATLAB
files for functions that are called by the functions that you add. When the
MATLAB Builder JA product builds a component, it automatically includes
any MATLAB functions called by the functions that you explicitly specify for
the component. See “Spectral Analysis Example” on page 4-8 for a sample
application that illustrates this feature.
Naming Conventions
Typically you shou ld specify names for compone nts and classes that will be
clear to programmers who use your compon ents. For example, if you are
encapsulating many MATLAB functions, it helps to determine a scheme of
function categories and to create a separate class for each category. Also, the
name of each class should be descriptive of what the class does.
Valid characters are any alpha or numeric characters, as well a s the
underscore (
_) character.
Packaging the Magic Square Java Component (Optional)
Bundling the Java component with additional files into a JAR file that can
be distributed to users is called packaging. You will perform this step using
the packaging function of
distrib folder and the MCR Installer to a local folder of your choice. If you
are creating a shared component and want to include additional code with the
component, you must perform this step.
deploytool. Alternately, copy the contents of the
1-21
1 Getting Started
Note “Packaging”acomponentanda“Javapackage” are different concepts.
“Packaging” in this context refers only to the act of using MATLAB Builder
JA to bundle the Java component with associated files needed to successfully
deploy the application. A “Java package” is a collection of Java classes and
methods.
1 On the Package tab, add the MATLAB Compiler Runtime (the MCR) by
clicking Add MCR.
2 Next, add others files useful for end users. The readme.txt file contains
important information about others files useful for end users. To package
additional files or folders, click Add file/directories, select the file or
folder you want to package, and click Open.
3 In the Deployment Tool, click the Packaging button ().
1-22
4 On Window
other tha
distrib
Note Wh
VCREDS
of Micr
cations.
appli
What H
tes a self-extracting executable (on Windows platforms) or a
crea
forms other than Windows). The package contains at least the following:
plat
• The b
• The
• Doc
MCR Installer (if the Install MCR option was selected when the
ponent was built)
com
umentation generated by the Sun Microsystems Javadoc tool
s, the package is a self-extracting executable. On platforms
nWindows,itisa
.zip file. Verify that the contents of the
folder contains the files you specified.
en the self-extracting executable is uncompressed on a system,
IT_X86
is installed. VCREDSIT_X86 installs run-time components
osoft Visual C++ libraries necessary for running Visual C++
appens in the Packaging Process?. The packaging process
.zip fi le (on
uilder component
Deploying a Component with the Magic Square Example
Note For guidelines on multi-platform portability, reference “Ensuring
Multi-Platform Portability” on page 3-59.
How Does the MATLAB B u ilder JA Product Use JAR Files?. As of
R2007b, the MATLAB Builder JA product now embeds the CTF archive
within the generated JAR file, by default. This offers convenient deployment
of a single output file since all encrypted MATLAB file data is now contained
within this Java archive.
For information on CTF archive data extraction and utilization
using
MWComponentOptions see “Using MCR Component Cache and
MWComponentOptions” on page 3-61.
Copy the Package You Created (Optional)
Copy the package that you created from the distrib folder to the local folder
of your choice or send them directly to the J ava programmer..
TheMATLABCompilerBuildProcess
To generate and package an application, the use r:
1 Writes an application o r component in MATLAB
2 Invokes the MATLAB Compiler, which:
a Examines the input MATLAB files and the external dependency
database to determine the complete list of all functions used by the
application or component. As part of this p rocess, MATLAB Compiler
determines which files are not able to be compiled and automatically
excludes them.
b Determines which f u ncti ons are to be made publicly visible (for example,
those that can be called from another product or environment).
1-23
1 Getting Started
c Generates the appropriate interface code files based on the public
function list and the complete function list from the preceding steps. The
interface code g enerated is also dependent on what target the user wants
to create (for example, a Java component, a standalone executable, or a
Microsoft
d Packages compilable functions into a CTF archive, creating a file on the
®
Excel®add-in).
user’s disk. This archive is embedded by default in the binary executable.
e Optionally, invokes target specific compiler to generate a binary
application or component from the files in C and the interface code
libraries provided by The MathWorks.
3 Locates the install package for the MATLAB Compiler Runtime (MCR).
4 Collects together the binary, the C TF archive, and the MCR installer (along
with other optional, user-specified files) for the user.
The deployment GUI (
deploytool) automates many o f the steps in the
process for user convenience.
1-24
Deploying a Component with the Magic Square Example
1-25
1 Getting Started
Magic Square Exa
The following ta
Key Tasks for th
Task
Ensure you have the needed files
from the MATLAB Programmer
before proceeding.
TesttheJavacodebyusingitina
Java application. Compile and run
the component to ensure it produces
the same results as your MATLAB
code.
Archive and distribute the output to
end users.
Import c
MATLAB B
existi
Use bui
enhan
Address potential data conversion
issues with differing data types.
lasses generated by the
ng Java applications.
lt-in Java c la ss methods to
ce your Java application.
sks are usually performed by the Java programmer.
e Java Programmer
uilder JA product into
mple: Java Programmer Tasks
Reference
“Gathering Files Needed for
Deployment” on page 1-26
“Creating the Magic Square Java
Component” on page 1-19
“Distributing the Component to End
Users” on page 1-32
“Integrating Java Classes G ene rated
by MATLAB into a Java Application”
on page 1-33
“Calling Class Methods from Java”
on page 1-34
“Handle Data Conversion as Needed”
on page 1-34
1-26
Verify your Java application works
as expected in your end user’s
deployment environment.
“Build an d Test” on page 1-35
Gathering Files Needed for Deployment
fore beginning, verify you have access to the following files, created by the
Be
TLAB P rog ram mer in “Copy the Package Yo u Created (Optional)” on page
CR Installer. For locations of the MCR Installer, run the
• M
ommand.
c
mcrinstaller
Deploying a Component with the Magic Square Example
• Javadoc documentation
readme.txt file
•
See “Packaging the Magic Square Java Component (Optional)” on page
1-21 for more information about these files. You will also want to
communicate the location of
com.mathworks.toolbox.javabuilder
(matlabroot\toolbox\javabuilder\jar\javabuilder.jar). You can
browse the API Javadoc for
com.mathworks.toolbox.javabuilder from the
MATLAB Help.
Testing the Java Component in a Java Application
Before deploying the created component, you need to verify that it can be used
in a Java application successfully.
First, create a small Java program that uses the component created for
your by the MATLAB Programmer (see “Packaging the Magic Square Java
Component (Optional)” on page 1-21 ). The example provides a sample
Java program that accomplishes this (
com.mathworks.toolbox.javabuilder) and uses one of the
magicsquare package you created
MATLAB Builder JA conversion classes to convert the number p assed to the
program on the command line into a type that can be accepted by MATLAB,
in this case a scalar double value.
The program then creates an instance of class
magic,andcallsthemakesqr
method on that object. Note how the MATLAB file becomes a method of
the Java class that encapsulates it. As explained in “Testing the M ATLAB
File You Want to Deploy” on page 1-18, the
square using the MATLAB
magic function. The source code of getmagic.java
makesqr method computes the
follows, for your reference:
/* getmagic.java
* This file is used as an example for the MATLAB
* Builder JA product.
*
* Copyright 2008 The MathWorks, Inc.
D:\javabuilder_examples\MagicSquareExample as noted previously in this
example. Then, do the following:
1 Compile the Java component with the Java compiler, javac.Atthe
command prompt, enter one of the following commands. When entering
these commands, ensure they are entered as one continuous command. On
Windows systems, the semicolon (
systems, the colon (
If you bundled the component as a self-extracting executable, paste it in a
folder on the development machine, and run it. If you are using a
bundled with WinZip, unzip and extract the contents to the development
machine.
.zip file
Deploying a Component with the Magic Square Example
Integrating Java Clas ses Generated by MATLAB into a Java
Application
If y ou are implementing your Java component on a computer other than the
one on which it was built:
1 Install the MATLAB Compiler Runtime on the target system. See
“Deployment Process” in the MATLAB Compiler documentation.
2 Consult the Javadoc for information on classes generated by MATLAB
classes. Reference the Javadoc from the MATLAB Builder JA product
roadmap.
3 To integrate the Java class generated by MATLAB Builder JA,software
both the component and the MWArray API need to be imported in the Java
code. Import the MATLAB libraries and the component classes into your
code with the Java
componentname.classname; or import componentname.*;
import function. For example:
For more information, see Chapte r 3, “Programming”.
4 As with all Java classes, you must use the new function to create an
instance of a class. To create an object (
theMagic)fromthemagic class,
the example application uses the following code:
theMagic = new magic();
For more information, see Chapte r 3, “Programming”.
5 To conserve system resources and optimize performance, it is g ood practice
to get in the habit of destroying any instances of classes that are no longer
needed. For example, to dispose of the object
theMagic,usethefollowing
code:
theMagic.dispose();
/* Make it eligible for garbage collection */
theMagic = null;
For more information, see Chapter 3, “Programming”, in particular, “Using
the dispose Method” on page 3-41.
1-33
1 Getting Started
Calling Class Methods from Java
After you have instantiated the class, you can call a class method as you
would with any Java object. In the Magic Square example, the
method is called as shown:
result = theMagic.makesqr(1, n);
Here n is an instance of an MWArray class. Note that the first argument
expresses number of outputs (
(
n).
1) and succeeding arguments represent inputs
makesqr
See the following code fragment for the declaration of
n = new MWNumericArray(Double.valueOf(args[0],
MWClassID.DOUBLE);
n:
Note The MATLAB Builder JA product provides a rich AP I for integrating
the generated components. D etai led exa m p les an d complete listings of input
parameters and possible thrown exceptions can be found in the Javadoc,
available from thethe MATLAB Builder JA roadmap.
Handle Data Conversion as Needed
When you invoke a method on a builder component, the input parameters
received by the method must be in the MATLAB internal array format. You
can either (manually) convert them yourself within the calling program, or
pass the parameters as Java data types.
• To manually convert to one of the standard MATLAB data types, use
MWArray classes in the package
• IfyoupassthemasJavadatatypes,they are automatically converted.
How MATLAB Builder JA Handles Data. To enable Java
applications to exchange data with MATLAB methods they
invoke, the 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. EachclassrepresentsaMATLABdatatype.
com.mathworks.toolbox.javabuilder.
1-34
Deploying a Component with the Magic Square Example
For m ore detailed information on data handling within the
product and programming with the
com.mathworks.toolbox.javabuilder.MWArray Javadoc and “About the
MATLAB
®
Builder JA API” on page 3-3.
MWArray package, see the
Build and Test
Build and test the Java application as you would any application in your end
user’s environment. Build on what you’ve created by working with additional
classes and methods.
After you create and distribute the initial application, you will want to
continue to enhance it. Details about some of the more common tasks you will
perform as you develop your application are listed in the chapters described in
“Next Steps” on page 1-36.
Running a 64-Bit Mac Application
Before you run a 64-bit Macintosh application, you need to use the the
Macintosh Application Launcher. See “Running Your 64-Bit M ac Application”
in the MATLAB Compiler User Guide for more information.
See “Using MATLAB Compiler on UNIX” in the MATLAB Compiler User
Guide for complete information about bu ilding, deploying, and testing UNIX
applications with MATLAB Compiler.
1-35
1 Getting Started
Next Steps
Writing Java applications that
can access Java methods that
encapsulate MATLAB code
Sample applications that access
methods developed in MATLAB
Deploying Ja
Web
Reference information about
automatic data conversion rules
va components over the
Chapter 3, “Programming”
Chapter 4, “Sample Java
Applications”
Chapter 5, “Deploying a Java
Component Over the Web”
Chapter 8, “Reference Information
for Java”
1-36
WritingDeployable
MATLAB Code
• “The MATLAB Application Deployment Products” on page 2-2
• “Building Your Application with the Application Deployment Products and
the Deployment Tool” on page 2-4
• “Guidelines for Writing Deployable M ATLA B Code” on page 2-10
• “Working with MATLAB Data Files Using Load and Save” on page 2-14
2
2 Writing Deployable MATLAB
®
Code
The MATLAB Application Deployment Products
The MATLAB S
Product
MATLAB
Compiler
MATLAB
Builder NE
MATLAB
Builder JA
MATLAB expert
No IT experience
MATLAB
Programmer
The followin
No access to IT systems
g tables summarizes the target applications supported by each
product.:
uite of Applic ation Deployment Products
Target
CandC++
Create
Standalone
Executables?
Create
Function
Libraries?
YesYesYesNo
standalones
and libraries
C# .NET
NoYesYesYes
components
Visual
Basic COM
components
Java
NoYesYesYes
components
Develops model
Uses the builder tools to create a
component that is given to the
business service developer
Create
Applications
Create Web
Applications?
with
Graphics?
2-2
MATLAB
Builder EX
Microsoft
Excel add-ins
NoYesYesNo
The MATLAB®Application Deployment Products
The MATLAB®Application Deployment Products
Each of the builder products uses the MATLAB Compiler core code to create
deployable components.
2-3
2 Writing Deployable MATLAB
®
Code
Building Your Application with the Application Deployment
Products and the
In this section...
“What Is the Difference Between the Deployment Tool and the mcc
Command Line?” on page 2-4
“How Does MATLAB®Compiler Software Build My Application?” on page
2-4
“What You Should Know About the Dependency Analysis Function
(depfun)” on page 2-5
“Compiling MEX-Files, DLLs, or Shared Libraries” on page 2-6
“The Role of the Component Technology File (CTF Archive)” on page 2-7
Deployment Tool
What Is th
and the m
Using th
would i
Deploy
custom
the sa
Using
• Perf
• Main
• Pac
Ho
Ap
MA
nvoke using the MATLAB Compiler
ment Tool interactive menus and dialogs build
ized to your specification. As such, your MATLAB code is processe d
me way as if you were compiling it using
the Deployment Tool, you:
orm related deployment tasks with a single intuitive GUI.
tain related information in a convenient project file. Your project
e persists between sessions. Your previous project loads automatically
stat
n the Deployment Tool starts. You load previously stored compiler
whe
jects from a prepopulated menu.
pro
kage applications for distribution.
w Does MATLAB C ompiler Software Build My
plication?
TLAB Compiler software:
e Difference Between the Deployment Tool
cc Command Line?
e D eploym ent Tool (
deploytool) GUI, you perform any function you
mcc command-line interface. The
mcc commands that are
mcc.
2-4
Building Your Application with the Application Deployment Products and the Deployment Tool
1 Parses command-line arguments and classifies by type the files you provide.
2 Analyzes files for dependencies using the Dependency Analysis Function
(
depfun). Dependencies affect deployability and originate from file
contents—functions called by the file. Deployability is affected by:
• File type — MATLAB, Java, MEX, and so on.
• File location — MATLAB, MATLAB toolbox, user code, and so on.
• File deployability — Whether the file is deployable outside of MATLAB
For more information about
depfun, see “What You Should Know About
the D ependency Analysis Function (depfun)” on page 2-5.
3 Validates MEX-files. In particular, mexFunction entry points are verified).
For more details about MEX-file processing, see “Compiling MEX-Files,
DLLs, or Shared Libraries” on page 2-6.
4 Creates a CTF archive from the input files and their dependencies.
For more details about CTF archives see “The Role of the Component
Technology File (CTF Archive)” on page 2-7.
5 Generates target-specific wrapper code. For example, the wrapper for a C
main function is very different than the wrapper for a Java interface class.
6 Invokes a third-party target-specif ic compiler to create the appropriate
binary software com ponent (a standalone executable, a Java JAR file,
and so on).
For details about how MATLAB Compiler software builds your deployable
component, see “The MATLAB
®
Compiler Build Process” on page 1-23.
What You Should Know About the Dependency
Analysis Function (depfun)
MATLAB Compiler uses a dependency analysis function (depfun)to
determine the list of necessary files to include in the CT F package. In some
cases, this process includes an large number of files. This is often true when
MATLAB object classes exist in the compilation and
overloaded methods at compile time. Dependency analysis also processes
include/exclude files on each pass (see the mcc flag “-a Add to Archive”).
depfun cannot resolve
2-5
2 Writing Deployable MATLAB
Tip To improve compile time performance and lessen application size, prune
the path with “-N Clear Path”, “-p Add Directory to Path”, or by specifying
Toolboxes on Path in the
depfun searches for executable content such as:
• MATLAB files
• P-files
®
Code
deploytool Settings
• Java classes and
.fig files
•
.jar files
• MEX-files
depfun does not search for data files of any kind (except MAT files). You
must manually
include data files.
Compiling MEX-Files, DLLs, or Shared Libraries
When you compile MATLAB functions containing MEX-files, ensure
that
depfun can find them—doing so allows you to avoid many common
compilation problems. In particular, note that:
•
depfun cannot examine MEX-files, DLLs, or shared libraries to determine
their dependencies. Explicitly include all binaries these files require
either with the
Deployment Tool unde r Settings.
• If you have any doubts that
a MEX-file, DLL, or shared library—manually include it. Do this with
either the
the Deployment Tool under Settings.
• Not all functions are compatible with MATLAB Compiler. Check the file
mccExcludedFiles.log after your build completes. This file lists all
functions called from your application that you cannot deploy.
mcc -a option or the options on the Advanced tab in the
depfun can find a MATLAB function called by
mcc -a option or by using the options on the Advanced tab in
2-6
Building Your Application with the Application Deployment Products and the Deployment Tool
TheRoleoftheComponentTechnologyFile(CTF
Archive)
Each application or shared library produced by MATLAB Compiler has an
associated Component Technology File (CTF) archive. The archive contains
all the MATLAB based content (MATLAB files, MEX-files, and so on)
associated with the compo ne nt.
MATLAB Compiler also embeds a CTF) archive in each generated binary.
The CTF houses all deployable files. All MATLAB files encrypt in the CTF
archive using the Advanced Encryption Standard (AES) cryptosystem .
If you choose the extract the CTF archive as a separate file the files remain
encrypted. For more information on how to extract the CTF archive refer to
the references in the following table.
Information on CTF Archive Embedding/Extraction and Component
Cache
Product
MATLAB Compiler“Overriding Default CTF Archive
MATLAB Builder NE“Overriding Default CTF Archive
MATLAB Builder JA“Using M CR Component Cache and
MATLAB Builder EX“Overriding Default CTF Archive
Refer to
Embedding Using the MCR
Component Cache”
Embedding for Components Using
the MCR Component Cache”
MWComponentOptions” on page
3-61
Embedding for Components Using
the MCR Component Cache”
2-7
2 Writing Deployable MATLAB
®
Code
2-8
Building Your Application with the Application Deployment Products and the Deployment Tool
Additional Details
Multiple CTF archives, such as those generated with C OM, .NET, or Excel
components, can coexist in the same user application. You cannot, however,
mix and match the MATLAB files they contain. You cannot combine
encrypted and compressed MATLAB files from multiple CTF archives into
another CTF archive and distribute them.
All the M ATLA B files from a given CTF archive associate with a unique
cryptographic key. MATLAB files with different keys, placed in the same
CTF archive, do not execute. If you want to generate another application
with a different mix of MATLAB files, recompile these MATLAB files into a
new CTF archive.
MATLAB Compiler deleted the CTF archive and generated binary following
a failed compilation, but only if these files did not exist before compilation
initiates. Run
Caution Release Engineers and Software Configuration Managers:
Do not use build procedures or processes that strip shared libraries on CTF
archives. If you do, you can possibly strip the CTF archive from the binary,
resulting in run-time errors for the driver application.
help mcc -K for more information.
®
2-9
2 Writing Deployable MATLAB
®
Code
Guidelines for Writing Deployable MATLAB Code
In this section...
“Compiled Applications Do Not Process MATLAB Files at Runtime” on
page 2-10
“Do Not Rely on Changing Directory or Path to Control the Execution of
MATLAB Files” on page 2-11
“Use ismcc and isdeployed Functions To Execute Deployment-Specific Code
Paths” on page 2-11
“Gradually Refactor Applications That Depend on Noncom pilable
Functions” on page 2-12
“Do Not Create or Use Nonconstant Static State Variables” on page 2-12
Compiled Applications Do Not Process MATLAB Files
at Runtime
The MATLAB Compiler was designed so that you can deploy locked down
functionality. Deployable MATLAB files are suspended or frozen at the
time MATLAB Compiler encrypts them—they do not change from that point
onward. This does not mean that you cannot deploy a flexible application—it
means that you must design your application with flexibility in mind.Ifyou
want the end user to be able to choose between two different methods, for
example, they both must be compiled in.
2-10
The MCR only works on MATLAB code that was encrypted when the
component was built. Any function or process that dynamically generates
new MATLAB code will not work against the MCR.
Some MATLAB toolboxes, such as the Neural Network Toolbox™ product,
generate MATLAB code dynamically. Because the MCR only executes
encrypted MATLAB files, and the Neural Network Toolbox generates
unencrypted MATLAB files, some functions in the Neural Network Toolbox
cannot be deployed.
Similarly, functions that need to examine the contents of a MATLAB function
file cannot be deployed.
HELP, for example, is dynamic and not available in
Guidelines for Writing Deployable MATLAB®Code
deployed mode. You can use LOADLIBRARY in deployed mode if you provide
it with a MATLAB function prototype.
Instead of compiling the function that generates the MATLAB code and
attempting to deploy it, perform the following tasks:
1 Run the code once in MATLAB to obtain your generated function.
2 Compile the MATLAB code with MATLAB Compiler, including the
generated function.
Tip Another alternative to using EVAL or FEVAL is using anonymous function
handles.
If you require the ability to create MATLAB code for dynamic runtime
processing, your end-users must have an installed copy of MATLA B.
Do Not Rely on Changing Director y or Path to Control
the Execution of MATLAB Files
In general, good programming practices advise against redirecting a program
search path dynamically within the code. Many programmers are prone
to this behavior since it mimics the actions they usually perform on the
command line. However, this can lead to problems when deploying code.
For example, in a deployed application, the MATLAB and Java paths are
fixed and cannot change. Therefore, any attempts to change these paths
(using the
If you find you cannot avoid placing
ismcc and isdeployed. See the next section for details.
cd command or the addpath command) fails
addpath calls in your MATLAB code, use
Use ismcc and isdeployed Functions To Execute
Deployment-Specific Code Paths
The isdeployed function allows you to specify which portion of your MATLAB
code is deployable, and which is not. Such specification minimizes your
compilation errors and helps create m ore efficient, maintainable code.
2-11
2 Writing Deployable MATLAB
For example, you find it unavoidable to use addpath when writing your
startup.m.Usingismcc and isdeployed, you specify when and what is
compiled and executed.
®
Code
For an example of using
a Standalone Application”.
isdeployed, see “Passing Arguments to and from
Gradually Refactor Applications That Depend on
Noncompilable Functions
Over time, refactor, streamline, and modul ari ze MATLAB code containing
non-compilable or non-deployable functions that use
Your eventual goal is “graceful degradation” of no n-deploya ble code. In
other words, the code must present the end user with as few obstacles to
deployment as possible until it is practically eliminated.
Partition your code into design-time and run-time code sections:
• Design-time code is code that is currently evolving. Almost all code goes
through a phase of perpetual rewriting, debugging, and optimization. In
some toolboxes, such as the Neural Network Toolbox product, the code goes
through a period of self-training as it reacts to various data permutations
and patterns. Such code is almost never designed to be deployed.
• Run-time code, on the other hand, has solidified or become stable—it is in a
finishedstateandisreadytobedeployedbytheenduser.
Consider creating a separate directory for code that is not meant to be
deployed or for code that calls undeployable code.
ismcc and isdeployed.
2-12
Do Not Create or Use Nonconstant Static State
Variables
Avoid using the following:
• Global variables in MATLAB code
• Static variables in MEX-files
• Static variables in Java code
Guidelines for Writing Deployable MATLAB®Code
The state of these variables is persistent and shared with everything in the
process.
Persistent variables can cause problems because the MCR process runs in a
single thread. You cannot load more than one of these non-constant, static
variables into the same process. In addition, these static variables do not
work well in multithrea ded applications.
If you must u se static variables, bind them to instances. For example,
defining instance variables in a Java class is preferable to defining the
variable as
static.
Note This guideline does not apply to MATLAB Builder EX customers.
When programming with Microsoft Excel, you can assign global variables to
large matrices that persist between calls.
2-13
2 Writing Deployable MATLAB
®
Code
Working with MATLAB Data Files Using Load and Save
If you r deployed application uses MATLAB data files (MAT-files), it is helpful
to code
processing.
LOAD and SAVE functions to manipulate the data and store it for later
• Use
• Specify the data file by full path name or relative to
• All MAT-files are unchanged after
For more information about C TF archives, see “The Role of the Component
Technology File (CTF Archive)” on page 2-7.
Use the following example as a template for manipulating your MATLAB
data inside, and outside, of MATLAB.
isdeployed to determine if your code is running in or out of the
MATLAB workspace.
ctfroot.
mcc runs. These files are not encrypted
when written to the CTF archive.
Using Load/Save Functions to Process MATLAB Data
for Deployed Applications
The following example specifies three MATLAB data files:
•
user_data.mat
• userdata/extra_data.mat
• ../externdata/extern_data.mat
Compile ex_loadsave.m with the following mcc command:
2-14
mcc -mvC ex_loadsave.m -a 'user_data.mat' -a
'./userdata/extra_data.mat' -a
'../externdata/extern_data.mat'
loadsave.m
ex_
function ex_loadsave
Working with MATLAB Data Files Using Load and Save
% This example shows how to work with the
% "load/save" functions on data files in
% deployed mode. There are three source data files
% in this example.
%user_data.mat
%userdata/extra_data.mat
%../externdata/extern_data.mat
%
% Compile this example with the mcc command:
%mcc -mC ex_loadsave.m -a 'user_data.mat' -a
%'./userdata/extra_data.mat'
%-a '../externdata/extern_data.mat'
% All the folders under the current main MATLAB file directory will
%be included as
% relative path to ctfroot; All other folders will have the
%folder
% structure included in the ctf archive file from root of the
%disk drive.
%
% If a data file is outside of the main MATLAB file path,
%the absolute path will be
% included in ctf and extracted under ctfroot. For example:
To access a Java component built and packaged by the MATLAB Builder JA
product, you must first unpackage and install components so you can use
them on a particular machine. See Chapter 1, “Getting Started” for more
information.
3
• “About the MATLAB
• “Importing Classes ” on page 3-8
• “Creating an Instance of the Class” on page 3-9
• “Passing Arguments to and from Java” on page 3-13
• “Passing Java O b jects by Reference” on page 3-27
• “Handling Errors” on page 3-34
• “Managing Native R esources” on page 3-40
• “Improving Data Access Using the MCR User Data Interface and
MATLAB
• “Dynamically Specifying Run-Time Options to the MCR” on page 3-49
• “Handling Data Conversion Between Java and MATLAB” on page 3-52
• “Setting Java Properties” on page 3-54
• “Blocking Execution of a Console Application that Creates Figures” on
page 3-56
• “Ensuring Multi-Platform Portability” on page 3-59
• “Using MCR Component Cache and MWComponentOptions” on page 3-61
• “Learning About Java Classes and Methods by Exploring the Javadoc”
on page 3-64
®
Builder JA” on page 3-44
®
Builder JA API” on page 3-3
3 Programming
Note For examples of these tasks, see Chapter 4, “Sample Java Applications”.
For information about deploying your application after you complete these
tasks, see “How Does Component Deployment Work?” on page 1-3.
3-2
About the MATLAB Builder JA API
In this section...
“Understanding the MATLAB®Builder JA API Data Conversion Classes”
on page 3-3
“Automatic Conversion to MATLAB Types” on page 3-4
“Understanding Function Signatures Generated by the MATLAB®Builder
JA Product” on page 3-5
“Adding Fields to Data Structures and Data Structure Arrays” on page 3-6
“Returning Data from MATLAB to Java” on page 3-7
Understanding the MATLAB Builder JA API Data
Conversion Classes
When writing your Java application, you can represent your data using
objects of any of the data conversion classes. Alternativ ely , you can use
standard Java data types and objects.
About the MATLAB®Builder™ JA API
The data conversion classes are built as a class hierarchy that represents the
major MATLAB array types.
Note This discussion provides conceptual information about the classes.
For details, see
“Documentation Set”.
This discussion assumes you have a working knowledge of the Java
programming language and the Java Software Developer’s Kit (SDK). This
is not intended to be a discussion on how to program in Java. Refer to the
documentation that came with your Java SDK for general programming
information.
com.mathworks.toolbox.javabuilder in the product
3-3
3 Programming
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
major MATLAB types:
MWCellArray,andMWStructArray.
Each subclass stores a reference to a native MATLAB array of that type.
Each class provides constructors and a basic set of m ethods for accessing
the underlying array’s propertiesanddata. Tobespecific,
classes derived from
• Constructors and finalizers to instantiate and dispose of MATLAB arrays
•
get and set methods to read and write the array data
• Methods to identify properties of the array
• Comparison methods to test the equality or order of the array
• Conversion methods to convert to other data types
MWArray class has the following subclasses representing the
MWNumericArray, MWLogicalArray, MWCharArray,
MWArray and the
MWArray provide the following:
3-4
Advantage of Using Data Conversion Classes
The MWArray data conversion classes let you pass native type parameters
directly without using explicit data conversion. If you pass the same array
frequently, you might improve the performance of your program by storing
thearrayinaninstanceofoneofthe
MWArray subclasses.
Automatic Conversion to MATLAB Types
Note Because the conversion process is a utomatic (in most cases), you do not
need to understand the conversion process to pass and return arguments with
MATLAB Builder JA components.
When you pass an MWArray instance as an input argumen t, the encapsulated
MATLABarrayispasseddirectlytothemethodbeingcalled.
In contrast, if your code uses a native Java primitive or array as an input
parameter, the builder converts it to an instance of the appropriate
MWArray
About the MATLAB®Builder™ JA API
class before it is passed to the method. The builder can convert any Java
string, numeric type, or any multidimensional array of these types to an
appropriate
Conversion Rules” on page 8-8 for a list of all the data types that are
supported along with their equivalent types in MATLAB.
The conversion rules apply not only when calling your own methods, but
also when calling constructors and factory methods be longing to the
classes.
Note There are some data types commonly used in M ATLAB that are
not available as native Java types. Examples are cell arrays and arrays of
complex numbers. Represent these array types as instances of
and MWNumericArray,respectively.
MWArray type, using its data conversion rules. See “Data
MWArray
MWCellArray
Understanding Function Signatures Generated by the
MATLAB Builder JA Product
The Java programming language now supports optional function arguments
in the way that MATLAB does with
feature of MATLAB, the builder generates a single overloaded Java method
that accommodates any number of input arguments. This behavior is an
enhancement over previous versions of
limited number of arguments.
varargin and varargout.Tosupportthis
varargin supportthatonlyhandleda
Note In addition to handling optional function arguments, the overloaded
Java methods that wrap MATLAB functions handle data conversion. See
“Automatic Conversion to MATLAB Types” on page 3-4 for more details.
Understanding MATLAB Function Signatures
As background, recall that the generic MATLAB function has the following
structure:
function [Out1, Out2, ..., varargout]=
foo(In1, In2, ..., varargin)
3-5
3 Programming
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. When you include the
or varargout argument, you can specify any number of inputs or outputs
beyond the ones that are explicitly declared.
varargin
Overloaded Methods in Java That Encapsulate MATLAB Code
When the MATLAB Builder JA product encapsulates your MA TLAB code, it
creates an overloaded method that implements the MATLAB functions. This
overloaded method corresponds to a call to the generic MATLAB function for
each combination of the possible number and type of input arguments.
In addition to encapsulating input arguments, the builder creates another
method, which represents the output arguments, or return values, of the
MATLAB function. This additional overloaded method takes care of return
values for the encapsulated MATLAB function. This method of encapsulating
the information about return values simulates the
MATLAB Compiler product.
These overloaded methods are called the standard interface (encapsulating
input arguments) and the
“Programming Interfaces Generated by the MATLAB
on page 8-12 for det ails.
mlx interface (encapsulating return values). See
mlx interface in the
®
Builder JA Product”
Adding Fields to Data Structures and Data Structure
Arrays
When adding fields to data structures and data structure arrays, do so
using standard programming techniques. Do not use the
shortcut.
set command as a
3-6
For examples of how to correctly add fields to data structures and data
structure arrays, see the programming examples in Chapter 4, “Sample Java
Applications”.
About the MATLAB®Builder™ JA API
ReturningDatafromMATLABtoJava
All data returned from a method coded in MATLAB is passed as an instance
of the appropriate
returned to the Java application as an
Return data is not convertedtoaJavatype. IfyouchoosetouseaJavatype,
you must convert to that type using the
subclass to which the return data belongs.
MWArray subclass. For example, a MATLAB cell array is
MWCellArray object.
toArray method of the MWArray
3-7
3 Programming
Importing Classes
To use a component generated by the MATLAB Builder JA product:
1 Import MATLAB libraries with the J ava import function, for example:
import com.mathworks.toolbox.javabuilder.*;
2 Import the component classes created by the builder, for example:
import com.mathworks.componentname.classname;
Tip It is important to note the difference between the component and the
package n ames. T he component name is the last part of the full package
name, and is what is used in the .JAR file (and the embedded CTF file within
the JAR). For example, in
hello.m
com.mathworks.demos.Theimport statement should include the full
package name:
, the component name is demos and the package name is
import com.mathworks.demos.HelloDemo;
mcc -W java:com.mathworks.demos.HelloDemo
3-8
Note When you use the MATLAB Builder JA product to create classes,
you must create those classes on the same operating system to which you
are deploying them for development (or for use by end users running an
application). For example, if your goal is to deploy an application to end users
to run on Windows, you must create the Java classes w ith the MATLAB
Builder JA product running on Windows.
The reason for this limitation is that although the
platform independent, the
.jar file is dependent on the embedded .ctf file,
which is intrinsically platform dependent. It is possible to make your
.jar file itself might be
.ctf file
platform independent in certain circumstances; see “Ensuring Multi-Platform
Portability” on page 3-59 for more details.
Creating an Instance of the Class
In this section...
“What Is an Instance?” on page 3-9
“Code Fragm ent: Instantiating a Java Class” on page 3-9
What Is an Instance?
As with any Java class, you need to instantiatetheclassesyoucreatewiththe
MATLAB Builder JA product before you can use them in your program.
Creating an Instance of the Class
Suppose you build a component named
MyClass. Here is an example of creating an instance of the MyClass class:
MyClass ClassInstance = new MyClass();
MyComponent with a class named
Code Fragment: Instantiating a Java Class
The following Java code shows how to create an instance of a class that
was built with MATLAB Builder JA. The application uses a Java class that
encapsulates a MATLAB function,
/*
* usemyclass.java uses myclass
*/
/* Import all com.mathworks.toolbox.javabuilder classes */
import com.mathworks.toolbox.javabuilder.*;
/* Import all com.mycompany.mycomponent classes */
import com.mycompany.mycomponent.*;
/*
* usemyclass class
*/
public class usemyclass
{
/** Constructs a new usemyclass */
public usemyclass()
myprimes.
3-9
3 Programming
{
super();
}
/* Returns an array containing the primes between 0 and n */
public double[] getprimes(int n) throws MWException
{
myclass cls = null;
Object[] y = null;
try
{
cls = new myclass();
y = cls.myprimes(1, new Double((double)n));
return (double[])((MWArray)y[0]).getData();
}
catch (MWException e) {
// something went wrong while
//initializing the component - the
//MWException's message contains more information
}
3-10
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.
The following statement instantiates the class
cls = new myclass();
myclass:
Creating an Instance of the Class
The following statement calls the class method myprimes:
y = cls.myprimes(1, new Double((double)n));
Thesamplecodepassesajava.lang.Double to the myprimes method. The
java.lang.Double is automatically converted to the double data type
required by the encapsulated MATLAB
myprimes function.
When
value and returns them in a MATLAB
to the Java p rogram as an
to
The
myprimes executes, it finds all prime numbers between 0 and the input
double array. This array is returned
MWNumericArray with its MWClassID property set
MWClassID.DOUBLE.
myprimes method encapsulates the myprimes function.
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-2007 The MathWorks, Inc.
if length(n) ~= 1
error('N must be a scalar');
end
if n < 2
p = zeros(1,0);
return
end
p = 1:2:n;
q = length(p);
p(1) = 2;
for k = 3:2:sqrt(n)
3-11
3 Programming
if p((k+1)/2)
p(((k*k+1)/2):k:q) = 0;
end
end
p = (p(p>0));
3-12
Passing Arguments to and from Java
In this section...
“Format” on page 3-13
“Manual C onversion of Data Types” on page 3-13
“Automatic Conversion to a MATLAB Type” on page 3-14
“Specifying Optional Arguments” on page 3-16
“Handling Return Values” on page 3-21
Format
When you invoke a method on a MATLAB Builder JA 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.
Passing Arguments to and from Java™
To convert them yourself, use instances of the
you are using manual conversion. Storing your data using the classes and
data types defined in the Java language means that you are relying on
automatic conversion. Most likely, you will use a combination of manual and
automatic conversion.
MWArray classes; in this case
Manual Conversion of Data Types
To manually convert to one of the standard MATLAB data types, use the
MWArray data conversion classes provided by the builder. For class reference
and usage information, see the
package.
Code Fragment: Using MWNumericArray
TheMagicSquareexample(“Deploying a Compon e nt with the Magic Square
Example” on page 1-16) exemplifies manual conversion. The following code
fragment from that program shows a
converted to an
function without further conversion:
MWNumericArray type that can be used by the MATLAB
com.mathworks.toolbox.javabuilder
java.lang.Double argument that is
3-13
3 Programming
MWNumericArray dims = null;
dims = new MWNumericArray(Double.valueOf(args[0]),
MWClassID.DOUBLE);
result = theMagic.makesqr(1, dims);
Code Fragment: Passing an MWArray. This example constructs an
MWNumericArray of type MWClassID.DOUBLE.Thecalltomyprimes passes the
number of outputs,
x = new MWNumericArray(n, MWClassID.DOUBLE);
cls = new myclass();
y = cls.myprimes(1, x);
1,andtheMWNumericArray, x:
MATLAB Builder JA product converts the MWNumericArray object to a
MATLAB scalar
double to pass to the MATLAB function.
Automatic Conversion to a MATLAB Type
When passing an argument only a small number of times, it is usually just
as efficient to pass a primitive Java type or object. In this case, the calling
mechanism converts the data for you into an equivalent MATLAB type.
3-14
For instance, either of the following Java types would be automatically
converted to the MATLAB
• AJava
• An object of class
double primitive
java.lang.Double
double type:
For reference information about data conversion (tables showing each Java
type along with its converted MATLAB type, and each MATLAB type with its
converted Java type), see “Data Conversion Rules” on page 8-8.
Code Fragment: Automatic Data Conversion
When callin g the makesqr method used in the getmagic application, you could
construct an object of type
of manual conversion. Instead, you could rely on automatic conversion, as
shown in the following code fragment:
MWNumericArray. Doing so would be an example
Passing Arguments to and from Java™
result = M.makesqr(1, arg[0]);
In this case, a Java double is passed as arg[0].
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 t o conversion rules, the
to a MATLA B 1-by-1
double array.
java.lang.Double automaticallyconverts
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.Double that passes the one data input to myprimes.
cls = new myclass();
y = cls.myprimes(1, new Double((double)n));
This second argument is converted to a MATLAB 1-by-1 double array, as
required by the MATLAB function. This is the default conversion rule for
java.lang.Double.
Code Fragment: Passing an MWArray
This example constructs an MWNumericArray of type MWClassID.DOUBLE.The
call to
builder converts the MWNumericArray object to a MATLAB scalar double to
pass to the MATLAB function.
myprimes passes the number of outputs, 1,andtheMWNumericArray, x.
x = new MWNumericArray(n, MWClassID.DOUBLE);
cls = new myclass();
y = cls.myprimes(1, x);
3-15
3 Programming
Code Fragment: Calling MWArray Methods
The conversion rules apply not only when calling your own methods, but
also when calling constructors and factory methods be longing to the
classes.
For example, the following code fragment calls the constructor for the
MWNumericArray class with a Java double as the input argument:
double Adata = 24;
MWNumericArray A = new MWnumericArray(Adata);
System.out.println("Array A is of type " + A.classID());
The builder converts the input argument to an instance of MWNumericArray,
with a
is the equivalent of a MATLAB 1-by-1
ClassID property of MWClassID.DOUBLE.ThisMWNumericArray object
double array.
When you run this example, the result is as follows:
Array A is of type double
MWArray
3-16
Changing the Default by Specifying the Type
When calling an MWArray class method constructor, supplying a specific data
type causes the MATLAB Builder JA product to convert to that type instead
of the default.
For example, in the following code fragment,thecodespecifiesthat
A sho uld
be constructed as a MATLAB 1-by-1 16-bit integer array:
double Adata = 24;
MWNumericArray A = new MWnumericArray(Adata, MWClassID.INT16);
System.out.println("Array A is of type " + A.classID());
When you run this example, the result is as follows:
Array A is of type int16
Specifying Optional Arguments
So far, the examples have not used MATLAB functions that have varargin or
varargout arguments. Consider the following MATLAB function:
Passing Arguments to and from Java™
function y = mysum(varargin)
%MYSUM Returns the sum of the inputs.
%Y = MYSUM(VARARGIN) Returns the sum of the inputs.
%This file is used as an example for the MATLAB
%Builder for Java product.
%Copyright 2001-2007 The MathWorks, Inc.
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.
Code Fragment: Passing Variable Numbers of Inputs
The MATLAB Builder JA product generates a Java interface to this function
as follows:
/* mlx interface - List version*/
public void mysum(List lhs, List rhs)
This version of getsum takes an array of Object as input and converts each
value to a
double array. The list of double arrays is then passed to the mysum
function, where it calculates the total sum of each input array.
Code Fragment: Passing a Variable Number of Outputs
When present, varargout arguments are handled in the same way that
varargin arguments are handled. Consider the following MATLAB function:
function varargout = randvectors
3-19
3 Programming
%RANDVECTORS Returns a list of random vectors.
%VARARGOUT = RANDVECTORS Returns a list of random
%vectors such that the length of the ith vector = i.
%This file is used as an example for the MATLAB
%Builder for Java product.
%Copyright 2001-2007 The MathWorks, Inc.
for i=1:nargout
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. The MATLAB Compiler product generates a Java
interface to this function as follows:
/* mlx interface - List version */
public void randvectors(List lhs, List rhs) throws MWException
{
(implementation omitted)
}
/* mlx interfaceArray version */
public void randvectors(Object[] lhs,
Object[] rhs) throws MWException
{
(implementation omitted)
}
/* Standard interfaceno inputs*/
public Object[] randvectors(int nargout) throws MWException
{
(implementation omitted)
}
3-20
Code Fragment: Passing Optional Arguments with the Standard
Interface. Here is one way to use the
randvectors method in a Java
program:
public double[][] getrandvectors(int n) throws MWException
{
myclass cls = null;
Object[] y = null;
try
{
cls = new myclass();
y = cls.randvectors(n);
double[][] ret = new double[y.length][];
for (int i = 0; i < y.length; i++)
ret[i] = (double[])((MWArray)y[i]).getData();
return ret;
}
finally
{
MWArray.disposeArray(y);
if (cls != null)
cls.dispose();
}
}
Passing Arguments to and from Java™
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
Thepreviousexamplesusedthefactthatyouknewthetypeand
dimensionality of the output argument. In the case that this information is
unknown, or can vary (as is possible in MATLAB programming), the code
that calls the method might need to query the type and dimensionality of
the output arguments.
Thereareseveralwaystodothis. Dooneofthefollowing:
• Use reflection support in the Java lang u age to query any object for its t ype.
• Use several methods provided by the
about the underlying MATLAB array.
MWArray class to query information
3-21
3 Programming
• Coercing to a specific type using the toTypeArray methods.
Code Fragment: Using Java Reflection
This code sample calls the myprimes method, and then determines the type
using reflection. The example assumes that the output is returned as a
numeric matrix but the exact numeric type is unknown.
public void getprimes(int n) throws MWException
{
myclass cls = null;
Object[] y = null;
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;
3-22
/* (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...) */
}
else if (a instanceof short[][])
{
short[][] x = (short[][])a;
/* (do something with x...) */
}
else if (a instanceof byte[][])
{
byte[][] x = (byte[][])a;
/* (do something with x...) */
}
Passing Arguments to and from Java™
else
{
throw new MWException(
"Bad type returned from myprimes");
}
}
This example uses the toArray method to return a Java primitive array
representing the underlying MATLAB array. The
like
getData in the previou s examples, except that the returned array has the
toArray method works just
same dimensionality as the underlying MATLAB array.
Code Fragment: Using MWArray Query
The next example uses the MWArray classID method to determine the type
of the underlying MATLAB array. It also checks the dimensionality by
calling
exception is thrown. It then checks the
accordingly.
numberOfDimensions. If any unexpected information is returned, an
MWClassID and processes the array
3-23
3 Programming
public void getprimes(int n) throws MWException
{
myclass cls = null;
Object[] y = null;
try
{
cls = new myclass();
y = cls.myprimes(1, new Double((double)n));
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();
3-24
/* (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.UINT32)
{
int[][] x = (int[][])((MWArray)y[0]).toArray();
/* (do something with x...) */
}
Passing Arguments to and from Java™
else if (clsid == MWClassID.INT64 ||
clsid == MWClassID.UINT64)
{
long[][] x = (long[][])((MWArray)y[0]).toArray();
/* (do something with x...) */
}
else if (clsid == MWClassID.INT16 ||
clsid == MWClassID.UINT16)
{
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.dispose();
}
}
Code Fragment: Using toTyp eArray Methods
The next example demonstrates how you can coerce or force data to a specified
numeric type by invoking any of the to
return an array of Java types matching the primitive type specified in the
name of the called method. The data is coerced or forced to the primitive type
TypeArray methods. These methods
3-25
3 Programming
specified in the method name. Note that when using these methods, data will
be truncated when ne eded to allow conformance to the specified data type.
Object results = null;
try {
// call a compiled MATLAB function
results = myobject.myfunction(2);
// first output is known to be a numeric matrix
MWArray resultA = (MWNumericArray) results[0];
double[][] a = (double[][]) resultA.toDoubleArray();
// second output is known to be
//a 3-dimensional numeric array
MWArray resultB = (MWNumericArray) results[1];
Int[][][] b = (Int[][][]) resultB.toIntArray();
}
finally {
MWArray.disposeArray(results);
}
3-26
Passing Java Objects by Reference
In this section...
“MATLAB Array” on page 3-27
“Wrappering and Passing Java Objects to MATLAB Functions with
MWJavaObjectRef” on page 3-27
MATLAB Array
MWJavaObjectRef,aspecialsubclassofMWArray, can be used to create a
MATLAB array that references Java objects. For detailed usage information
on this class, constructor, and associated methods, see the MWJavaObjectRef
page in the Javadoc or search for
browser Search field.
Wrappering and Passing Java Objects to MATLAB
Functions w ith MWJavaObjectRef
You can create a MATLAB code wrapper around Java objects using
MWJavaObjectRef. Using this technique, you can pass objects by reference
to MATLAB functions, clone a Java object inside a MATLAB Builder JA
component, as well as perform other object marshalling specific to the
MATLAB Compiler product. The examples in this section present some
common use cases.
MWJavaObjectRef in the MATLAB Help
Passing Java™ Objects by Reference
Code Fragment: Passing a Java Object into a MATLAB Builder
JA Component
To pass an object into a MATLAB Builder JA component:
1 Use MWJavaObjectRef to wrap your object.
2 Pass your object to a MATLAB function. For example:
/* Create an object */
java.util.Hashtable<String,Integer> hash =
new java.util.Hashtable<String,Integer>();
hash.put("One", 1);
3-27
3 Programming
hash.put("Two", 2);
System.out.println("hash: ");
System.out.println(hash.toString());
/* Create a MWJavaObjectRef to wrap this object */
origRef = new MWJavaObjectRef(hash);
/* Pass it to an MATLAB function that lists its methods, etc */
result = theComponent.displayObj(1, origRef);
MWArray.disposeArray(origRef);
For reference, here is the source code for displayObj.m:
displayObj.m.
function className = displayObj(h)
disp('---------------------------');
disp('Entering MATLAB function')
h
className = class(h)
whos('h')
methods(h)
Code Fragment: Cloning an Object Inside a Builder Component
You can also use MWJavaObjectRef to clone an object inside a MATLAB
Builder JA c om p onent. Continuing with the example in “Code Fragment:
Passing a Java Object into a MATLAB
3-27, do the following:
1 Add to the original hash.
2 Clone the object.
3 (Optional) Continue to add items to each copy. For example:
®
Builder JA Component” on page
Passing Java™ Objects by Reference
origRef = new MWJavaObjectRef(hash);
System.out.println("hash:");
System.out.println(hash.toString());
result = theComponent.addToHash(1, origRef);
outputRef = (MWJavaObjectRef)result[0];
/* We can typecheck that the reference contains a*/
/*Hashtable but not <String,Integer>;*/
/* this can cause issues if we get a Hashtable<wrong,wrong>. */