java builder

70
Web Newsgroup Technical Support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information 508-647-7000 (Phone) 508-647-7001 (Fax) The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 For contact information about worldwide offices, see the MathWorks Web site. MATLAB Builder JA Users Guide ゥ COPYRIGHT 20062010 by The MathWorks, Inc. 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 MathWorks, 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 the use, modification, reproduction, release, performance, display, and disclosure of the Program and 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 governments needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders. The MathWorks products are protected by one or more U.S. patents. Please see for more information. September 2006 Online only New for Version 1.0 (Release 2006b) March 2007 Online only Revised for Version 1.1 (Release 2007a) September 2007 Online only Revised for Version 2.0 (Release 2007b) March 2008 Online only Revised for Version 2.0.1 (Release 2008a) October 2008 Online only Revised for Version 2.0.2 (Release 2008b) March 2009 Online only Revised for Version 2.0.3 (Release 2009a) September 2009 Online only Revised for Version 2.0.4 (Release 2009b) March 2010 Online only Revised for Version 2.1 (Release 2010a)

Upload: maitreyamaity

Post on 08-Apr-2015

676 views

Category:

Documents


3 download

TRANSCRIPT

MA|A88u|der" 1A 2Usors Guido How lo Conlocl Ihe MolhWorksWWW.na1hWorks.con Webconp.sof1-sys.na1Jab NewsgroupWWW.na1hWorks.con1con1ac1TS.h1nJ Technical Supportsugges10na1hWorks.con Product enhancement suggestionsbugs0na1hWorks.con Bug reportsdoc0na1hWorks.con Documentation error reportsserv1ce0na1hWorks.con Order status, license renewals, passcodes1nfo0na1hWorks.con Sales, pricing, and general information508-647-7000 (Phone)508-647-7001 (Fax)The MathWorks, Inc.3 Apple Hill DriveNatick, MA 01760-2098For contact information about worldwide offices, see the MathWorks Web site.MATLAB Builder JA Users Guide COPYRIGHT 20062010 by The MathWorks, Inc.The software described in this document is furnished under a license agreement. The software may be usedor copied only under the terms of the license agreement. No part of this manual may be photocopied orreproduced in any form without prior written consent from The MathWorks, Inc.FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentationby, for, or through the federal government of the United States. By accepting delivery of the Programor Documentation, the government hereby agrees that this software or documentation qualifies ascommercial computer software or commercial computer software documentation as such terms are usedor defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms andconditions of this Agreement and only those rights specified in this Agreement, shall pertain to and governthe use, modification, reproduction, release, performance, display, and disclosure of the Program andDocumentation 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 thegovernments needs or is inconsistent in any respect with federal procurement law, the government agreesto return the Program and Documentation, unused, to The MathWorks, Inc.IrodemorksMATLAB and Simulink are registered trademarks of The MathWorks, Inc. SeeWWW.na1hWorks.con11radenarks for a list of additional trademarks. Other product or brandnames may be trademarks or registered trademarks of their respective holders.PolenlsThe MathWorks products are protected by one or more U.S. patents. Please seeWWW.na1hWorks.con1pa1en1s for more information.kevision HislorySeptember 2006 Online only New for Version 1.0 (Release 2006b)March 2007 Online only Revised for Version 1.1 (Release 2007a)September 2007 Online only Revised for Version 2.0 (Release 2007b)March 2008 Online only Revised for Version 2.0.1 (Release 2008a)October 2008 Online only Revised for Version 2.0.2 (Release 2008b)March 2009 Online only Revised for Version 2.0.3 (Release 2009a)September 2009 Online only Revised for Version 2.0.4 (Release 2009b)March 2010 Online only Revised for Version 2.1 (Release 2010a)ConlenlsGetting Started1Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2MATLAB Compiler Extension . . . . . . . . . . . . . . . . . . . . . . 1-2How the MATLAB Compiler and MATLAB Builder JAProducts Work Together . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2How Does Component Deployment Work? . . . . . . . . . . . . . 1-3Limitations of Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Before You Use MATLAB Builder JA . . . . . . . . . . . . . . . 1-4Your Role in the Java Application Deployment Process . . . 1-4What You Need to Know . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Required Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7Configuring Your Environment . . . . . . . . . . . . . . . . . . . . . . 1-7Quick Start: Deploying a Component with the HelloWorld Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10About the Hello World Example . . . . . . . . . . . . . . . . . . . . . . 1-10Before Running the Hello World Example . . . . . . . . . . . . . 1-10The Hello World Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10Building the Java Component . . . . . . . . . . . . . . . . . . . . . . . 1-11Deploying Hello World On a Computer with MATLAB,MATLAB Compiler, and MATLAB Builder JAInstalled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13Deploying Hello World On a Computer with Only theMATLAB Compiler Runtime (MCR) Installed (MATLABNot Installed) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14Deploying a Component with the Magic SquareExample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16About This Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16Magic Square Example: MATLAB Programmer Tasks . . . 1-16Magic Square Example: Java Programmer Tasks . . . . . . . 1-26Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36vWriting Deployable MATLAB Code2The MATLAB Application Deployment Products . . . . . 2-2Building Your Application with the ApplicationDeployment Products and the Deployment Tool . . . . 2-4What Is the Difference Between the Deployment Tool andthe mcc Command Line? . . . . . . . . . . . . . . . . . . . . . . . . . 2-4How Does MATLAB Compiler Software Build MyApplication? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4What You Should Know About the Dependency AnalysisFunction (depfun) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5Compiling MEX-Files, DLLs, or Shared Libraries . . . . . . . 2-6The Role of the Component Technology File (CTFArchive) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Guidelines for Writing Deployable MATLAB Code . . . . 2-10Compiled Applications Do Not Process MATLAB Files atRuntime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10Do Not Rely on Changing Directory or Path to Control theExecution of MATLAB Files . . . . . . . . . . . . . . . . . . . . . . . 2-11Use ismcc and isdeployed Functions To ExecuteDeployment-Specific Code Paths . . . . . . . . . . . . . . . . . . . 2-11Gradually Refactor Applications That Depend onNoncompilable Functions . . . . . . . . . . . . . . . . . . . . . . . . . 2-12Do Not Create or Use Nonconstant Static StateVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12Working with MATLAB Data Files Using Load andSave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14Using Load/Save Functions to Process MATLAB Data forDeployed Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14Programming3About the MATLAB Builder JA API . . . . . . . . . . . . . . . . 3-3vi ContentsUnderstanding the MATLAB Builder JA API DataConversion Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3Automatic Conversion to MATLAB Types . . . . . . . . . . . . . . 3-4Understanding Function Signatures Generated by theMATLAB Builder JA Product . . . . . . . . . . . . . . . . . . . . . 3-5Adding Fields to Data Structures and Data StructureArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6Returning Data from MATLAB to Java . . . . . . . . . . . . . . . . 3-7Importing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8Creating an Instance of the Class . . . . . . . . . . . . . . . . . . . 3-9What Is an Instance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9Code Fragment: Instantiating a Java Class . . . . . . . . . . . . 3-9Passing Arguments to and from Java . . . . . . . . . . . . . . . . 3-13Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13Manual Conversion of Data Types . . . . . . . . . . . . . . . . . . . . 3-13Automatic Conversion to a MATLAB Type . . . . . . . . . . . . . 3-14Specifying Optional Arguments . . . . . . . . . . . . . . . . . . . . . . 3-16Handling Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21Passing Java Objects by Reference . . . . . . . . . . . . . . . . . . 3-27MATLAB Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27Wrappering and Passing Java Objects to MATLABFunctions with MWJavaObjectRef . . . . . . . . . . . . . . . . . 3-27Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34Error Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34Handling Checked Exceptions . . . . . . . . . . . . . . . . . . . . . . . 3-34Handling Unchecked Exceptions . . . . . . . . . . . . . . . . . . . . . 3-37Managing Native Resources . . . . . . . . . . . . . . . . . . . . . . . . 3-40What Are Native Resources? . . . . . . . . . . . . . . . . . . . . . . . . 3-40Using Garbage Collection Provided by the JVM . . . . . . . . . 3-40Using the dispose Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-41Overriding the Object.Finalize Method . . . . . . . . . . . . . . . . 3-43Improving Data Access Using the MCR User DataInterface and MATLAB Builder JA . . . . . . . . . . . . . . . 3-44viiExample: Supplying Run-Time Configuration Informationfor Parallel Computing Toolbox Applications . . . . . . . . . 3-45Dynamically Specifying Run-Time Options to theMCR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49What Run-Time Options Can You Specify? . . . . . . . . . . . . . 3-49Setting and Retrieving MCR Option Values UsingMWApplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49Handling Data Conversion Between Java andMATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52Calling MWArray Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52Creating Buffered Images from a MATLAB Array . . . . . . . 3-53Setting Java Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-54How to Set Java System Properties . . . . . . . . . . . . . . . . . . . 3-54Ensuring a Consistent GUI Appearance . . . . . . . . . . . . . . . 3-54Blocking Execution of a Console Application thatCreates Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-56waitForFigures Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-56Code Fragment: Using waitForFigures to Block Executionof a Console Application . . . . . . . . . . . . . . . . . . . . . . . . . . 3-57Ensuring Multi-Platform Portability . . . . . . . . . . . . . . . . 3-59Using MCR Component Cache andMWComponentOptions . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61MWComponentOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61Selecting Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61Setting Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-62Learning About Java Classes and Methods by Exploringthe Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-64viii ContentsSample Java Applications4Plot Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Spectral Analysis Example . . . . . . . . . . . . . . . . . . . . . . . . . 4-8Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10Matrix Math Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17MATLAB Functions to Be Encapsulated . . . . . . . . . . . . . . . 4-18Understanding the getfactor Program . . . . . . . . . . . . . . . . . 4-19Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19Phonebook Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29Buffered Image Creation Example . . . . . . . . . . . . . . . . . . 4-37Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37Optimization Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42OptimDemo Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-43Web Application Example . . . . . . . . . . . . . . . . . . . . . . . . . . 4-53Example Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-53Before You Work this Example . . . . . . . . . . . . . . . . . . . . . . 4-53Downloading the Demo Files . . . . . . . . . . . . . . . . . . . . . . . . 4-54Build Your Java Component . . . . . . . . . . . . . . . . . . . . . . . . 4-55Compiling Your Java Code . . . . . . . . . . . . . . . . . . . . . . . . . . 4-55Generating the Web Archive (WAR) File . . . . . . . . . . . . . . 4-56Running the Web Deployment Demo . . . . . . . . . . . . . . . . . . 4-57Using the Web Application . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57ixDeploying a Java Component Over the Web5About the WebFigures Feature . . . . . . . . . . . . . . . . . . . . . . 5-2Supported Renderers for WebFigures . . . . . . . . . . . . . . . . . 5-2Preparing to Implement WebFigures for MATLABBuilder JA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3Your Role in the WebFigure Deployment Process . . . . . . . . 5-3What You Need to Know to Implement WebFigures . . . . . 5-5Required Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5Assumptions About the Examples . . . . . . . . . . . . . . . . . . . . 5-7Set DISPLAY on UNIX Systems . . . . . . . . . . . . . . . . . . . . . 5-8Quick Start: Implementing a Custom WebFigure . . . . . 5-9Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9Setting Up the Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9Creating the Default WebFigure . . . . . . . . . . . . . . . . . . . . . 5-10Interacting with the Default WebFigure . . . . . . . . . . . . . . . 5-11Creating a Custom WebFigure . . . . . . . . . . . . . . . . . . . . . . . 5-12Advanced Configuration of a WebFigure . . . . . . . . . . . . . 5-16Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16How Do WebFigures Work? . . . . . . . . . . . . . . . . . . . . . . . . . 5-18Installing WebFigureService . . . . . . . . . . . . . . . . . . . . . . . . 5-19Getting the WebFigure Object from Your Method . . . . . . . 5-20Attaching a WebFigure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21Using the WebFigure JSPTag to Reference a WebFigure . . 5-23Getting an Embeddable String That References aWebFigure Attached to a Cache . . . . . . . . . . . . . . . . . . . . 5-26Working with MATLAB Figures and ImagesYour Role in Working with Figures and Images . . . . . . 6-2Creating and Modifying a MATLAB Figure . . . . . . . . . . . 6-3Preparing a MATLAB Figure for Export . . . . . . . . . . . . . . . 6-3x ContentsChanging the Figure (Optional) . . . . . . . . . . . . . . . . . . . . . . 6-3Exporting the Figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4Cleaning Up the Figure Window . . . . . . . . . . . . . . . . . . . . . 6-4Example: Modifying and Exporting Figure Data . . . . . . . . 6-4Working with MATLAB Figure and Image Data . . . . . . 6-6For More Comprehensive Examples . . . . . . . . . . . . . . . . . . 6-6Working with Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6Working with Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6Creating Scalable Web Applications Using RMI7Using Remote Method Invocation (RMI) . . . . . . . . . . . . . 7-2Before You Use RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3Running the Client and Server on a Single Machine . . 7-4Running the Client and Server on SeparateMachines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8Using Native Java with Cell Arrays and StructArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9Why Use Native Type Cell Arrays and Struct Arrays? . . . . 7-9Before You Use Native Type Data Marshalling with Cellsand Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10The Native Java Cell and Struct Example . . . . . . . . . . . . . 7-10For More RMI Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16xiReference Information for JavaBRequirements for the MATLAB Builder JA Product . . 8-2System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2Path Modifications Required for Accessibility . . . . . . . . . . . 8-2Limitations and Restrictions . . . . . . . . . . . . . . . . . . . . . . . . 8-3Settings for Environment Variables (DevelopmentMachine) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3Data Conversion Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8Java to MATLAB Conversion . . . . . . . . . . . . . . . . . . . . . . . . 8-8MATLAB to Java Conversion . . . . . . . . . . . . . . . . . . . . . . . . 8-10Unsupported MATLAB Array Types . . . . . . . . . . . . . . . . . . 8-11Programming Interfaces Generated by the MATLABBuilder JA Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-12APIs Based on MATLAB Function Signatures . . . . . . . . . . 8-12Standard API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13mlx API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-15Code Fragment: Signatures Generated for the myprimesExample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-15MWArray Class Specification . . . . . . . . . . . . . . . . . . . . . . . 8-17Function Reference9ExamplesAHello World (Quick Start) . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Magic Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2xii ContentsUsing Load and Save . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Importing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Instantiating a Java Class . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Using MWNumericArray . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Handling Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Automatic Data Conversion . . . . . . . . . . . . . . . . . . . . . . . . A-3Calling MWArray Methods . . . . . . . . . . . . . . . . . . . . . . . . . . A-3Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4Handling Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4Supplying Run-Time Configuration Information forParallel Computing Toolbox Applications . . . . . . . . . A-4Ensuring a Consistent GUI Appearance . . . . . . . . . . . . . A-4COM Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4Using waitForFigures to Block Execution of a ConsoleApplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5Sample Applications (Java) . . . . . . . . . . . . . . . . . . . . . . . . . A-5Working with WebFigures . . . . . . . . . . . . . . . . . . . . . . . . . . A-5Creating and Modifying a MATLAB Figure . . . . . . . . . . . A-5Working with Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5xiiiWorking with Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6Using RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6Indexxiv ContentsJGetting Started* Product Overview on page 1-2* Before You Use MATLAB Builder JA on page 1-4* Quick Start: Deploying a Component with the Hello World Example onpage 1-10* Deploying a Component with the Magic Square Example on page 1-16* Next Steps on page 1-36J Gelllng SlorledProducl Overviewln lhis seclion...MATLAB Compiler Extension on page 1-2How the MATLAB Compiler and MATLAB Builder JA Products WorkTogether on page 1-2How Does Component Deployment Work? on page 1-3Limitations of Support on page 1-3MAILA8 Compiler ExlensionMATLAB Builder JA enables you to create Java classes from yourMATLAB programs. These Java classes can be integrated into Javaprograms and deployed royalty-free to desktop computers or Web serversthat do not have MATLAB installed.When used with MATLAB Compiler, the builder creates deployablecomponents that make MATLAB based computations, visualizations, andgraphical user interfaces accessible to end users of the Java programs.When the Java program is deployed to the Web, multiple users can access itthrough a Web browser.The builder encrypts your MATLAB functions and generates a Java wrapperaround them so that they behave just like any other Java class. Java classescreated with MATLAB Builder JA are portable and run on all platformssupported by MATLAB. See the Platform Roadmap for MATLAB for moreinformation.For information about how MATLAB Compiler works, see The MATLABCompiler Build Process on page 1-23.How lhe MAILA8 Compiler ond MAILA8 8uilder JAProducls Work IogelherThe MATLAB Compiler product can compile MATLAB files, MEX-files,MATLAB objects, or other MATLAB code. The MATLAB Builder JA product1-2Producl Cvervlewsupports all the features of MATLAB, and adds support for Java classes,Java objects (instances of a class), and methods. Using these productstogether, you can generate the following:* Standalone applications on UNIX, Windows, and Macintosh platforms* C and C++ shared libraries (dynamically linked libraries, or DLLs, onMicrosoft Windows)* Enterprise Java applications for use on any Java compatible platformHow Does Componenl Deploymenl Work?There are two kinds of deployment:* Installing components and setting up support for them on a developmentmachine so that they can be accessed by a developer who seeks to use themin writing a Java application.* Deploying support for the components when they are accessed at run timeon an end-user machine.To accomplish this kind of deployment, you must make sure that theinstaller you create for the application takes care of supporting the Javacomponents on the target machine. In general, this means the MCR mustbe installed, on the target machine. You must also install the MATLABBuilder JA component.Nole Java components created with the MATLAB Builder JA product aredependent on the version of MATLAB with which they were built.Limilolions ol 5upporlMATLAB Builder JA provides a wide variety of support for various Javatypes and objects. However, MATLAB (MCOS) objects are not supported asinputs or outputs for compiled or deployed functions.1-3J Gelllng Slorled8elore You Use MAILA8 8uilder JAln lhis seclion...Your Role in the Java Application Deployment Process on page 1-4What You Need to Know on page 1-6Required Products on page 1-7Configuring Your Environment on page 1-7Your kole in lhe Jovo Applicolion Deploymenl ProcessDepending 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 themby writing a program in MATLAB code. Or, your role may be to implement theinfrastructure needed to successfully deploy a Java application to the Web.In smaller installations, you may find one person responsible for performingtasks associated with multiple roles.The table Application Deployment Roles, Tasks, and References on page 1-5describes some of the different roles, or jobs, that MATLAB Builder JA userstypically perform and which tasks they would most likely perform whenrunning Deploying a Component with the Magic Square Example on page1-16.1-4Belore You se MAlLABBullder" !AApplicolion Deploymenl koles, Iosks, ond kelerenceskole Iosks kelerencesMATLAB programmer * Understandend-user businessrequirements andthe mathematicalmodels needed tosupport them.* Write MATLABcode.* Build an executablecomponent withMATLAB tools(usually withsupport from a Javaprogrammer).* Package thecomponent fordistribution to endusers.* Pass the packagedcomponent to theJava programmerfor rollout andfurther integrationinto the end-userenvironment.Copying the ExampleFiles on page 1-18Testing the MATLABFile You Want toDeploy on page 1-18Creating theMagic Square JavaComponent on page1-19Packaging theMagic Square JavaComponent (Optional)on page 1-21Copy the Package YouCreated (Optional) onpage 1-23Java programmer * Write Java codeto execute theJava package builtby the MATLABprogrammer.* Roll out the packagedcomponent andintegrate it intoGathering FilesNeeded forDeployment on page1-26Testing the JavaComponent in a JavaApplication on page1-271-5J Gelllng SlorledApplicolion Deploymenl koles, Iosks, ond kelerences (Conlinued}kole Iosks kelerencesthe end-userenvironment.* Use the componentin enterprise Javaapplications, addingand modifying codeas needed.* Address dataconversion issuesthat may beencountered,according to the endusers specifications.* Ensure the final Javaapplication executesreliably in the endusers environment.Distributing theComponent to EndUsers on page 1-32Integrating JavaClasses Generatedby MATLAB into a JavaApplication on page1-33Calling Class Methodsfrom Java on page 1-34Handle DataConversion as Neededon page 1-34Build and Test onpage 1-35External user Execute the solutioncreated by MATLABand Java programmers.Run the deployedapplication (outside thescope of this document).Whol You Need lo KnowThe following knowledge is assumed when you use the MATLAB BuilderJA product:* If your job function is MATLAB programmer, the following is required:- A basic knowledge of MATLAB, and how to work with cell arrays andstructures* If your job function is Java programmer, the following is required:- Exposure to the Java programming language- Object-oriented programming concepts1-6Belore You se MAlLABBullder" !Akequired ProduclsYou must install the following products to run the example described in thischapter:* MATLAB* MATLAB Compiler* MATLAB Builder JAConliguring Your EnvironmenlConfigure your environment to work with the examples. Consult your systemadministrator or Java programmer before performing these taskssome maybe unnecessary. Your administrator or programmer is often the best resourcefor verifying, installing, or customizing your Java environment.Verilying Your Jovo EnvironmenlYou may already be running a compatible version of Java. To find out ifyou have Java installed on your computer, and if it is compatible with theMATLAB Builder JA product:J Open a command prompt.2 Enter the command ]ava -vers1on. If Java is installed, the result lookslike this:]ava vers1on "versonnuoer"Java{TM) 2 Pun11ne Env1ronnen1. S1andard Ed111on{bu1Jd versonnuoer.ouJdnuoerJava Ro1Spo1{TM) CJ1en1 vM{bu1Jd versonnuoer.ouJdnuoer. n1xed node)3 Enter the command ]avac -vers1on.Nole Alternately, you may have to enter JAvAR0ME`b1n`]avac-vers1on if you have the user environment variable JAvAR0ME defined.For information on locating environment variables, see Setting Up YourJava Environment on page 1-8.1-7J Gelllng SlorledIf ]avac is installed, the results should look like this:]avac versonnuoerIf ]ava and ]avac are installed and the version numbers are at least 1.5, go toDeploying a Component with the Magic Square Example on page 1-16. Ifnot, go to Setting Up Your Java Environment on page 1-8.5elling Up Your Jovo EnvironmenlJ Download and install the Java Developers Kit (JDK) from SunMicrosystems, 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 ofthe JDK collectively make up a Java development environment.The JDK includes the Java Runtime Environment (JRE), a collection ofcompiled classes that makes up the Java virtual machine, a standaloneexecutor of the Java language, on a specific platform. Ensure your JavaRuntime Environment and JDK are compatible with the Sun MicrosystemsJDK Version 1.6.0 before proceeding to the next step.2 Set the environment variable JAvAR0ME. This tells Java where to find yourinstalled JDK. from the MATLAB prompt. You can set JAvAR0ME:* On Windows platforms:o 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 JAvAR0ME for Variablename. Enter the absolute path name where your JDK is installedfor Variable value. Here is the value of a typical JAvAR0MEenvironment variable:C:`Progran F1Jes`Java`J0K1.6.0031-8Belore You se MAlLABBullder" !ANole If JAvAR0ME already exists, select it and click Edit. Enter thepath name where your JDK is installed.l Click OK to accept changes.* On UNIX platforms:g Open a command prompt.h Set JAvAR0ME as follows:se1 JAvAR0ME=J0|pathnae3 Verify that MATLAB is reading the correct value of JAvAR0ME.o At the command prompt, type ge1env JAvAR0ME.b The response from MATLAB should be the path name you set toJAvAR0ME in Configuring Your Environment on page 1-7. If not,ensure the JDK that MATLAB is pointing to will be compatible torun this example (at least Java Version 1.5). Consult your systemadministrator if you are unsure.1-9J Gelllng SlorledOuick 5lorl: Deploying o Componenl wilh lhe Hello WorldExompleln lhis seclion...About the Hello World Example on page 1-10Before Running the Hello World Example on page 1-10The Hello World Example on page 1-10Building the Java Component on page 1-11Deploying Hello World On a Computer with MATLAB, MATLABCompiler, and MATLAB Builder JA Installed on page 1-13Deploying Hello World On a Computer with Only the MATLAB CompilerRuntime (MCR) Installed (MATLAB Not Installed) on page 1-14Aboul lhe Hello World ExompleThis section gives a very brief example of MATLAB Builder JA functionality.For a more extensive starter example, refer to Deploying a Component withthe Magic Square Example on page 1-16.Nole The examples here use the Windows depJoy1ooJ GUI, a graphicalfront-end interface to MATLAB Compiler software. For information abouthow to perform these tasks using the command-line interface to MATLABCompiler software, see the ncc reference page. For information about how tostart the Deployment Tool GUI from the command line, see the depJoy1ooJreference page.8elore kunning lhe Hello World ExompleBefore running this example, configure your environment. See ConfiguringYour Environment on page 1-7 .Ihe Hello World ExompleTo write a function in MATLAB that displays the text heJJo WorJd as output,you define the following function and save it as heJJo.n.1-10Culck Slorl. Deploylng o Componenl wllh lhe Hello Vorld Exomplefunc11on heJJod1sp{`heJJo. WorJd`)8uilding lhe Jovo ComponenlYou create a Java application by using the Deployment Tool GUI to build aJava class that wraps around the sample MATLAB code discussed in TheHello World Example on page 1-10.To compile or build heJJo using the Deployment Tool, use the followinginformation as you work through this example:Project name heJJopr]Class name heJJocJsPackage name heJJopckFile to compile heJJo.nNole When a component is built, the package name is the same as theproject name, by default. To change the package name, click the Actionsicon and select Settings.J Start MATLAB.2 Type depJoy1ooJ at the command prompt and press Enter. ThedepJoy1ooJ GUI opens.3 Create a deployment project using the Deployment Project dialog:o Type the name of your project in the Name field.b Enter the location of the project in the Location field. Alternately,navigate to the location.c Select the target for the deployment project from the Target drop-downmenu.d Click OK.1-11J Gelllng SlorledCreoling o Jovo Projecl4 On the Build tab:* If you are building a Java application, click Add class. Type the nameof 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. Toadd another class, click Add class.Nole You may optionally add supporting files. For examples of thesefiles, see the depJoy1ooJ Help. To add these files, in the Shared Resourcesand Helper Files area:o Click Add files/directoriesb Click Open to select the file or files.5 When you complete your changes, click the Build button ( ).1-12Culck Slorl. Deploylng o Componenl wllh lhe Hello Vorld ExompleWhol ls o MAILA8 8uilder JA Projecl?To use the MATLAB Builder JA product, you create a project, which specifiesthe MATLAB code to be used in the components that you want to create. Thisproduct supports data conversion between Java types and MATLAB types.For more about projects and their contents, see Anatomy of a MATLABBuilder JA Project on page 1-20.Whol ls o MAILA8 8uilder JA Componenl?A component created by the MATLAB Builder JA product is a standaloneJava package (.]ar file). The package contains one or more Java classes thatencapsulate MATLAB code. The classes provide methods that are callabledirectly from Java code.Deploying Hello World On o Compuler wilh MAILA8,MAILA8 Compiler, ond MAILA8 8uilder JA lnslolledRun Hello World by entering the following from a system command shell.J Before proceeding, ensure you have renamed you package file to heJJopck.When a component is built, the package name is the same as the projectname, by default. To change the package name, click the Actions iconand select Settings.2 Navigate to the directory containing the JAR file.3 Run the following command on:* Windows:]ava -cJasspa1hatJaoroot`1ooJbox`]avabu1Jder`]ar`arch`]avabu1Jder.]arheJJopck.]arheJJopck.heJJocJs* UNIX: ]ava -cJasspa1hna1Jabroo111ooJbox1]avabu1Jder1]ar1arch1]avabu1Jder.]ar:heJJopck.]arheJJopck.heJJocJs1-13J Gelllng Slorledwhere:* atJaoroot is the location of your MATLAB installation* arch is the operating system and processor type of the local machinNole The above command should be entered on one continuous line.Deploying Hello World On o Compuler wilh Only lheMAILA8 Compiler kunlime (MCk} lnslolled (MAILA8Nol lnslolled}J Before proceeding, ensure you have renamed you package file to heJJopck.When a component is built, the package name is the same as the projectname, by default. To change the package name, click the Actions iconand select Settings.2 Run Hello World by entering the following from a system command shell:* Windows:]ava -cJasspa1h|0||00J`1ooJbox`]avabu1Jder`]ar`arch`]avabu1Jder.]arheJJopck.]arheJJopck.heJJocJs* UNIX: ]ava -cJasspa1h|0||00J11ooJbox1]avabu1Jder1]ar1arch1]avabu1Jder.]ar:heJJopck.]arheJJopck.heJJocJswhere:* |0||00J is the location of your MCR installation* arch is the operating system and processor type of the local machine1-14Culck Slorl. Deploylng o Componenl wllh lhe Hello Vorld ExompleNole The above command should be entered on one continuous line.3 If you are running UNIX, set your system path appropriately. SeeDirectories Required for Development and Testing and DirectoriesRequired for Run-Time Deployment.1-15J Gelllng SlorledDeploying o Componenl wilh lhe Mogic 5quore Exompleln lhis seclion...About This Example on page 1-16Magic Square Example: MATLAB Programmer Tasks on page 1-16Magic Square Example: Java Programmer Tasks on page 1-26Aboul Ihis ExompleIn this section, you will step through an example of how a simple MATLABfunction can be transformed into a deployable MATLAB Builder JAcomponent.The Magic Square example shows you how to create a Java component namednag1csquare which contains the nag1c class, a .]ar file, and other filesneeded to deploy your application.The class wraps a MATLAB function, nakesqr, which computes a magicsquare. A magic square is a matrix containing any number of rows. Theserows, when added horizontally and vertically, equate to the same value.MATLAB contains a function, nag1c, that can create magic squares of anydimension. In this example, you will work with that function.Nole The examples here use the Windows depJoy1ooJ GUI, a graphicalfront-end interface to MATLAB Compiler software. For information abouthow to perform these tasks using the command-line interface to MATLABCompiler software, see the ncc reference page.Mogic 5quore Exomple: MAILA8 Progrommer IosksThe following tasks are usually performed by the MATLAB programmer.1-16Deploylng o Componenl wllh lhe Moglc Squore ExompleKey Iosks lor lhe MAILA8 ProgrommerIosk kelerencePrepare to run the example bycopying the MATLAB example filesinto a work folder.Copying the Example Files on page1-18Test the MATLAB code to ensure itis suitable for deployment. Testing the MATLAB File YouWant to Deploy on page 1-18Create a Java package(encapsulating your MATLABcode in a Java class) by running theBuild function in depJoy1ooJ.Creating the Magic Square JavaComponent on page 1-19Run the Packaging Tool to bundleyour Java component with theadditional files you selected.Packaging the Magic Square JavaComponent (Optional) on page 1-21Copy the output from the PackagingTool (the d1s1r1b folder). Copy the Package You Created(Optional) on page 1-23The Magic Square example shows you how to create a Java component(nag1csquare), which contains the nag1c class, a .]ar file (which includes the.c1f archive described in How Does the MATLAB Builder JA Product UseJAR Files? on page 1-23), and other files needed to deploy your application.The class encapsulates a MATLAB function, nakesqr, which computes amagic square.The client Java application, ge1nag1c.]ava converts the array returned bynakesqr to a native array and displays it on the screen. When you run thege1nag1c application from the command line, you can pass the dimension forthe magic square as a command-line argument.Nole The examples for the MATLAB Builder JA product are inatJaoroot`1ooJbox`]avabu1Jder`ExanpJes. In most examples, Windowssyntax is featured (backslashes, instead of forward slashes). This exampleassumes the work folder is on drive 0:.1-17J Gelllng SlorledCopying lhe Exomple FilesPrepare to run the example by copying needed files into your work area asfollows:J Navigate toatJaoroot`1ooJbox`]avabu1Jder`ExanpJes`Mag1cSquareExanpJe.atJaoroot is the MATLAB root folder (where MATLAB is installed). Tofind the value of this variable on your system, type atJaoroot at acommand prompt.2 Copy the Mag1cSquareExanpJe folder to a work area, for example,0:`]avabu1JderexanpJes. Avoid using spaces in your foldernames, if possible. The example files should now reside in0:`]avabu1JderexanpJes`Mag1cSquareExanpJe.3 Using a command prompt, navigate to 0:`]avabu1JderexanpJes`Mag1cSquareExanpJe by switching to the 0: drive and enteringcd `]avabu1JderexanpJes`Mag1cSquareExanpJe.Iesling lhe MAILA8 File You Wonl lo DeployNormally you would first create the MATLAB file you want to deploy. In thisexample, you will test a precreated MATLAB file (nakesqr.n) containing thepredefined MATLAB function nag1c.J Using MATLAB, locate the nakesqr.n file at0:`]avabu1JderexanpJes`Mag1cSquareExanpJe`Mag1c0enoConp. Thecontents of the file are as follows:func11on y = nakesqr{x)MAKES0P Mag1c square of s1ze x. Y = MAKES0P{X) re1urns a nag1c square of s1ze x. Th1s f1Je 1s used as an exanpJe for 1he MATLA8 8u1Jder JA produc1. Copyr1gh1 2001-2008 The Ma1hWorks. 1nc.y = nag1c{x)2 At the command prompt, enter nakesqr{5) and view the results. Theoutput should appear as follows:1-18Deploylng o Componenl wllh lhe Moglc Squore Exomple17 24 1 8 1523 5 7 14 164 6 13 20 2210 12 19 21 311 18 25 2 9Creoling lhe Mogic 5quore Jovo ComponenlYou create the Magic Square Java application by using the Deployment ToolGUI to build a Java class that wraps around the sample MATLAB codediscussed in Testing the MATLAB File You Want to Deploy on page 1-18.Use the following information as you work through this example using theinstructions in Building the Java Component on page 1-11:Project Name nag1csquareClass Name nag1cFile to compile nakesqr.nWhol Hoppens in lhe 8uild Process.Nole The MATLAB Builder JA product uses the JAvAR0ME variable tolocate the Java Software Development Kit (SDK) on your system. Thecompiler uses this variable to set the version of the ]avac.exe commandit uses during compilation.To create a component, the builder does the following:J Generates Java code to implement your component. The files are as follows:1-19J Gelllng SlorledycJass.]ava Contains a Java class withmethods encapsulating theMATLAB functions specifiedin the project for that class.ycoponentMCPFac1ory.]ava Java component with firstcharacter of ycoponentcapitalzed.ycJassreno1e.]ava Contains a remotableJava class with methodsencapsulating the MATLABfunctions specified in theproject for that class.See Chapter 7, CreatingScalable Web ApplicationsUsing RMI.package-1nfo.]ava Javadoc packagedocumentation.2 Compiles the Java code produced in step 1.3 Generates /d1s1r1b and /src subfolders.4 Invokes the Jar utility to package the Java class files it has created into aJava archive file (ycoponent.]ar).For information about how MATLAB Compiler works, see The MATLABCompiler Build Process on page 1-23.Anolomy ol o MAILA8 8uilder JA Projecl. A builder project containsinformation about the files and settings needed by the MATLAB Builder JAproduct to create a deployable Java component. A project specifies informationabout classes and methods, including the MATLAB functions to be included.Classes and MethodsThe builder transforms MATLAB functions that are specified in thecomponents project to methods belonging to a Java class.1-20Deploylng o Componenl wllh lhe Moglc Squore ExompleWhen creating a component, you must provide one or more class names aswell as a component name. The class name denotes the name of the classthat 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 methodsthat encapsulate the MATLAB functions.Nole When you add files to a project, you do not have to add any MATLABfiles for functions that are called by the functions that you add. When theMATLAB Builder JA product builds a component, it automatically includesany MATLAB functions called by the functions that you explicitly specify forthe component. See Spectral Analysis Example on page 4-8 for a sampleapplication that illustrates this feature.Naming ConventionsTypically you should specify names for components and classes that will beclear to programmers who use your components. For example, if you areencapsulating many MATLAB functions, it helps to determine a scheme offunction categories and to create a separate class for each category. Also, thename of each class should be descriptive of what the class does.Valid characters are any alpha or numeric characters, as well as theunderscore () character.Pockoging lhe Mogic 5quore Jovo Componenl (Oplionol}Bundling the Java component with additional files into a JAR file that canbe distributed to users is called packaging. You will perform this step usingthe packaging function of depJoy1ooJ. Alternately, copy the contents of thed1s1r1b folder and the MCR Installer to a local folder of your choice. If youare creating a shared component and want to include additional code with thecomponent, you must perform this step.1-21J Gelllng SlorledNole Packaging a component and a Java package are different concepts.Packaging in this context refers only to the act of using MATLAB BuilderJA to bundle the Java component with associated files needed to successfullydeploy the application. A Java package is a collection of Java classes andmethods.J On the Package tab, add the MATLAB Compiler Runtime (the MCR) byclicking Add MCR.2 Next, add others files useful for end users. The readne.1x1 file containsimportant information about others files useful for end users. To packageadditional files or folders, click Add file/directories, select the file orfolder you want to package, and click Open.3 In the Deployment Tool, click the Packaging button ( ).4 On Windows, the package is a self-extracting executable. On platformsother than Windows, it is a .z1p file. Verify that the contents of thed1s1r1b folder contains the files you specified.Nole When the self-extracting executable is uncompressed on a system,vCPE0S1TX86 is installed. vCPE0S1TX86 installs run-time componentsof Microsoft Visual C++ libraries necessary for running Visual C++applications.Whol Hoppens in lhe Pockoging Process?. The packaging processcreates a self-extracting executable (on Windows platforms) or a .z1p file (onplatforms other than Windows). The package contains at least the following:* The builder component* The MCR Installer (if the Install MCR option was selected when thecomponent was built)* Documentation generated by the Sun Microsystems Javadoc tool1-22Deploylng o Componenl wllh lhe Moglc Squore ExompleNole The packaging process is not available when using ncc directly.Nole For guidelines on multi-platform portability, reference EnsuringMulti-Platform Portability on page 3-59.How Does lhe MAILA8 8uilder JA Producl Use JAk Files?. As ofR2007b, the MATLAB Builder JA product now embeds the CTF archivewithin the generated JAR file, by default. This offers convenient deploymentof a single output file since all encrypted MATLAB file data is now containedwithin this Java archive.For information on CTF archive data extraction and utilizationusing MWConponen10p11ons see Using MCR Component Cache andMWComponentOptions on page 3-61.Copy lhe Pockoge You Creoled (Oplionol}Copy the package that you created from the d1s1r1b folder to the local folderof your choice or send them directly to the Java programmer..Ihe MAILA8 Compiler 8uild ProcessTo generate and package an application, the user:J Writes an application or component in MATLAB2 Invokes the MATLAB Compiler, which:o Examines the input MATLAB files and the external dependencydatabase to determine the complete list of all functions used by theapplication or component. As part of this process, MATLAB Compilerdetermines which files are not able to be compiled and automaticallyexcludes them.b Determines which functions are to be made publicly visible (for example,those that can be called from another product or environment).1-23J Gelllng Slorledc Generates the appropriate interface code files based on the publicfunction list and the complete function list from the preceding steps. Theinterface code generated is also dependent on what target the user wantsto create (for example, a Java component, a standalone executable, or aMicrosoft Excel add-in).d Packages compilable functions into a CTF archive, creating a file on theusers disk. This archive is embedded by default in the binary executable.e Optionally, invokes target specific compiler to generate a binaryapplication or component from the files in C and the interface codelibraries provided by The MathWorks.3 Locates the install package for the MATLAB Compiler Runtime (MCR).4 Collects together the binary, the CTF archive, and the MCR installer (alongwith other optional, user-specified files) for the user.The deployment GUI (depJoy1ooJ) automates many of the steps in theprocess for user convenience.1-24Deploylng o Componenl wllh lhe Moglc Squore Exomple1-25J Gelllng SlorledMogic 5quore Exomple: Jovo Progrommer IosksThe following tasks are usually performed by the Java programmer.Key Iosks lor lhe Jovo ProgrommerIosk kelerenceEnsure you have the needed filesfrom the MATLAB Programmerbefore proceeding.Gathering Files Needed forDeployment on page 1-26Test the Java code by using it in aJava application. Compile and runthe component to ensure it producesthe same results as your MATLABcode.Creating the Magic Square JavaComponent on page 1-19Archive and distribute the output toend users. Distributing the Component to EndUsers on page 1-32Import classes generated by theMATLAB Builder JA product intoexisting Java applications.Integrating Java Classes Generatedby MATLAB into a Java Applicationon page 1-33Use built-in Java class methods toenhance your Java application. Calling Class Methods from Javaon page 1-34Address potential data conversionissues with differing data types. Handle Data Conversion as Neededon page 1-34Verify your Java application worksas expected in your end usersdeployment environment.Build and Test on page 1-35Golhering Files Needed lor DeploymenlBefore beginning, verify you have access to the following files, created by theMATLAB Programmer in Copy the Package You Created (Optional) on page1-23. The following files are required to deploy to users who do not have acopy of MATLAB installed:* MCR Installer. For locations of the MCR Installer, run the ncr1ns1aJJercommand.1-26Deploylng o Componenl wllh lhe Moglc Squore Exomple* Javadoc documentation* readne.1x1 fileSee Packaging the Magic Square Java Component (Optional) on page1-21 for more information about these files. You will also want tocommunicate the location of con.na1hWorks.1ooJbox.]avabu1Jder(atJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar). You canbrowse the API Javadoc for con.na1hWorks.1ooJbox.]avabu1Jder from theMATLAB Help.Iesling lhe Jovo Componenl in o Jovo ApplicolionBefore deploying the created component, you need to verify that it can be usedin a Java application successfully.First, create a small Java program that uses the component created foryour by the MATLAB Programmer (see Packaging the Magic Square JavaComponent (Optional) on page 1-21). The example provides a sampleJava program that accomplishes this (ge1nag1c.]ava now in the folder0:`]avabu1JderexanpJes`Mag1cSquareExanpJe`Mag1c0enoJavaApp).The program imports the nag1csquare package you createdwith depJoy1ooJ and the MATLAB Builder JA package(con.na1hWorks.1ooJbox.]avabu1Jder) and uses one of theMATLAB Builder JA conversion classes to convert the number passed to theprogram 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 nag1c, and calls the nakesqrmethod on that object. Note how the MATLAB file becomes a method ofthe Java class that encapsulates it. As explained in Testing the MATLABFile You Want to Deploy on page 1-18, the nakesqr method computes thesquare using the MATLAB nag1c function. The source code of ge1nag1c.]avafollows, for your reference:1* ge1nag1c.]ava* Th1s f1Je 1s used as an exanpJe for 1he MATLA8* 8u1Jder JA produc1.** Copyr1gh1 2008 The Ma1hWorks. 1nc.1-27J Gelllng Slorled*11* Necessary package 1npor1s *11npor1 con.na1hWorks.1ooJbox.]avabu1Jder.*1npor1 nag1csquare.*1** ge1nag1c cJass conpu1es a nag1c square of order N. The* pos111ve 1n1eger N 1s passed on 1he connand J1ne.*1cJass ge1nag1c{pubJ1c s1a11c vo1d na1n{S1r1ng|] args){MWNuner1cArray n = nuJJ 1* S1ores 1npu1 vaJue *10b]ec1|] resuJ1 = nuJJ 1* S1ores 1he resuJ1 *1nag1c 1heMag1c = nuJJ 1* S1ores nag1c *11* cJass 1ns1ance *11ry{1* 1f no 1npu1. ex11 *11f {args.Jeng1h == 0){Sys1en.ou1.pr1n1Jn{"Error: nus1 1npu1 a pos111ve1n1eger")re1urn}1* Conver1 and pr1n1 1npu1 vaJue*1n = neW MWNuner1cArray{0oubJe.vaJue0f{args|0]).MWCJass10.00u8LE)Sys1en.ou1.pr1n1Jn{"Mag1c square of order " +n.1oS1r1ng{))1* Crea1e neW nag1c ob]ec1 *11heMag1c = neW nag1c{)1* Conpu1e nag1c square and pr1n1 resuJ1 *11-28Deploylng o Componenl wllh lhe Moglc Squore ExompleresuJ1 = 1heMag1c.nakesqr{1. n)Sys1en.ou1.pr1n1Jn{resuJ1|0])}ca1ch {Excep11on e){Sys1en.ou1.pr1n1Jn{"Excep11on: " + e.1oS1r1ng{))}f1naJJy{1* Free na11ve resources *1MWArray.d1sposeArray{n)MWArray.d1sposeArray{resuJ1)1f {1heMag1c != nuJJ)1heMag1c.d1spose{)}}}Ensure your current working folder is set to0:`]avabu1JderexanpJes`Mag1cSquareExanpJe as noted previously in thisexample. Then, do the following:J Compile the Java component with the Java compiler, ]avac. At thecommand prompt, enter one of the following commands. When enteringthese commands, ensure they are entered as one continuous command. OnWindows systems, the semicolon () is a concatenation character. On UNIXsystems, the colon (:) is a concatenation character.* On Windows platforms:JAvAR0ME`b1n`]avac -cJasspa1hatJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar.`nag1csquare`d1s1r1b`nag1csquare.]ar.`Mag1c0enoJavaApp`ge1nag1c.]ava* On UNIX platforms:$JAvAR0ME1b1n1]avac -cJasspa1h.:atJaoroot11ooJbox1]avabu1Jder1-29J Gelllng Slorled1]ar1]avabu1Jder.]ar:.1nag1csquare1d1s1r1b1nag1csquare.]ar.1Mag1c0enoJavaApp1ge1nag1c.]avaInspect the syntax of the ]avac compile command on Windows platforms:JAvAR0ME`b1n`]avac -cJasspa1hatJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar.`nag1csquare`d1s1r1b`nag1csquare.]ar.`Mag1c0enoJavaApp`ge1nag1c.]avaThe components of this command are:* JAvAR0ME1b1n1]avac Using this command invokes the Javacompiler explicitly from the version of Java you set with JAvAR0ME (seeConfiguring Your Environment on page 1-7).Nole JAvAR0ME is Windows syntax and $JAvAR0ME is UNIX syntax.* -cJasspa1h Using this argument allows Java to access the packages andother files you need to compile your component.* atJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar The location of the MATLAB Builder JA package file(con.na1hWorks.1ooJbox.]avabu1Jder).* .`nag1csquare`d1s1r1b`nag1csquare.]ar The location of thenag1csquare package file you created with depJoy1ooJ.* .`Mag1c0enoJavaApp`ge1nag1c.]ava The location of thege1nag1c.]ava source file.2 When you run ge1nag1c, you pass an input argument to Java representingthe dimension for the magic square. In this example, the value for thedimension is 5. Run ge1nag1c by entering one of the following ]avacommands at the command prompt. When entering these commands,ensure they are entered as one continuous command. On Windows systems,the semicolon () is a concatenation character. On UNIX systems, the colon(:) is a concatenation character.1-30Deploylng o Componenl wllh lhe Moglc Squore Exomple* On Windows platforms:JAvAR0ME`b1n`]ava-cJasspa1h.`Mag1c0enoJavaAppatJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar.`nag1csquare`d1s1r1b`nag1csquare.]arge1nag1c 5* On UNIX platforms:$JAvAR0ME1b1n1]ava-cJasspa1h.1Mag1c0enoJavaApp:atJaoroot11ooJbox1]avabu1Jder1]ar1]avabu1Jder.]ar:.1nag1csquare1d1s1r1b1nag1csquare.]arge1nag1c 5Inspect the syntax of the ]ava command on Windows platforms:JAvAR0ME`b1n`]ava-cJasspa1h.`Mag1c0enoJavaAppatJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar.`nag1csquare`d1s1r1b`nag1csquare.]arge1nag1c 5Nole If you are running on the Mac 64-bit platform, you must add the-d64 flag in the Java command. See Limitations and Restrictions on page8-3 for more specific information.The components of this command are:* JAvAR0ME`b1n`]ava Using this command invokes the ]ava runtime explicitly from the MATLAB JRE.* -cJasspa1h Using this argument allows Java to access the packagesand other files you need to run your application.* .`Mag1c0enoJavaApp The location of ge1nag1c.cJass. Thesemicolon concatenates this file location with the following file location,so Java can find the files needed to run your program.1-31J Gelllng Slorled* atJaoroot`1ooJbox`]avabu1Jder`]ar`]avabu1Jder.]ar The location of the MATLAB Builder JA package file(con.na1hWorks.1ooJbox.]avabu1Jder). The semicolon concatenatesthis file location with the following file location, so Java can find thefiles needed to run your program.* .`nag1csquare`d1s1r1b`nag1csquare.]ar The location of thenag1csquare package file you created with depJoy1ooJ.* ge1nag1c 5 Invokes the compiled ge1nag1c application with thecommand-line argument 5.3 Verify the program output. If the program ran successfully, a magic squareof order 5 will print, matching the output of the MATLAB function you ranin Testing the MATLAB File You Want to Deploy on page 1-18, as follows:Mag1c square of order 517 24 1 8 1523 5 7 14 164 6 13 20 2210 12 19 21 311 18 25 2 9Using mcrrool lo Iesl Agoinsl lhe MCk. To test directly against the MCR,substitute crroot for atJaoroot, where crroot is the location where theMCR is installed on your system. An example of an MCR root location is0:`AppJ1ca11ons`MATLA8`MATLA8Conp1JerPun11ne`|0|versonnuoer.Remember to double-quote all parts of the ]ava command path argumentsthat contain spaces.Dislribuling lhe Componenl lo End UsersIf you bundled the component as a self-extracting executable, paste it in afolder on the development machine, and run it. If you are using a .z1p filebundled with WinZip, unzip and extract the contents to the developmentmachine.1-32Deploylng o Componenl wllh lhe Moglc Squore Exomplelnlegroling Jovo Closses Generoled by MAILA8 inlo o JovoApplicolionIf you are implementing your Java component on a computer other than theone on which it was built:J Install the MATLAB Compiler Runtime on the target system. SeeDeployment Process in the MATLAB Compiler documentation.2 Consult the Javadoc for information on classes generated by MATLABclasses. Reference the Javadoc from the MATLAB Builder JA productroadmap.3 To integrate the Java class generated by MATLAB Builder JA,softwareboth the component and the MWArray API need to be imported in the Javacode. Import the MATLAB libraries and the component classes into yourcode with the Java 1npor1 function. For example:1npor1 con.na1hWorks.1ooJbox.]avabu1Jder.*1npor1 coponentnae.cJassnae or 1npor1 coponentnae.*For more information, see Chapter 3, Programming.4 As with all Java classes, you must use the neW function to create aninstance of a class. To create an object (1heMag1c) from the nag1c class,the example application uses the following code:1heMag1c = neW nag1c{)For more information, see Chapter 3, Programming.5 To conserve system resources and optimize performance, it is good practiceto get in the habit of destroying any instances of classes that are no longerneeded. For example, to dispose of the object 1heMag1c, use the followingcode:1heMag1c.d1spose{)1* Make 11 eJ1g1bJe for garbage coJJec11on *11heMag1c = nuJJFor more information, see Chapter 3, Programming, in particular, Usingthe dispose Method on page 3-41.1-33J Gelllng SlorledColling Closs Melhods lrom JovoAfter you have instantiated the class, you can call a class method as youwould with any Java object. In the Magic Square example, the nakesqrmethod is called as shown:resuJ1 = 1heMag1c.nakesqr{1. n)Here n is an instance of an MWArray class. Note that the first argumentexpresses number of outputs (1) and succeeding arguments represent inputs(n).See the following code fragment for the declaration of n:n = neW MWNuner1cArray{0oubJe.vaJue0f{args|0].MWCJass10.00u8LE)Nole The MATLAB Builder JA product provides a rich API for integratingthe generated components. Detailed examples and complete listings of inputparameters and possible thrown exceptions can be found in the Javadoc,available from thethe MATLAB Builder JA roadmap.Hondle Dolo Conversion os NeededWhen you invoke a method on a builder component, the input parametersreceived by the method must be in the MATLAB internal array format. Youcan either (manually) convert them yourself within the calling program, orpass the parameters as Java data types.* To manually convert to one of the standard MATLAB data types, useMWArray classes in the package con.na1hWorks.1ooJbox.]avabu1Jder.* If you pass them as Java data types, they are automatically converted.How MAILA8 8uilder JA Hondles Dolo. To enable Javaapplications to exchange data with MATLAB methods theyinvoke, the builder provides an API, which is implemented as thecon.na1hWorks.1ooJbox.]avabu1Jder.MWArray package. This packageprovides a set of data conversion classes derived from the abstract class,MWArray. Each class represents a MATLAB data type.1-34Deploylng o Componenl wllh lhe Moglc Squore ExompleFor more detailed information on data handling within theproduct and programming with the MWArray package, see thecon.na1hWorks.1ooJbox.]avabu1Jder.MWArray Javadoc and About theMATLAB Builder JA API on page 3-3.8uild ond IeslBuild and test the Java application as you would any application in your endusers environment. Build on what youve created by working with additionalclasses and methods.After you create and distribute the initial application, you will want tocontinue to enhance it. Details about some of the more common tasks you willperform as you develop your application are listed in the chapters described inNext Steps on page 1-36.kunning o 64-8il Moc ApplicolionBefore you run a 64-bit Macintosh application, you need to use the theMacintosh Application Launcher. See Running Your 64-Bit Mac Applicationin the MATLAB Compiler User Guide for more information.See Using MATLAB Compiler on UNIX in the MATLAB Compiler UserGuide for complete information about building, deploying, and testing UNIXapplications with MATLAB Compiler.1-35J Gelllng SlorledNexl 5lepsWriting Java applications thatcan access Java methods thatencapsulate MATLAB codeChapter 3, ProgrammingSample applications that accessmethods developed in MATLAB Chapter 4, Sample JavaApplicationsDeploying Java components over theWeb Chapter 5, Deploying a JavaComponent Over the WebReference information aboutautomatic data conversion rules Chapter 8, Reference Informationfor Java1-362Writing DeployableMATLAB Code* The MATLAB Application Deployment Products on page 2-2* Building Your Application with the Application Deployment Products andthe Deployment Tool on page 2-4* Guidelines for Writing Deployable MATLAB Code on page 2-10* Working with MATLAB Data Files Using Load and Save on page 2-142 Vrlllng Deployoble MAlLABCodeIhe MAILA8 Applicolion Deploymenl ProduclsM/T|/B erue|tlc lT erue|iercelc occess tc lT s]steas0eelcus acJeluses t|e |uilJe| tccls tc c|eote occaucrert t|ot is cier tc t|e|usiress se|ice Jeelcue|The following tables summarizes the target applications supported by eachproduct.:Ihe MAILA8 5uile ol Applicolion Deploymenl ProduclsProducl Iorgel Creole5londoloneExeculobles?CreoleFunclionLibrories?CreoleApplicolionswilhGrophics?Creole WebApplicolions?MATLABCompiler C and C++standalonesand librariesYes Yes Yes NoMATLABBuilder NE C# .NETcomponentsVisualBasic COMcomponentsNo Yes Yes YesMATLABBuilder JA Javacomponents No Yes Yes YesMATLABBuilder EX MicrosoftExcel add-ins No Yes Yes No2-2lhe MAlLABAppllcollon Deploymenl ProduclsIhe MAILA8Applicolion Deploymenl ProduclsEach of the builder products uses the MATLAB Compiler core code to createdeployable components.2-32 Vrlllng Deployoble MAlLABCode8uilding Your Applicolion wilh lhe Applicolion DeploymenlProducls ond lhe Deploymenl Ioolln lhis seclion...What Is the Difference Between the Deployment Tool and the mccCommand Line? on page 2-4How Does MATLAB Compiler Software Build My Application? on page2-4What You Should Know About the Dependency Analysis Function(depfun) on page 2-5Compiling MEX-Files, DLLs, or Shared Libraries on page 2-6The Role of the Component Technology File (CTF Archive) on page 2-7Whol ls lhe Dillerence 8elween lhe Deploymenl Ioolond lhe mcc Commond Line?Using the Deployment Tool (depJoy1ooJ) GUI, you perform any function youwould invoke using the MATLAB Compiler ncc command-line interface. TheDeployment Tool interactive menus and dialogs build ncc commands that arecustomized to your specification. As such, your MATLAB code is processedthe same way as if you were compiling it using ncc.Using the Deployment Tool, you:* Perform related deployment tasks with a single intuitive GUI.* Maintain related information in a convenient project file. Your projectstate persists between sessions. Your previous project loads automaticallywhen the Deployment Tool starts. You load previously stored compilerprojects from a prepopulated menu.* Package applications for distribution.How Does MAILA8 Compiler 5ollwore 8uild MyApplicolion?MATLAB Compiler software:2-4Bulldlng Your Appllcollon wllh lhe Appllcollon Deploymenl Producls ond lhe Deploymenl loolJ 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 filecontentsfunctions 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 MATLABFor more information about depfun, see What You Should Know Aboutthe Dependency Analysis Function (depfun) on page 2-5.3 Validates MEX-files. In particular, nexFunc11on 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 ComponentTechnology File (CTF Archive) on page 2-7.5 Generates target-specific wrapper code. For example, the wrapper for a Cmain function is very different than the wrapper for a Java interface class.6 Invokes a third-party target-specific compiler to create the appropriatebinary software component (a standalone executable, a Java JAR file,and so on).For details about how MATLAB Compiler software builds your deployablecomponent, see The MATLAB Compiler Build Process on page 1-23.Whol You 5hould Know Aboul lhe DependencyAnolysis Funclion (deplun}MATLAB Compiler uses a dependency analysis function (depfun) todetermine the list of necessary files to include in the CTF package. In somecases, this process includes an large number of files. This is often true whenMATLAB object classes exist in the compilation and depfun cannot resolveoverloaded methods at compile time. Dependency analysis also processes1ncJude/excJude files on each pass (see the ncc flag -a Add to Archive).2-52 Vrlllng Deployoble MAlLABCodeIip To improve compile time performance and lessen application size, prunethe path with -N Clear Path, -p Add Directory to Path, or by specifyingToolboxes on Path in the depJoy1ooJ Settingsdepfun searches for executable content such as:* MATLAB files* P-files* Java classes and .]ar files* .f1g files* MEX-filesdepfun does not search for data files of any kind (except MAT files). Youmust manually 1ncJude data files.Compiling MEX-Files, DLLs, or 5hored LibroriesWhen you compile MATLAB functions containing MEX-files, ensurethat depfun can find themdoing so allows you to avoid many commoncompilation problems. In particular, note that:* depfun cannot examine MEX-files, DLLs, or shared libraries to determinetheir dependencies. Explicitly include all binaries these files requireeither with the ncc -a option or the options on the Advanced tab in theDeployment Tool under Settings.* If you have any doubts that depfun can find a MATLAB function called bya MEX-file, DLL, or shared librarymanually include it. Do this witheither the ncc -a option or by using the options on the Advanced tab inthe Deployment Tool under Settings.* Not all functions are compatible with MATLAB Compiler. Check the filenccExcJudedF1Jes.Jog after your build completes. This file lists allfunctions called from your application that you cannot deploy.2-6Bulldlng Your Appllcollon wllh lhe Appllcollon Deploymenl Producls ond lhe Deploymenl loolIhe kole ol lhe Componenl Iechnology File (CIFArchive}Each application or shared library produced by MATLAB Compiler has anassociated Component Technology File (CTF) archive. The archive containsall the MATLAB based content (MATLAB files, MEX-files, and so on)associated with the component.MATLAB Compiler also embeds a CTF) archive in each generated binary.The CTF houses all deployable files. All MATLAB files encrypt in the CTFarchive using the Advanced Encryption Standard (AES) cryptosystem.If you choose the extract the CTF archive as a separate file the files remainencrypted. For more information on how to extract the CTF archive refer tothe references in the following table.lnlormolion on CIF Archive EmbeddingJExlroclion ond ComponenlCocheProducl keler loMATLAB Compiler Overriding Default CTF ArchiveEmbedding Using the MCRComponent CacheMATLAB Builder NE Overriding Default CTF ArchiveEmbedding for Components Usingthe MCR Component CacheMATLAB Builder JA Using MCR Component Cache andMWComponentOptions on page3-61MATLAB Builder EX Overriding Default CTF ArchiveEmbedding for Components Usingthe MCR Component Cache2-72 Vrlllng Deployoble MAlLABCode2-8Bulldlng Your Appllcollon wllh lhe Appllcollon Deploymenl Producls ond lhe Deploymenl loolAddilionol DeloilsMultiple CTF archives, such as those generated with COM, .NET, or Excelcomponents, can coexist in the same user application. You cannot, however,mix and match the MATLAB files they contain. You cannot combineencrypted and compressed MATLAB files from multiple CTF archives intoanother CTF archive and distribute them.All the MATLAB files from a given CTF archive associate with a uniquecryptographic key. MATLAB files with different keys, placed in the sameCTF archive, do not execute. If you want to generate another applicationwith a different mix of MATLAB files, recompile these MATLAB files into anew CTF archive.MATLAB Compiler deleted the CTF archive and generated binary followinga failed compilation, but only if these files did not exist before compilationinitiates. Run heJp ncc -K for more information.Coulion Release Engineers and Software Configuration Managers:Do not use build procedures or processes that strip shared libraries on CTFarchives. If you do, you can possibly strip the CTF archive from the binary,resulting in run-time errors for the driver application.2-92 Vrlllng Deployoble MAlLABCodeGuidelines lor Wriling Deployoble MAILA8 Codeln lhis seclion...Compiled Applications Do Not Process MATLAB Files at Runtime onpage 2-10Do Not Rely on Changing Directory or Path to Control the Execution ofMATLAB Files on page 2-11Use ismcc and isdeployed Functions To Execute Deployment-Specific CodePaths on page 2-11Gradually Refactor Applications That Depend on NoncompilableFunctions on page 2-12Do Not Create or Use Nonconstant Static State Variables on page 2-12Compiled Applicolions Do Nol Process MAILA8 Filesol kunlimeThe MATLAB Compiler was designed so that you can deploy locked downfunctionality. Deployable MATLAB files are suspended or frozen at thetime MATLAB Compiler encrypts themthey do not change from that pointonward. This does not mean that you cannot deploy a flexible applicationitmeans that you must design your application with flexibility in mind. If youwant the end user to be able to choose between two different methods, forexample, they both must be compiled in.The MCR only works on MATLAB code that was encrypted when thecomponent was built. Any function or process that dynamically generatesnew 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 executesencrypted MATLAB files, and the Neural Network Toolbox generatesunencrypted MATLAB files, some functions in the Neural Network Toolboxcannot be deployed.Similarly, functions that need to examine the contents of a MATLAB functionfile cannot be deployed. RELP, for example, is dynamic and not available in2-10Guldellnes lor Vrlllng Deployoble MAlLABCodedeployed mode. You can use LOADLIBRARY in deployed mode if you provideit with a MATLAB function prototype.Instead of compiling the function that generates the MATLAB code andattempting to deploy it, perform the following tasks:J Run the code once in MATLAB to obtain your generated function.2 Compile the MATLAB code with MATLAB Compiler, including thegenerated function.Iip Another alternative to using EvAL or FEvAL is using anonymous functionhandles.If you require the ability to create MATLAB code for dynamic runtimeprocessing, your end-users must have an installed copy of MATLAB.Do Nol kely on Chonging Direclory or Polh lo Conlrollhe Execulion ol MAILA8 FilesIn general, good programming practices advise against redirecting a programsearch path dynamically within the code. Many programmers are proneto this behavior since it mimics the actions they usually perform on thecommand line. However, this can lead to problems when deploying code.For example, in a deployed application, the MATLAB and Java paths arefixed and cannot change. Therefore, any attempts to change these paths(using the cd command or the addpa1h command) failsIf you find you cannot avoid placing addpa1h calls in your MATLAB code, use1sncc and 1sdepJoyed. See the next section for details.Use ismcc ond isdeployed Funclions Io ExeculeDeploymenl-5pecilic Code PolhsThe 1sdepJoyed function allows you to specify which portion of your MATLABcode is deployable, and which is not. Such specification minimizes yourcompilation errors and helps create more efficient, maintainable code.2-112 Vrlllng Deployoble MAlLABCodeFor example, you find it unavoidable to use addpa1h when writing yours1ar1up.n. Using 1sncc and 1sdepJoyed, you specify when and what iscompiled and executed.For an example of using 1sdepJoyed, see Passing Arguments to and froma Standalone Application.Groduolly keloclor Applicolions Ihol Depend onNoncompiloble FunclionsOver time, refactor, streamline, and modularize MATLAB code containingnon-compilable or non-deployable functions that use 1sncc and 1sdepJoyed.Your eventual goal is graceful degradation of non-deployable code. Inother words, the code must present the end user with as few obstacles todeployment 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 goesthrough a phase of perpetual rewriting, debugging, and optimization. Insome toolboxes, such as the Neural Network Toolbox product, the code goesthrough a period of self-training as it reacts to various data permutationsand patterns. Such code is almost never designed to be deployed.* Run-time code, on the other hand, has solidified or become stableit is in afinished state and is ready to be deployed by the end user.Consider creating a separate directory for code that is not meant to bedeployed or for code that calls undeployable code.Do Nol Creole or Use Nonconslonl 5lolic 5loleVorioblesAvoid using the following:* Global variables in MATLAB code* Static variables in MEX-files* Static variables in Java code2-12Guldellnes lor Vrlllng Deployoble MAlLABCodeThe state of these variables is persistent and shared with everything in theprocess.Persistent variables can cause problems because the MCR process runs in asingle thread. You cannot load more than one of these non-constant, staticvariables into the same process. In addition, these static variables do notwork well in multithreaded applications.If you must use static variables, bind them to instances. For example,defining instance variables in a Java class is preferable to defining thevariable as s1a11c.Nole This guideline does not apply to MATLAB Builder EX customers.When programming with Microsoft Excel, you can assign global variables tolarge matrices that persist between calls.2-132 Vrlllng Deployoble MAlLABCodeWorking wilh MAILA8 Dolo Files Using Lood ond 5oveIf your deployed application uses MATLAB data files (MAT-files), it is helpfulto code L0A0 and SAvE functions to manipulate the data and store it for laterprocessing.* Use 1sdepJoyed to determine if your code is running in or out of theMATLAB workspace.* Specify the data file by full path name or relative to c1froo1.* All MAT-files are unchanged after ncc runs. These files are not encryptedwhen written to the CTF archive.For more information about CTF archives, see The Role of the ComponentTechnology File (CTF Archive) on page 2-7.Use the following example as a template for manipulating your MATLABdata inside, and outside, of MATLAB.Using LoodJ5ove Funclions lo Process MAILA8 Dololor Deployed ApplicolionsThe following example specifies three MATLAB data files:* userda1a.na1* userda1a1ex1rada1a.na1* ..1ex1ernda1a1ex1ernda1a.na1Compile exJoadsave.n with the following ncc command:ncc -nvC exJoadsave.n -a `userda1a.na1` -a`.1userda1a1ex1rada1a.na1` -a`..1ex1ernda1a1ex1ernda1a.na1`ex_loodsove.mfunc11on exJoadsave2-14Vorklng wllh MAlLAB Dolo Flles slng Lood ond Sove Th1s exanpJe shoWs hoW 1o Work W11h 1he "Joad1save" func11ons on da1a f1Jes 1n depJoyed node. There are 1hree source da1a f1Jes 1n 1h1s exanpJe. userda1a.na1 userda1a1ex1rada1a.na1 ..1ex1ernda1a1ex1ernda1a.na1 Conp1Je 1h1s exanpJe W11h 1he ncc connand: ncc -nC exJoadsave.n -a `userda1a.na1` -a `.1userda1a1ex1rada1a.na1` -a `..1ex1ernda1a1ex1ernda1a.na1` AJJ 1he foJders under 1he curren1 na1n MATLA8 f1Je d1rec1ory W1JJ be 1ncJuded as reJa11ve pa1h 1o c1froo1 AJJ o1her foJders W1JJ have 1he foJder s1ruc1ure 1ncJuded 1n 1he c1f arch1ve f1Je fron roo1 of 1he d1sk dr1ve. 1f a da1a f1Je 1s ou1s1de of 1he na1n MATLA8 f1Je pa1h. 1he absoJu1e pa1h W1JJ be 1ncJuded 1n c1f and ex1rac1ed under c1froo1. For exanpJe: 0a1a f1Je "c:`$na1Jabroo1`exanpJes`ex1ernda1a`ex1ernda1a.na1" W1JJ be added 1n1o c1f and ex1rac1ed 1o "$c1froo1`$na1Jabroo1`exanpJes`ex1ernda1a`ex1ernda1a.na1". AJJ na11da1a f1Jes are unchanged af1er ncc runs. There 1s no excryp11on on 1hese user 1ncJuded da1a f1Jes. They are 1ncJuded 1n 1he c1f arch1ve. The 1arge1 da1a f1Je 1s: .1ou1pu11savedda1a.na1 When Wr111ng 1he f1Je 1o JocaJ d1sk. do no1 save any f1Jes under c1froo1 s1nce 11 nay be refreshed and deJe1ed When 1he appJ1ca11on 1snex1 s1ar1ed.==== Joad da1a f1Je =============================1f 1sdepJoyed 1n depJoyed node. aJJ f1Je under CTFPoo1 1n 1he pa1h are Joaded2-152 Vrlllng Deployoble MAlLABCode by fuJJ pa1h nane or reJa11ve 1o $c1froo1. L0A0F1LENAME1=Wh1ch{fuJJf1Je{c1froo1.nf1Jenane.`userda1a.na1`)) L0A0F1LENAME2=Wh1ch{fuJJf1Je{c1froo1.`userda1a`.`ex1rada1a.na1`))L0A0F1LENAME1=Wh1ch{fuJJf1Je{`userda1a.na1`))L0A0F1LENAME2=Wh1ch{fuJJf1Je{`ex1rada1a.na1`)) For ex1ernaJ da1a f1Je. fuJJ pa1h W1JJ be added 1n1o c1f you don`1 need spec1fy 1he fuJJ pa1h 1o f1nd 1he f1Je.L0A0F1LENAME3=Wh1ch{fuJJf1Je{`ex1ernda1a.na1`))eJserunn1ng 1he code 1n MATLA8L0A0F1LENAME1=fuJJf1Je{na1Jabroo1.`ex1ern`.`exanpJes`.`conp1Jer`.`0a1aRandJ1ng`.`userda1a.na1`)L0A0F1LENAME2=fuJJf1Je{na1Jabroo1.`ex1ern`.`exanpJes`.`conp1Jer`.`0a1aRandJ1ng`.`userda1a`.`ex1rada1a.na1`)L0A0F1LENAME3=fuJJf1Je{na1Jabroo1.`ex1ern`.`exanpJes`.`conp1Jer`.`ex1ernda1a`.`ex1ernda1a.na1`)end Load 1he da1a f1Je fron curren1 Work1ng d1rec1oryd1sp{|`Load A fron : `.L0A0F1LENAME1])Joad{L0A0F1LENAME1.`da1a1`)d1sp{`A= `)d1sp{da1a1) Load 1he da1a f1Je fron sub d1rec1oryd1sp{|`Load 8 fron : `.L0A0F1LENAME2])Joad{L0A0F1LENAME2.`da1a2`)d1sp{`8= `)d1sp{da1a2) Load ex1ern da1a ou1s1de of curren1 Work1ng d1rec1oryd1sp{|`Load ex1ern da1a fron : `.L0A0F1LENAME3])Joad{L0A0F1LENAME3)d1sp{`ex1da1a= `)d1sp{ex1da1a)==== nuJ11pJe 1he da1a na1r1x by 2 ==============resuJ1 = da1a1*da1a2d1sp{`A * 8 = `)d1sp{resuJ1)2-16Vorklng wllh MAlLAB Dolo Flles slng Lood ond Sove==== save 1he neW da1a 1o a neW f1Je ===========SAvEPATR=s1rca1{pWd.f1Jesep.`ou1pu1`)1f { -1sd1r{SAvEPATR))nkd1r{SAvEPATR)endSAvEF1LENAME=s1rca1{SAvEPATR.f1Jesep.`savedda1a.na1`)d1sp{|`Save 1he A * 8 resuJ1 1o : `.SAvEF1LENAME])save{SAvEF1LENAME. `resuJ1`)2-172 Vrlllng Deployoble MAlLABCode2-183ProgrammingTo access a Java component built and packaged by the MATLAB Builder JAproduct, you must first unpackage and install components so you can usethem on a particular machine. See Chapter 1, Getting Started for moreinformation.* About the MATLAB Builder JA API on page 3-3* 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 Objects by Reference on page 3-27* Handling Errors on page 3-34* Managing Native Resources on page 3-40* Improving Data Access Using the MCR User Data Interface andMATLAB Builder JA on page 3-44* 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 onpage 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 Javadocon page 3-643 ProgrommlngNole For examples of these tasks, see Chapter 4, Sample Java Applications.For information about deploying your application after you complete thesetasks, see How Does Component Deployment Work? on page 1-3.3-2Aboul lhe MAlLABBullder" !A APlAboul lhe MAILA8 8uilder JA APlln lhis seclion...Understanding the MATLAB Builder JA API Data Conversion Classeson page 3-3Automatic Conversion to MATLAB Types on page 3-4Understanding Function Signatures Generated by the MATLAB BuilderJA Product on page 3-5Adding Fields to Data Structures and Data Structure Arrays on page 3-6Returning Data from MATLAB to Java on page 3-7Underslonding lhe MAILA8 8uilder JA APl DoloConversion ClossesWhen writing your Java application, you can represent your data usingobjects of any of the data conversion classes. Alternatively, you can usestandard Java data types and objects.The data conversion classes are built as a class hierarchy that represents themajor MATLAB array types.Nole This discussion provides conceptual information about the classes.For details, see con.na1hWorks.1ooJbox.]avabu1Jder in the productDocumentation Set.This discussion assumes you have a working knowledge of the Javaprogramming language and the Java Software Developers Kit (SDK). Thisis not intended to be a discussion on how to program in Java. Refer to thedocumentation that came with your Java SDK for general programminginformation.3-33 ProgrommlngOverview ol Closses ond Melhods in lhe Dolo ConversionCloss HierorchyThe root of the data conversion class hierarchy is the MWArray abstractclass. The MWArray class has the following subclasses representing themajor MATLAB types: MWNuner1cArray, MWLog1caJArray, MWCharArray,MWCeJJArray, and MWS1ruc1Array.Each subclass stores a reference to a native MATLAB array of that type.Each class provides constructors and a basic set of methods for accessingthe underlying arrays properties and data. To be specific, MWArray and theclasses derived from MWArray provide the following:* Constructors and finalizers to instantiate and dispose of MATLAB arrays* ge1 and se1 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 typesAdvonloge ol Using Dolo Conversion ClossesThe MWArray data conversion classes let you pass native type parametersdirectly without using explicit data conversion. If you pass the same arrayfrequently, you might improve the performance of your program by storingthe array in an instance of one of the MWArray subclasses.Aulomolic Conversion lo MAILA8 IypesNole Because the conversion process is automatic (in most cases), you do notneed to understand the conversion process to pass and return arguments withMATLAB Builder JA components.When you pass an MWArray instance as an input argument, the encapsulatedMATLAB array is passed directly to the method being called.In contrast, if your code uses a native Java primitive or array as an inputparameter, the builder converts it to an instance of the appropriate MWArray3-4Aboul lhe MAlLABBullder" !A APlclass before it is passed to the method. The builder can convert any Javastring, numeric type, or any multidimensional array of these types to anappropriate MWArray type, using its data conversion rules. See DataConversion Rules on page 8-8 for a list of all the data types that aresupported along with their equivalent types in MATLAB.The conversion rules apply not only when calling your own methods, butalso when calling constructors and factory methods belonging to the MWArrayclasses.Nole There are some data types commonly used in MATLAB that arenot available as native Java types. Examples are cell arrays and arrays ofcomplex numbers. Represent these array types as instances of MWCeJJArrayand MWNuner1cArray, respectively.Underslonding Funclion 5ignolures Generoled by lheMAILA8 8uilder JA ProduclThe Java programming language now supports optional function argumentsin the way that MATLAB does with vararg1n and varargou1. To support thisfeature of MATLAB, the builder generates a single overloaded Java methodthat accommodates any number of input arguments. This behavior is anenhancement over previous versions of vararg1n support that only handled alimited number of arguments.Nole In addition to handling optional function arguments, the overloadedJava methods that wrap MATLAB functions handle data conversion. SeeAutomatic Conversion to MATLAB Types on page 3-4 for more details.Underslonding MAILA8 Funclion 5ignoluresAs background, recall that the generic MATLAB function has the followingstructure:func11on |0u11. 0u12. .... varargou1]=foo{1n1. 1n2. .... vararg1n)3-53 ProgrommlngTo the left of the equal sign, the function specifies a set of explicit and optionalreturn arguments.To the right of the equal sign, the function lists explicit input argumentsfollowed by one or more optional arguments.Each argument represents a MATLAB type. When you include the vararg1nor varargou1 argument, you can specify any number of inputs or outputsbeyond the ones that are explicitly declared.Overlooded Melhods in Jovo Ihol Encopsulole MAILA8 CodeWhen the MATLAB Builder JA product encapsulates your MATLAB code, itcreates an overloaded method that implements the MATLAB functions. Thisoverloaded method corresponds to a call to the generic MATLAB function foreach combination of the possible number and type of input arguments.In addition to encapsulating input arguments, the builder creates anothermethod, which represents the output arguments, or return values, of theMATLAB function. This additional overloaded method takes care of returnvalues for the encapsulated MATLAB function. This method of encapsulatingthe information about return values simulates the nJx interface in theMATLAB Compiler product.These overloaded methods are called the standard interface (encapsulatinginput arguments) and the nJx interface (encapsulating return values). SeeProgramming Interfaces Generated by the MATLAB Builder JA Producton page 8-12 for details.Adding Fields lo Dolo 5lruclures ond Dolo 5lruclureArroysWhen adding field