MATLAB BUILDER JA 2 Betriebsanweisung

Stöbern Sie online oder laden Sie Betriebsanweisung nach Software MATLAB BUILDER JA 2 herunter. MATLAB BUILDER JA 2 User`s guide Benutzerhandbuch

  • Herunterladen
  • Zu meinen Handbüchern hinzufügen
  • Drucken
  • Seite
    / 292
  • Inhaltsverzeichnis
  • LESEZEICHEN
  • Bewertet. / 5. Basierend auf Kundenbewertungen

Inhaltsverzeichnis

Seite 1 - Builder for

MATLAB®Builder forJava™The Language of Technical ComputingComputationVisualizationProgrammingUser’s GuideVersion 1

Seite 2 - Natick, MA 01760-2098

1 Getting StartedWhat Is MATLAB Builder for Java?MATLAB Builder for Java (also called Java Builder) is an extension toMATLAB Compiler. Use Java Builde

Seite 3 - Contents

4 Using MWArra y ClassesFactory Method UsagenewInstance(int[], Object)New logical array. Values areinitialized with supported data.newSparse(int[], in

Seite 4 - Programming

Guidelines for Working with MWArray ClassesMWLogicalArray a1 = MWLogicalArray.newInstance(dims, x1);MWLogicalArray a2 = MWLogicalArray.newInstance(dim

Seite 5 - Sample A

4 Using MWArra y Classesdouble, float, byte, short, int, long, java.lang.Boolean, subclasses ofjava.lang.Number,andjava.lang.String.Examples of Using

Seite 6 - Functions — Alphabetical List

Guidelines for Working with MWArray ClassesConstructing an MWCharArrayThe MWCharArray class provides a set of constructors and factory methods forcrea

Seite 7 - ... A-3

4 Using MWArra y ClassesConstructing an N-Dimensional Character Array. You can create amultid imensio nalchar array using a multidimensional array of

Seite 8

Guidelines for Working with MWArray ClassesThe a1, a2,anda3 arrays constructed all contain a 2-by-14 MATLAB chararray. The column count of the array i

Seite 9 - Getting Started

4 Using MWArra y Classesnew Character('g')};int[] dims = {1, 8};MWCharArray a1 = MWCharArray.newInstance(dims, x1);MWCharArray a2 = MWCharAr

Seite 10 - 1 Getting Started

Guidelines for Working with MWArray ClassesMethod Usageset(int,Object)Replaces the element at the one-based index with thesupplied value (inherited fr

Seite 11 - Using the Deploy

4 Using MWArra y ClassesUsing MWCellArray ConstructorsThe MWCellArray class provides the following constructors:Constructor UsageMWCellArray()Empty ce

Seite 12

Guidelines for Working with MWArray ClassesHere, each cell is initialized with a Java a rray, and default conversion rulesare used to create the MATLA

Seite 13 - Creating a Java Component

What Is MATLAB Builder for Java?Using the Deployment ToolThe Deployment Tool provides a graphical user interface to Java Builder.Whileyouarestill in M

Seite 14

4 Using MWArra y Classesif (x != null)x.dispose();throw new MWException(e.getMessage());}}This me tho d creates a n ew MWCellArray of the necessary si

Seite 15 - CreatingaJavaComponent

Guidelines for Working with MWArray ClassesMethod Usageset(int, Object)Replaces the element at the one-based index with thesupplied value (inherited f

Seite 16

4 Using MWArra y Classes}}finally{if (c != null)c.dispose();}}This method loops through the array and prints the type of each ce ll. Thetemporary arra

Seite 17

Guidelines for Working with MWArray Classesindex[1] = 2;double[][] x12 = (double[][])a.get(index);index[0] = 2;boolean[][] x22 = (boolean[][])a.get(in

Seite 18

4 Using MWArra y ClassesUsing Class MethodsUse MWArray classes to construct data types as needed in y our Java code.You can use the following classes

Seite 19

Using Class MethodsExample. Construct an empty MWArray object:MWArray A = new MWArray();Methods to Create and Destroy an MWArrayUse these methods to d

Seite 20 - Developing an Application

4 Using MWArra y ClassesdisposeArray. This method destroys any native MATLAB arrays containedin the input object and frees the m emory occupied by the

Seite 21

Using Class MethodsMethod Description“classID” on page 4-41 Returns the MATLAB type of the array.“getDimensions” on page 4-42 Returns the size of each

Seite 22 - Deploying an Application

4 Using MWArra y ClassesWhen run, the example displays this output:Class of A is int32getDimensions. This method returns a one-dimensional int arrayco

Seite 23 - Example: Magic Square

Using Class MethodsExample — Testing for an Empty MWArrayDisplay a message if array object A is an empty array. Otherwise, displaythe contents ofA:if

Seite 24

1 Getting StartedUse the Deployment Tool to perform the follo wing tasks:1-4

Seite 25 - Example: Magic S quare

4 Using MWArra y ClassesThe prototype for the numberOfElements method is as follows:public int numberOfElements()Input ParametersNoneExample — Getting

Seite 26

Using Class Methodsget. This method returns the element located at the specified one-based offsetor index array in the array object. The e lem ent is

Seite 27

4 Using MWArra y ClassesExample—GettinganMWArrayValuewithgetRetrieve element (2, 4) from array object A:int[] index = {2, 4};Object d_out = A.get(inde

Seite 28

Using Class MethodsSystem.out.println();When run, the example displays this output:Data read from matrix A is:171328143915410165111761218set. This met

Seite 29

4 Using MWArra y ClassesExceptionsThe set method throws the following exception:IndexOutOfBoundsExceptionThe specified index parameter is invalid.Exam

Seite 30

Using Class MethodsExample — Getting an MWArray with toArrayCreate and d isplay a copy of MWArray object A:int[][] x = (int[][]) A.toArray();int[] dim

Seite 31 - Importing Classes

4 Using MWArra y ClassesMethod Description“sharedCopy” onpage 4-53Creates and returns a shared copy of this array.“toString” on page4-54Returns a stri

Seite 32

Using Class MethodsWhen run, the example displays this output:Clone of matrix A is:1234567 8 910111213 14 15 16 17 18compareTo. This method compares t

Seite 33 - For More Information

4 Using MWArra y Classesequals. This method indicates the MWArray obje ct is equal to the inputobject. Theequals method of the MWArray classoverridest

Seite 34

Using Class MethodsExample — Getting an MWArray Hash CodeObtain the hash code for MWArray object A:System.out.println("Hash code for matrix A is

Seite 35 - Concepts

CreatingaJavaComponentCreating a Java ComponentTo create a component you need to write M-code (or use existing code) andthen create a project in MATLA

Seite 36 - 2 Concepts

4 Using MWArra y ClassestoString. This method returns a string representation of the array. ThetoString method of the MWArray classoverridesthetoStrin

Seite 37 - What Is a Project?

Using Class MethodsMethod Description“maximumNonZeros”on page 4-57Returns the allocated capacity of a sparse array.If the underlying array is nonspars

Seite 38

4 Using MWArra y ClassesInput ParametersNoneExample — Testing an MWArray for SparsenessTest the MWArray object A created previously for sparseness:if

Seite 39 - Class Hierarchy

Using Class MethodsrowIndex. This method returns an array containing the row index of eachelement in the underlying MATLAB array.The prototype for the

Seite 40

4 Using MWArra y ClassesExample — Getting the Maximum Number of Nonzeros in anMWArrayDisplay the maximum number of nonzeros for this array:System.out.

Seite 41 - ReturningDatafromMATLABtoJava

Using Class Methods• “Methods to Create and Destroy an MWNumericArray” on page 4-63• “Methods to Get and Set the Real Parts of an MWNumericArray” on p

Seite 42

4 Using MWArra y ClassesExample — Constructing an Empty Numeric Array ObjectCreate an empty scalar o f type int64:MWNumericArray A = new MWNumericArra

Seite 43 - 5 Invokes the J

Using Class MethodsA nonnumeric array type was specified.Example — Constructing an Integer Array ObjectConstruct a scalar numeric array of type MWClas

Seite 44

4 Using MWArra y ClassesMWClassID classid)The type javatype canbeanyofthefollowing:•double• float• long• int• short• byte• boolean• ObjectExample — Co

Seite 45 - .ctf file

Using Class MethodsMWNumericArray A =new MWNumericArray(AReal, AImag, MWClassID.DOUBLE);System.out.println("Array A of type " + A.classID()

Seite 46

1 Getting StartedThe .ctf is a component technology file, which is required to supportcomponents that encapsulate MATLAB functions when running them o

Seite 47

4 Using MWArra y ClassesTo construct an uninitialized real or complex numeric array, use the following:newInstance(int[] dims, MWClassID classid, MWCo

Seite 48 - Impor t Classes

Using Class Methods• short[]• byte[]• boolean[]• One-dimensional arrays of any subclass of java.lang.Number• One-dimensional arrays of java.lang.Boole

Seite 49

4 Using MWArra y ClassesWhen run, the example displays this output:A=1234567 8 910111213 14 15 16 17 18newSparse. This method constructs a real or com

Seite 50 - 3 Programming

Using Class MethodsnewSparse(int[] rowindex, int[] colindex, Object realData,int rows, int cols, int nzmax, MWClassID classid)Constructing a Sparse Ma

Seite 51

4 Using MWArra y ClassesRow and column index arrays are used to construct the sparse array such thatthe following holds true, with space allocated for

Seite 52

Using Class MethodsExceptionsThe newSparse method throws the following exceptions:NegativeArraySizeExceptionRow or column size is negative.IndexOutOfB

Seite 53

4 Using MWArra y Classes(1,4) 16.0000 +41.0000i(2,5) 0 + 2.0000iExample — Using newSparse with Row and Column IndicesConstruct a sparse MWNumericArray

Seite 54

Using Class MethodsSystem.out.println("A = " + A.toString());When run, the example displays this output:(2,1) 50(2,2) 60(1,5) 40(2,5) 250dis

Seite 55 - Specifying Optional Arguments

4 Using MWArra y ClassesclassID. MWNumericArray inherits this method from the MWArray class.complexity. This method returns the complexity of theMWNum

Seite 56

Using Class MethodsInput ParametersvaluedoublevaluetotestforfinitenessExample — Testing for Finite Array ValuesTest x for finiteness:double x = 25;if

Seite 57

CreatingaJavaComponentUsing the Command Line to Create Java ComponentsAction to Performmcc Option to Use Description-W java:Tells Java Builder to gene

Seite 58

4 Using MWArra y ClassesTest x for infin ity:double x = 1.0 / 0.0;if (MWNumericArray.isInf(x))System.out.println("The input value is infinite&quo

Seite 59

Using Class MethodsnumberOfDimensions. MWNumericArray inherits this method from theMWArray class.numberOfElem ents.MWNumericArray inherits this method

Seite 60

4 Using MWArra y ClassesThefollowingsyntaxappliestoalltheabovemethodsexceptgetData andtoArray.Calling Sy n ta x. To get the element at a specific inde

Seite 61

Using Class MethodsUse either of the following prototypes for the getDouble method, where indexcan be of type int or int[]:public double getDouble(int

Seite 62

4 Using MWArra y ClassesUse either of the following prototypes for the getShort method, where indexcan be of type int or int[]:public short getShort(i

Seite 63

Using Class MethodsSystem.out.println("Setting A(2, 3) to a new value ...");A.set(idx, 555);System.out.println("");System.out.prin

Seite 64

4 Using MWArra y ClassesMethod Description“getImagFloat” onpage 4-84Returns the imagin ary part at the specified offset asafloat value.“getImagLong” o

Seite 65

Using Class MethodsIn the case where index is of type int, the valid range for index is 1<=index<= N,whereN is the total number of elements in t

Seite 66

4 Using MWArra y ClassesSystem.out.println(A.toString());Here is the complex array that is displayed:2.0000 + 6.0000i 3.0000 + 5.0000i 4.0000 + 14.000

Seite 67

Using Class MethodsSystem.out.println("The real data in matrix A is:");x = (double[]) A.getData();for (int i = 0; i < x.length; i++)Syste

Seite 68

1 Getting StartedUsing the Comm and Line to Create Java Components (Contin ued)Action to Performmcc Option to Use Descriptionclass{...}Used with -W ja

Seite 69

4 Using MWArra y ClassesSystem.out.println("The imaginary part of A(2,3) = " +A.getImagDouble(index));When run, the example displays this ou

Seite 70

Using Class MethodsUse either of the following prototypes for the getImagShort method, whereindex can be of type int or int[]:public short getImagShor

Seite 71 - Managing Native Resources

4 Using MWArra y ClassesExceptionsThese methods throw the following exception:IndexOutOfBoundsExceptionThe specified index parameter is invalid.toImag

Seite 72

Using Class MethodsWhen run, the example displays this output:The imaginary part of matrix A is:6.0 5.0 14.07.0 1.0 23.01.0 1.0 9.0Methods to Copy, Co

Seite 73

4 Using MWArra y ClassesInput ParametersNoneExceptionsThe clone method throws the following exception:java.lang.CloneNotSupportedExceptionThe object’s

Seite 74

Using Class Methodsequals. MWNumericArray inherits this m ethod from the MWArray class.hashcode.MWNumericArray inherits this method from the MWArray c

Seite 75 - Array A is of type int16

4 Using MWArra y ClassesMethods to Use on Sparse MWNumericArraysUse these methods to return information on sparse arrays of typeMWNumericArray. All ar

Seite 76

Using Class MethodsMethod Description“getEps” onpage 4-91Get the value represented byEPS (floating-point relativeaccuracy) in M ATLAB.“getInf” on pag

Seite 77 - UsingMWArrayClasses

4 Using MWArra y ClassesExceptionsNonegetNaN. This m ethod returns the M ATLAB concept ofNaN,whichstandsfor "Not a Number".The p rototype fo

Seite 78

Using Class MethodsMWLogicalArray()Constructing an Initialized Logical Scalar or Array. Use this constructorsyntax to create aMWLogicalArray scalar or

Seite 79

CreatingaJavaComponentUsing the Comm and Line to Create Java Components (Contin ued)Action to Performmcc Option to Use Description-BTells Java Builder

Seite 80

4 Using MWArra y ClassesMethod Description“newInstance” onpage 4-94Constructs a logical array with the specifieddimensions.“newSparse” onpage 4-95Cons

Seite 81

Using Class MethodsExceptionsThe newInstance method throws the following exceptions:NegativeArraySizeExceptionThe specified dims para m eter is negati

Seite 82

4 Using MWArra y ClassesTo construct a sparse logical matrix with no nonzero elements, use thefollowing:public static MWLogicalArray newSparse(int row

Seite 83 - Constructing Numeric Arrays

Using Class MethodsS(rowIndex(k), colIndex(k)) = data(k)rowsand colsNumber o f rows and columns in the m atrixnzmaxMaximum number of nonzero elementsV

Seite 84

4 Using MWArra y ClassesThe specified index parameter is invalid.ArrayStoreExceptionIncompatible array type or invalid array dataExample — Constructin

Seite 85 - Constructing Complex Arrays

Using Class MethodsMethod Description“getDimensions” on page4-100Returns an array containing the size of eachdimension of this a rray.“isEmpty” on p a

Seite 86

4 Using MWArra y ClassesWhen run, the example displays this output:Class of A is logicalgetDimensions.MWLogicalArray inherits this m ethod from the MW

Seite 87 - Constructing Jagged Arrays

Using Class MethodsgetBoolean. This method returns the element located at the specifiedone-based index of theMWLogicalArray object.To get the element

Seite 88

4 Using MWArra y ClassesExample — Getting a Boolean Value from a Logical Arrayboolean[][] Adata = {{true, false, false},{false, true, false}};MWLogica

Seite 89

Using Class MethodsInthecasewhereindex is of type int[],eachelementoftheindex vectoris an index along one dimension of theMWLogicalArray object. The v

Seite 90

1 Getting StartedUsing the Comm and Line to Create Java Components (Contin ued)Action to Performmcc Option to Use Description-STells Java Builder to c

Seite 91 - Constructing Sparse Arrays

4 Using MWArra y ClassesSetting A(2,3) to trueArray element A(2,3) is truetoArray. MWLogicalArray inherits this method from the MWArray class.Methods

Seite 92

Using Class Methodspublic Object clone()Input ParametersNoneExceptionsThe clone method throws the following exception:java.lang.CloneNotSupportedExcep

Seite 93

4 Using MWArra y ClasseshashCode. MWLogicalArray inherits this method from the MWArray class.sharedCopy. This method creates and returns a shared copy

Seite 94

Using Class MethodsMethods to Use on Sparse MWLogicalArraysUse these methods to return information on sparse arrays of typeMWLogicalArray. All are inh

Seite 95

4 Using MWArra y ClassesConstructing an MWCharArrayUse the tables in this section to construct an MWCharArray from a particularJava data type. See the

Seite 96

Using Class Methodschar[] chArray2 = {'W', 'o', 'r', 'l', 'd'};MWCharArray A = new MWCharArray(chArr

Seite 97

4 Using MWArra y ClassesTo construct a MWCharArray object w ith the specified dimensions, usepublic static MWCharArray newInstance(int[] dims)The elem

Seite 98

Using Class MethodsdisposeArray. MWCharArray inherits this method from the MWArray class.Methods to R eturn Information About an MWCharArrayUse these

Seite 99

4 Using MWArra y ClassesWhen run, the example displays this output:The class of A is chargetDimensions.MWCharArray inherits this method from the MWArr

Seite 100 - 4 Using MWArra y Classes

Using Class MethodsgetChar. This method returns the character located at the specifiedone-based index of theMWCharArray object.Togettheelementataspeci

Seite 101

CreatingaJavaComponentNote All of t hese com m and-line examples produce the following files:mycomponent.jar (com ponent jar file)mycomponent.ctf (com

Seite 102

4 Using MWArra y ClassesExample — Getting Character Array Data with getCharUse getChar to display the string stored in MWCharArray object A:char[] chA

Seite 103 - Constructing an MWCharArray

Using Class MethodsInthecasewhereindex is of type int[],eachelementoftheindex vectoris an index along one dimension of theMWCharArray object. The vali

Seite 104

4 Using MWArra y ClassestoArray. MWCharArray inherits this method from the MWArray class.Methods to Copy, Convert, and Compare MWCharArraysUse these m

Seite 105

Using Class MethodsExample — Cloning a Character Array ObjectCreate a clone of MWCharArray object A:char[] chArray = {'H', 'e', &a

Seite 106

4 Using MWArra y ClassesExample — Making a Shared Copy of a Character Array ObjectCreate a shared copy of MWCharArray object A:char[] chArray = {&apos

Seite 107 - Working with Cell Arrays

Using Class MethodsTo construct an MWStructArray object with the specified dimensions andfield n ames, useMWStructArray(int[] dims, java.lang.String[]

Seite 108

4 Using MWArra y ClassesThe second example creates a 1-by-2 MWStructArray obje ct with fields f1,f2,andf3:int[] sdims = {1, 2};String[] sfields = {&qu

Seite 109

Using Class MethodsExample—DisposingofaStructureArrayObjectint[] sdims = {1, 2};String[] sfields = {"f1", "f2", "f3"};MW

Seite 110

4 Using MWArra y ClassesMethod Description“numberOfDimensions” onpage 4-123Returns the number o f dimensions of thisarray.“numberOfElements” onpage 4-

Seite 111

Using Class Methodspublic java.lang.String[] fieldNames()Input ParametersNoneExample — Getting the Field Names of a Structure ArrayCreate an MWStructA

Seite 112

How to Contact The MathWorkswww.mathworks.comWebcomp.soft-sys.matlab Newsgroupwww.mathworks.com/contact_TS.html Technical [email protected]

Seite 113

1 Getting StartedDeveloping an Application1 If the co mponent is not already i nstalled on t h e machin e where you want todevelop your application, u

Seite 114 - Using Class Methods

4 Using MWArra y Classespublic int numberOfFields()Input ParametersNoneExample — Getting the Number of Fields in a Structure ArrayCreate an MWStructAr

Seite 115 - Input Parameters

Using Class MethodsMethod Description“getField”on page4-128Returns a shared copy of the element at the specifie d one-basedoffset and field name in th

Seite 116

4 Using MWArra y ClassesindexIndex of the requested element in the MWStructArrayIn the case where index is of type int, the valid range for index is 1

Seite 117

Using Class MethodsStructure data S(1,1).f2 is 555getData. This method returns a one-dimensional array containing a copyof the data in the underlying

Seite 118

4 Using MWArra y ClassesMWArray[] x = (MWArray[]) S.getData();for (int i = 0; i < x.length; i++)System.out.print(" " + x[i]);When run, th

Seite 119

Using Class MethodsField name of the requested elementindexIndex of the requested element in the MWStructArrayIn the case where index is of type int,

Seite 120

4 Using MWArra y Classessecond syntax (int[] index) to return the element at the specified array ofone-based indices. The first syntax offers better p

Seite 121 - Exceptions

Using Class MethodsExample — Setting Values in a Structure Arrayint[] sdims = {1, 2};String[] sfields = {"f1", "f2", "f3"

Seite 122

4 Using MWArra y ClassesInput ParametersNoneExample — Getting Structure Array Data with toArrayint[] sdims = {1, 2};String[] sfields = {"f1"

Seite 123

Using Class MethodsMethod Description“clone” on page4-133Creates and returns a deep copy of this array.“compareTo”on pag e 4-134Compares this array wi

Seite 124

Developing an Application• To manually convert to one of the standard MATLAB data types, useMWArray classes in the packagecom.mathworks.toolbox,javabu

Seite 125

4 Using MWArra y ClassesExample — Cloning a Structure Array ObjectCreate an MWStructArray object and then a clone of that object:int[] sdims = {1, 2};

Seite 126

Using Class MethodsInput ParametersNoneExample — Making a Shared Copy of a Structure Array ObjectCreate an MWStructArray object and then a shared copy

Seite 127

4 Using MWArra y ClassesConstructing an MWCellArrayUse the tables in this section to construct an MWCellArray from a particularJava data type. See the

Seite 128

Using Class MethodsExample — Constructing an Empty Cell Array ObjectThis first example creates an empty MWCellArray object:MWCellArray C = new MWCellA

Seite 129

4 Using MWArra y ClassesMethod Description“dispose” onpage 4-138Frees the native MATLAB array contained by this array.“disposeArray”on page 4-138Frees

Seite 130

Using Class MethodsMethod Description“classID” on page 4-139 Returns the M ATLAB type of this array.“getDimensions” on page4-139Returns an array conta

Seite 131

4 Using MWArra y ClassesisEmpty. MWCellArray inherits this method from the MWArray class.numberOfDimensions.MWCellArray inherits this m ethod from the

Seite 132

Using Class MethodsUse the first syntax (int index) to return the ele ment at the specifiedone-based offset in the a rray, accessing elements in colum

Seite 133

4 Using MWArra y ClassesC.set(index, val);Object x = C.get(index);System.out.println("Cell data C(1,3) is " + x.toString());When run, the ex

Seite 134

Using Class MethodsExceptionsThe getCell method throws the following exception:IndexOutOfBoundsExceptionThe specified index parameter is invalid.getDa

Seite 135

1 Getting StartedDeploying an ApplicationTo deploy your application you must make sure that the installer you createfor the application takes care of

Seite 136

4 Using MWArra y ClassesSystem.out.println("Data read from cell array C: \n");MWArray[] x = (MWArray[]) C.getData();for (int i = 0; i < x

Seite 137

Using Class MethodsindexIndex of the requested element in the MWCellArrayIn the case where index is of type int, the valid range for index is 1<=in

Seite 138

4 Using MWArra y ClassestoArray. This method returns an array containing a copy of the data in t h eunderlying MATLAB array.The prototype for thetoArr

Seite 139

Using Class MethodsMethods to Copy, Convert, and Compare MWCellArraysUse these methods to copy, convert, and compare objects of class MWCellArray.Meth

Seite 140

4 Using MWArra y ClassesExceptionsThe clone method throws the following exception:IndexOutOfBoundsExceptionThe specified index parameter is invalid.Ex

Seite 141

Using Class Methodspublic Object sharedCopy()Input ParametersNoneExample — Making a Shared Copy of a Cell Array ObjectCreate an MWCellArray object and

Seite 142

4 Using MWArra y ClassesCHAR. CHAR represents MATLAB array type char.DOUBLE.DOUBLE represents MATLAB array type double.FUNCTION.FUNCTION represents MA

Seite 143

Using Class MethodsUINT32. UINT32 represents MATLAB array type uint32.UINT64.UINT64 represents MATLAB array type uint64.UNKNOWN.UNKNOWN represents MAT

Seite 144

4 Using MWArra y ClassesThe p rototype for hashCode is a s follows:public final int hashCode()isNumeric. Thismethodtestsifthistypeisnumeric.The p roto

Seite 145

Using Class MethodsExample – Determining the Complexity of an ArrayDetermine whether matrix A is real or complex. The complexity method ofMWNumericArr

Seite 146

Example: Magic S quareExample: Magic SquareThis example shows you how to:• Access the online examples provided with MATLAB Builder for Java.• Use MATL

Seite 147

4 Using MWArra y Classes4-154

Seite 148

5Sample Applications (Java)Note The examples for MATLAB Builder for Java are inmatlabroot\toolbox\javabuilder\Examples.In addition to these examples,

Seite 149

5 Sample Applications (Java)Plot ExampleThe purpose of the example is to show you how to do the following:• UseMATLABBuilderforJavatoconvertaMATLABfun

Seite 150

Plot Exampleplot(x,y);This code is already in your work d irectory inPlotExample\PlotDemoComp\drawplot.m.4 Specify a Java component as follows :a. Whi

Seite 151

5 Sample Applications (Java)The program listing is shown here.createplot.java/* createplot.java* This file is used as an example for the MATLAB* Build

Seite 152

Plot Examplex.set(i, i);y.set(i, i*i);}/* Create new plotter object */thePlot = new plotter();/* Plot data */thePlot.drawplot(x, y);}catch (Exception

Seite 153

5 Sample Applications (Java)• Uses a try-catch block to catch and handle any exceptions.7 Compile the createplot application using javac.a. On Windows

Seite 154

Plot ExampleNote The supported JRE version is 1.5.0. To find out what JRE you areusing, refer to the output of'version -java' in MATLAB or r

Seite 155 - MWNumericArray

5 Sample Applications (Java)Spectral Analysis ExampleThe purpose of the example is to show you the following:• How to use MATLAB Builder for Java to c

Seite 156

Spectral Analysis Examplepowerspect = [];return;endif (interval <= 0)error('Sampling interval must be greater then zero');return;endfftDa

Seite 157

1 Getting Startedmatlabroot\toolbox\javabuilder\Examples\MagicSquareExampleThis procedure assumes that you are working on Windows and yourwork directo

Seite 158

5 Sample Applications (Java)2 If you have not already done so, set the environment variables that arerequired on a d ev elo pm ent machine. See “Setti

Seite 159

Spectral Analysis Example6 W rite source code for an application that accesses the component.The sample application for this example is inSpectraExamp

Seite 160

5 Sample Applications (Java)* Sampling interval = 0.01*/int[] dims = {1, nSamples};data = MWNumericArray.newInstance(dims, MWClassID.DOUBLE,MWComplexi

Seite 161

Spectral Analysis ExampleThe program does the following:• Constructs an input array with values representing a random signalwith two sinusoids at 15 a

Seite 162

5 Sample Applications (Java).;matlabroot\java\jar\toolbox\javabuilder.jar;.\distrib\spectralanalysis.jar-Djava.library.path=matlabroot\bin\win32;.\dis

Seite 163

Spectral Analysis Example5-15

Seite 164

5 Sample Applications (Java)Matrix Math ExampleThe purpose of the example is to show you the following:• How to assign more than one MATLAB function t

Seite 165

Matrix Math Example%CHOLESKY Cholesky factorization of A.% L = CHOLESKY(A) returns the Cholesky factorization of A.% This file is used as an example f

Seite 166

5 Sample Applications (Java)b. At the MATLAB command prompt, cd to the new MatrixMathExamplesubdirectory in your w ork directory.2 If you have not alr

Seite 167

Matrix Math Examplegetfactor. ja va/* getfactor.java* This file is used as an example for the MATLAB* Builder for Java product.** Copyright 2001-2006

Seite 168

Example: Magic S quareWhen you create a new project, the Deploy ment Tool dialog bo x shows thefolders that are part of the project. By default the to

Seite 169

5 Sample Applications (Java)if (n <= 0){System.out.println("Error: must input a positive integer");return;}/** Allocate matrix. If second

Seite 170

Matrix Math Exampleresult = theFactor.cholesky(1, a);System.out.println("Cholesky factorization:");System.out.println(result[0]);MWArray.dis

Seite 171 - Supported Prototypes

5 Sample Applications (Java)creates an instance of the class factor.The following statements call the methods that encapsulate the MATLABfunctions:res

Seite 172

Matrix Math Example• On UNIX, execute the getfactor classfileasfollows:java -classpath.:matlabroot/java/jar/toolbox/javabuilder.jar:./distrib/factorma

Seite 173

5 Sample Applications (Java)0 1.5000 -1.0000 00 0 1.3333 -1.00000 0 0 1.2500QR factorization:Q matrix:-0.8944 -0.3586 -0.1952 0.18260.4472 -0.7171 -0.

Seite 174

Matrix Math Example(1,1) 1.4142(1,2) -0.7071(2,2) 1.2247(2,3) -0.8165(3,3) 1.1547(3,4) -0.8660(4,4) 1.1180LU factorization:L matrix:(1,1) 1.0000(2,1)

Seite 175

5 Sample Applications (Java)(4,3) -0.6831(1,4) 0.1826(2,4) 0.3651(3,4) 0.5477(4,4) 0.7303R matrix:(1,1) 2.2361(1,2) -1.7889(2,2) 1.6733(1,3) 0.4472(2,

Seite 176

6Reference Information forJavaRequirem en ts for MATLAB B u i lderfor Java (p. 6-2)Software requirements for usingMATLAB Builder for JavaMATLAB Builde

Seite 177

6 Reference Infor mation for JavaRequirements for MATLAB Builder for Java• “System Requirements” on page 6-2• “Limitations and Restrictions” on page 6

Seite 178

Requirements for MAT LAB Builder for Java• “Java CLASSPATH Variable” on page 6-4• “Native Library Path Variables” on page 6-6JAVA_HOME VariableJava Bu

Seite 179

1 Getting Started8 Access the component in a Java application. The sample application for thisexample is inMagicSquareExample\MagicDemoJavaApp\getmagi

Seite 180

6 Reference Infor mation for Javasetenv JAVA_HOME /java/jdk/j2sdk1.5.0Alternatively, you can add jdk_directory\bin to the system path.Java CLASSPATH V

Seite 181

Requirements for MAT LAB Builder for JavaNote For matlabro ot substitute the MATLAB root directory on your system .Typematlabroot to see this director

Seite 182

6 Reference Infor mation for Javajavac -classpath.:/matlabroot/toolbox/javabuilder/jar/javabuilder.jar:/mycomponent/mycomponent.jar usemyclass.javawhe

Seite 183 - Using MWCharArray

MATLAB Builder for Java Graphical User InterfaceMATLAB Builder for Java Graphical User Inter faceUse the MATLAB Builder for Java graphical user interf

Seite 184

6 Reference Infor mation for JavaNote that the Deployment Tool window can be docked or undocked.The Deploym ent To ol toolbar has the fo llow ing icon

Seite 185

MATLAB Builder for Java Graphical User InterfaceToolbar Icons (Continued)Name of Toolbar IconIconClick to...RemoveRemove the selected class folderor t

Seite 186

6 Reference Infor mation for JavaData Conversion Rules• “Java to MATLAB Conversion” on page 6-10• “MATLAB to Jav a Conversion” on page 6-12• “Unsuppor

Seite 187

Data Conversion RulesJava to MATLAB Conversion Rules (Continued)Java Type MATL AB Typejava.lang.Float singlejava.lang.Byte int8java.lang.Integer int32

Seite 188

6 Reference Infor mation for JavaMATLAB to Java ConversionThe following table lists the data conversion rules for converting MATLABdata types to Java

Seite 189

Data Conversion RulesMATLAB to Java Conversion Rules (Continued)MATLAB Type Java Type (Primitive) Java Type (Object)uint16 shortjava.lang.shortJava ha

Seite 190

Example: Magic S quareSystem.out.println("Magic square of order " + n.toString());/* Create new magic object */theMagic = new magic();/* Com

Seite 191

6 Reference Infor mation for JavaProgramming Interfaces Generated by Java Builder• “APIs Based on MATLAB Function Signatures” on page 6-14• “Standard

Seite 192

Programming Interfaces Generated by Java BuilderTypically you use the standard interface when you want to call MATLABfunctions that return a single ar

Seite 193

6 Reference Infor mation for Javaby thevararginargumentObject in2,...,ObjectInN,Object varargin)Details about the a rguments for these samples of stan

Seite 194

Programming Interfaces Generated by Java Buildermlx APIFor a function with the following structure:function [Out1, Out2, ..., varargout] =foo(In1, In2

Seite 195

6 Reference Infor mation for Java{(implementation omitted)}The standard interface specifies inputs to the function within the argumentlist and outputs

Seite 196

MWArray Class SpecificationMWArray Class SpecificationFor complete refere nce information about the MWArray class hierarchy,seecom.mathworks.toolbox.j

Seite 197

6 Reference Infor mation for Java6-20

Seite 198

7Functions — AlphabeticalList

Seite 199

deploytoolPurpose Open GUI for MATLAB Builder for Java and MATLAB CompilerSyntax deploytoolDescription The deploytool command opens the Deployment Too

Seite 200

AExamplesUse this list to find examples in the d o cumentation.

Seite 201 - in this

1 Getting StartedMATLAB function, nargout, in the method being called. The second inputargument is the input specified in the function declaration sta

Seite 202

A ExamplesQuick Start“Example: MagicSquare” on page 1 -15Handling Data“Code Fragment: Passing an MWArray” on page 3-7“Code Fragment: Passing a Java Do

Seite 203

Handling MemoryHandling Memory“Code Fragment:Use try-finally to Ensure Resources Are Freed” on page3-27Sample Applications (Java)“Plot Example” on pag

Seite 204

A ExamplesA-4

Seite 205

IndexIndexAAPIdata conversion classes 3-6MATLAB Builder for Java 4-1argumentsoptional 3-9standard interface 3-13optional inputs 3-10optional outputs 3

Seite 206

Indexconstructingcell arrays 4-32character arrays 4-27logical a rrays 4-22mwarrays 4-38mwcellarrays 4-136mwchar arrays 4-10 8mwlogicalarrays 4-92mwnum

Seite 207

Indexmwnumericarray 4-58comparing 4 -87constants 4-90constructors 4-59converting 4-87copying 4-87creating 4 -63disposing 4-63get information on 4-71ge

Seite 208

Indextry-finally 3-27Ggarbage collection 3 -25get 4-5mwarray 4-45mwcellarray 4-34 4-140mwchararray 4-30 4-112mwlogicalarray 4-25 4-100mwnumericarray 4

Seite 209

Indexmwclassid 4-151mwlogicalarray 4-106mwnumericarray 4-89mwstructarray 4-134Iimporting classe s 1-23isempty 4-5mwarray 4-42mwcellarray 4-140mwcharar

Seite 210

Indexmwlogicalarray 4-92comparing 4 -104constructors 4-92converting 4-104copying 4-104creating 4 -93disposing 4-93get information on 4-98get, set 4-10

Seite 211 - Using MWCellArray

Indexmwcellarray 4-34mwchararray 4-30mwlogicalarray 4-25mwnumericarray 4-17of MWArray 3-8 3-28multid imensional numeric array sconstructing 4-10mwarra

Seite 212

Example: Magic S quareb. On UNIX, execute this command:javac -classpath.:matlabroot/toolbox/javabuilder/jar/javabuilder.jar:./distrib/magicsquare.jar

Seite 213

Indexconverting 4-104copying 4-104creating 4 -93disposing 4-93get information on 4-98get, set 4-100newinstance 4-23newsparse 4-23sparse 4-107mwlogical

Seite 214

Indexinput 3-10output 3-12standard interface 3-13Ppassing arguments 3-6passing array inputs 3-11passing datamatlab to java 2-7path variable 6-6platfor

Seite 215

Indexmwstructarray 4-135try-finally 3-27Uunchecked exceptions 3-22usage informationdata conversion classes 4-1getting started 1-1sample Java applicati

Seite 216

ContentsGetting Started1What Is MATLAB Builder for Java?...1-2Support for MATLAB Features in Java...1-2KnownIssueinData Re

Seite 217

1 Getting StartedWhen you run the program you pass an argument representing the dimensionfor the magic square. In this example, the v alue for the dim

Seite 218

Understanding the Magic Square ExampleUnderstanding the Magic Square ExampleThe Magic Square example shows the following aspects of writing anapplicat

Seite 219

1 Getting Startedwhere n is an instance of an MWArray class. See the following code frag mentfor the declaration o fn:n = new MWNumericArray(Double.va

Seite 220

For More InformationFor More InformationUnderstanding concepts needed touse MATLAB B uilder for JavaChapter 2, “Concepts”Writing Java applications tha

Seite 221

1 Getting Started1-26

Seite 222

2ConceptsA component created by MATLAB Builder for Java is a stand-alone Javapackage (.jar file). ThepackagecontainsoneormoreJavaclassesthatencapsulat

Seite 223

2 ConceptsWhat Happens in the Build Process?(p. 2-9)Details about the process of buildinga Java componentWhat Happens in the PackageProcess? (p. 2-10)

Seite 224

What Is a Project?What Is a Project?A Java Builder project contains information about the files and settingsneeded by MATLAB Builder for Java to creat

Seite 225 - Using MWClassID

2 ConceptsHow Does MATLAB Builder for Java Handle Data?To enable Java applications to exchange data with MATLAB methodsthey invoke, Java Builder provi

Seite 226

How Does MATLAB Builder for Java H andle Data?Overview of Classes and Methods in the Data ConversionClass HierarchyThe root of the data conversion cla

Seite 227

How Does MATLAB Builder for Java Handle Data? ... 2-4Understanding the API Data Conversion Classes... 2-4Automatic Con version to MATLA B Types...

Seite 228

2 Conceptsclass before it is passed to the method. Java Builder can convert anyJava string, numeric type, or any multidimensional array of these types

Seite 229

How Does MATLAB Builder for Java H andle Data?Understanding MATLAB Function SignaturesAs background, recall that the generic MATLAB function has the f

Seite 230

2 ConceptsReturn data is not co nverte d to a Java ty pe. If yo u choo se to use a Java ty pe,you must convert to that type using thetoArray method of

Seite 231 - Sample Applications (Java)

What Happens in the Build Process?What Happens in the Build Process?Note MATLAB Builder for Java uses the JAVA_HOME variable to locate theJava Softwar

Seite 232 - Plot Example

2 ConceptsWhat Happens in the Package Process?The packaging process creates a self-extracting executable (on Windowsplatforms) or a.zip file (on non-W

Seite 233

How Does Component Deployment Work?How Does Component Deployment Work?There are two kinds of deployment:• Installing components and setting up support

Seite 235

3ProgrammingTo access a Java component built and packaged by M ATLAB Builder forJava, you must first unpack and install components so you can use them

Seite 236

3 ProgrammingImpor t ClassesTo use a component generated by MATLAB Builder for Java, you must dothe following:• Import MATLAB libraries with the Javai

Seite 237

Creating an Instance of the ClassCreating an Instance of the ClassAs with any Java class, you ne ed to instantiate th e classes you create withMATLAB

Seite 238 - Spectral Analysis Example

Handling Data Conversion Between Java andMATLAB... 3-28Calling MWA rray Methods... 3-28Usi

Seite 239

3 ProgrammingObject[] y = null;try{cls = new myclass();y = cls.myprimes(1, new Double((double)n));return (double[])((MWArray)y[0]).getData();}finally{

Seite 240

Creating an Instance of the Classmyprimes FunctionThe code for myprimes is as follows:function p = myprimes(n)% MYPRIMES Returns the primes between 0

Seite 241

3 ProgrammingPassing Argum ents to and from JavaWhen you invoke a method on a MATLAB Builder for Java component,the input arguments received by the me

Seite 242

Passing Arguments to and from JavaCode Fragment: Passing an MWArray. This example constructs anMWNumericArray of type MWClassID.DOUBLE.Thecalltomyprim

Seite 243

3 ProgrammingHere is another example:result = theFourier.plotfft(3, data, new Double(interval));In this Java statement, the third argument is of type

Seite 244

Passing Arguments to and from Javadouble Adata = 24;MWNumericArray A = new MWnumericArray(Adata);System.out.println("Array A is of type " +

Seite 245

3 Programmingy = sum([varargin{:}]);This function returns the sum of the inputs. The inputs are provided as avarargin argument, which means that the c

Seite 246 - Matrix Math Example

Passing Arguments to and from JavaM-function in the order in which they appear in the array. Here is an exampleof how you might use themysum method in

Seite 247

3 ProgrammingObject[] y = null;try{x = new Object[vals.length];for (int i = 0; i < vals.length; i++)x[i] = new MWNumericArray(vals[i], MWClassID.DO

Seite 248

Passing Arguments to and from Javavarargout{i} = rand(1, i);endThis function returns a list of random double vectors such that the lengthof theith vec

Seite 249

Reference Information for Java6Requirements for MATLAB Builder for Java ... 6-2System Requirements... 6-2Limitations

Seite 250

3 Programmingreturn ret;}finally{MWArray.disposeArray(y);if (cls != null)cls.dispose();}}The getrandvectors m ethod returns a two-dimensional double a

Seite 251

Passing Arguments to and from Javatry{cls = new myclass();y = cls.myprimes(1, new Double((double)n));Object a = ((MWArray)y[0]).toArray();if (a instan

Seite 252

3 Programming}else if (a instanceof byte[][]){byte[][] x = (byte[][])a;/* (do something with x...) */}else{throw new MWException("Bad type return

Seite 253

Passing Arguments to and from JavaMWClassID clsid = ((MWArray)y[0]).classID();if (!clsid.isNumeric() ||((MWArray)y[0]).numberOfDimensions() != 2){thro

Seite 254

3 Programming{short[][] x = (short[][])((MWArray)y[0]).toArray();/* (do something with x...) */}else if (clsid == MWClassID.INT8 ||clsid == MWClassID.

Seite 255

Handling ErrorsHandling ErrorsErrors that occur during execution of an M-function or during data conversionare s ignaled by a standard Java exception.

Seite 256

3 Programmingpublic Object[] myprimes(int nargout, Object n) throws MWException{(implementation omitted)}Any method that calls myprimes must do one of

Seite 257 - Reference Information for

Handling Errorsif (cls != null)cls.dispose();}}Note that in this case, it is the programmer’s responsibility to returnsomething reasonable from the me

Seite 258 - Machine)

3 Programmingcls.dispose();}}Handling Unchecked ExceptionsSeveral types of unchecked e xceptio ns can also occur during the course ofexecution. Unchec

Seite 259 - JAVA_HOME Variable

Handling Errorsy = cls.myprimes(1, new Double((double)n));return (double[])((MWArray)y[0]).getData();}/* Catches the exception thrown by anyone */catc

Seite 260 - Java CLASSPATH Variable

Handling Errors ... A-2Handling Memory... A-3Sample Applications (Java)...

Seite 261

3 ProgrammingSystem.out.println("Exception in MATLAB call: " +e.toString());return new double[0];}/* Catches all other exceptions */catch (E

Seite 262 - Native Library Path Variables

Managing Native ResourcesManaging Native ResourcesWhen your code accesses Java classes created by MATLAB Builder for Java,your program uses native res

Seite 263

3 Programmingheap, MWArray objects should be explicitly freed as soon as possible by theapplication that creates them.Using the dispose MethodThe best

Seite 264

Managing Native ResourcesThe MWArray class prov ides two disposal methods: dispose anddisposeArray.ThedisposeArray method is more general in that it d

Seite 265

3 ProgrammingHandling Data Conversion Between Java and MATLABThe call signature for a method that encapsulates a MATLAB function usesone of the MATLAB

Seite 266 - Data Conversion Rules

Handling Data Conversion Between Java and MATLABMWNumericArray A = new MWnumericArray(Adata, MWClassID.INT16);System.out.println("Array A is of t

Seite 267

3 Programming3-30

Seite 268 - MATLAB to Java Conversion

4UsingMWArrayClassesThe following topics explain how to use the data conversion classes in thecom.mathworks.toolbox.javabuilder.MWArray package.Guidel

Seite 269

4 Using MWArra y ClassesGuidelines for Wo rking with MWArray ClassesOverview of the MWArray APIThe MWArray Java API is a class hierarchy that represen

Seite 270

Guidelines for Working with MWArray ClassesMethod Overrides Implemented by MWArrayTo en sure integra t ion w ith Java program s, MWArray provides over

Seite 272

4 Using MWArra y ClassesJava Interfaces Implemented by MWArrayInterfaceMethod in MWArrayBase ClassDescription ofMethodCloneable clone(public method)Pr

Seite 273

Guidelines for Working with MWArray ClassesMethod UsagecolumnIndex()Returns the column index (seconddimension) of each element in the array.Call this

Seite 274 - (implementation omitted)

4 Using MWArra y ClassesMethod UsagemaximumNonZeros()Returns the current allocated capacity ofnonzero elements for a sparse array.numberOfDimensions()

Seite 275 - MWArray Class Specification

Guidelines for Working with MWArray ClassesMethod UsagesharedCopy()Creates a new MWArray instancethat represents a shared copy ofthe underlying MATLAB

Seite 276

4 Using MWArra y ClassesConstructor UsageMWNumericArray()Empty double arrayMWNumericArray (MWClassID)Empty array of type specified byMWClassIDMWNumeri

Seite 277 - Functions — Alphabetical

Guidelines for Working with MWArray ClassesSupported Data Types. In the previous table, type represents supportedJava types.MWNumericArray supports th

Seite 278 - Syntax deploytool

4 Using MWArra y ClassesNew Integer(2), MWClassID.INT32);MWNumericArray a4 = new MWNumericArray("1.0", "2.0",MWClassID.INT32);Cons

Seite 279 - Examples

Guidelines for Working with MWArray ClassesConstructing Jagged ArraysThe previous examples constructed rectangular Java arrays and used thesearrays to

Seite 280 - Handling Errors

4 Using MWArra y ClassesMWNumericArray a1 = new MWNumericArray(1.0);MWNumericArray a2 = new MWNumericArray(1, MWClassID.DOUBLE);MWNumericArray a3 = ne

Seite 281 - Handling Memory

Guidelines for Working with MWArray ClassesFactory Method UsagenewInstance(int[], Object,MWClassID)Real numeric array of specified type.Values are ini

Seite 282 - A Examples

1Getting StartedWhat Is MATLAB Builder for Java?(p. 1-2)Briefdescriptionofwhattheproductdoes and how it worksCreating a Java Component (p. 1-5)Step-by

Seite 283

4 Using MWArra y ClassesFactory Method UsagenewSparse(int[], int[],Object, Object, MWClassID)Complex sparse num eric ma trix ofspecified typ e. Values

Seite 284

Guidelines for Working with MWArray ClassesMWNumericArray.newInstance(dims, x1, MWClassID.DOUBLE);MWNumericArray a2 =MWNumericArray.newInstance(dims,

Seite 285

4 Using MWArra y Classes00-12]Calling newSparse. The call to newSparse passes three arrays: an array ofmatrix data (x), an array containing the row in

Seite 286

Guidelines for Working with MWArray ClassesNote Numeric sparse matrices are supported only for type double.Attempting to construct a sparse numeric ma

Seite 287

4 Using MWArra y ClassesMethod UsagesetImag(int, type)Replaces the imaginary part of the elementat the one-based index with the suppliedvaluesetImag(i

Seite 288

Guidelines for Working with MWArray ClassesExamples of Using set. T he following examples construct the 2-by-2 matrixof the p revious exam p le using

Seite 289

4 Using MWArra y Classesa.set(index, 2.0);else if (index[1] == index[0]+1 || index[1] == index[0]-1)a.set(index, -1.0);}}The example allocates the 4-b

Seite 290

Guidelines for Working with MWArray ClassesSystem.out.print("] = " + a.getDouble(dims));if (a.complexity() == MWComplexity.COMPLEX)System.ou

Seite 291

4 Using MWArra y Classesfor (index[0] = 1; index[0] <= dims[0]; index[0]++)sum += row[index[0]-1]*b.getDouble(index);result[i][index[0]] = sum;}}re

Seite 292 - Index-10

Guidelines for Working with MWArray ClassesThese examples construct a scalar logical array initialized to false:MWLogicalArray a1 = new MWLogicalArray

Kommentare zu diesen Handbüchern

Keine Kommentare