MATLAB REAL-TIME WORKSHOP 7 - TARGET LANGUAGE COMPILER Manuel d'utilisateur

Naviguer en ligne ou télécharger Manuel d'utilisateur pour Logiciel MATLAB REAL-TIME WORKSHOP 7 - TARGET LANGUAGE COMPILER. MATLAB REAL-TIME WORKSHOP 7 - TARGET LANGUAGE COMPILER User`s manual Manuel d'utilisatio

  • Télécharger
  • Ajouter à mon manuel
  • Imprimer
  • Page
    / 408
  • Table des matières
  • MARQUE LIVRES
  • Noté. / 5. Basé sur avis des utilisateurs

Résumé du contenu

Page 1 - External Interfaces

ComputationVisualizationProgrammingExternal Interfaces Version 6

Page 2 - How to Contact The MathWorks:

viii Contents8Serial Port I/OIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2What Is MATLAB’s Ser

Page 3

2 Creating C Language MEX-Files2-40Hybrid ArraysFunctions such as mxSetPr, mxSetData, and mxSetCell allow the direct placement of memory pieces into a

Page 4

Advanced Topics2-41This section explains how to write and build MEX-files that call LAPACK and BLAS functions. It provides information on:•Specifying

Page 5 - Creating Fortran MEX-Files

2 Creating C Language MEX-Files2-42 B = mxGetPr(prhs[1]); m = mxGetM(prhs[0]); p = mxGetN(prhs[0]); n = mxGetN(prhs[1]); if(p != mxGetM( prhs[1])

Page 6 - Calling Java from MATLAB

Advanced Topics2-43format, which takes twice the space. See the allocation of zout in the example that follows.2 Once the variable is returned to MATL

Page 7

2 Creating C Language MEX-Files2-44Preserving Input Values from ModificationMany LAPACK and BLAS functions modify the values of arguments passed in to

Page 8

Advanced Topics2-45mex myCmexFile.c <matlab>/extern/lib/win32/microsoft/msvc60/libmwlapack.libFor IBM_RS, use the following syntax.mex myCmexFil

Page 9

2 Creating C Language MEX-Files2-46mex myCmexFile.c <matlab>/extern/examples/refbook/fort.c -I<matlab>/extern/examples/refbook Example – S

Page 10 - Serial Port I/O

Debugging C Language MEX-Files2-47Debugging C Language MEX-FilesOn most platforms, it is now possible to debug MEX-files while they are running within

Page 11

2 Creating C Language MEX-Files2-48Note The tick marks used are back ticks (‘), not single quotes (').You may need to tell the debugger where th

Page 12 - Contents

Debugging C Language MEX-Files2-49edit boxes. In the edit box labeled Executable for debug session, enter the full path to where MATLAB resides. All o

Page 13 - Programs from MATLAB

ixEvents and Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-48Example: Introduction to Events and Callbacks . . . . .

Page 14

2 Creating C Language MEX-Files2-505 When MATLAB starts, in the command window change directories to where your MEX-file resides and run your MEX-file

Page 15 - Introducing MEX-Files

3Creating Fortran MEX-FilesFortran MEX-Files . . . . . . . . . . . . . . . . . 3-3The Components of a Fortran MEX

Page 16

3 Creating Fortran MEX-Files3-2This chapter describes how to write MEX-files in the Fortran programming language. It discusses the MEX-file itself, ho

Page 17

Fortran MEX-Files3-3Fortran MEX-FilesFortran MEX-files are built by using the mex script to compile your Fortran source code with additional calls to

Page 18 - MATLAB Data

3 Creating Fortran MEX-Files3-4Figure 3-1: Fortran MEX Cycleinteger AA = prhs(1)MATLAB A call to MEX-file func:[C,D]=func(A,B)tells MATLAB to pass va

Page 19 - Sparse Matrices

Fortran MEX-Files3-5The Pointer ConceptThe MATLAB API works with a unique data type, the mxArray. Because there is no way to create a new data type in

Page 20 - Multidimensional Arrays

3 Creating Fortran MEX-Files3-6The Gateway RoutineThe entry point to the gateway subroutine must be named mexFunction and must contain these parameter

Page 21 - The explore Example

Fortran MEX-Files3-7plhs is a 1-element C array where the single element is a null pointer. prhs is a 2-element C array where the first element is a p

Page 22

3 Creating Fortran MEX-Files3-8When a MEX-file completes its task, it returns control to MATLAB. Any MATLAB arrays that are created by the MEX-file th

Page 23 - Building MEX-Files

Examples of Fortran MEX-Files3-9Examples of Fortran MEX-FilesThe following sections include information and examples describing how to pass and manipu

Page 25

3 Creating Fortran MEX-Files3-10A First Example — Passing a ScalarLet’s look at a simple example of Fortran code and its MEX-file equivalent. Here is

Page 26

Examples of Fortran MEX-Files3-11C Check for proper number of arguments. if(nrhs .ne. 1) then call mexErrMsgTxt('One input requ

Page 27

3 Creating Fortran MEX-Files3-12To compile and link this example source file, at the MATLAB prompt typemex timestwo.fThis carries out the necessary st

Page 28

Examples of Fortran MEX-Files3-13Below is the gateway routine that calls the computational routine.C The gateway routine subroutine mexFuncti

Page 29 - Preconfigured Options Files

3 Creating Fortran MEX-Files3-14C Initialize outbuf_buf to blanks. This is necessary on some C compilers. output_buf = ' 'C

Page 30

Examples of Fortran MEX-Files3-15MEX-file. Consequently, when returning to MATLAB, the output matrix must be transposed.This example places a string a

Page 31

3 Creating Fortran MEX-Files3-16 character*15 string(5)C Create the string to passed into MATLAB. string(1) = 'MATLAB &apos

Page 32 - Custom Building MEX-Files

Examples of Fortran MEX-Files3-17Passing MatricesIn MATLAB, you can pass matrices into and out of MEX-files written in Fortran. You can manipulate the

Page 33

3 Creating Fortran MEX-Files3-18 integer x_pr, y_prC--------------------------------------------------------------C integer nlhs, nrhs

Page 34 - Default Options File on UNIX

Examples of Fortran MEX-Files3-19C Load the data into y_pr, which is the output to MATLAB. call mxCopyReal8ToPtr(y, y_pr, size) ret

Page 35 - The User Profile Directory

1Calling C and Fortran Programs from MATLABIntroducing MEX-Files . . . . . . . . . . . . . . . 1-3Using MEX-Files .

Page 36 - Link Stage

3 Creating Fortran MEX-Files3-20 do 20 i=1,m do 10 j=1,n z(i,j)=x*y(i,j) 10 continue 20 continue return endBe

Page 37 - Build Options

Examples of Fortran MEX-Files3-21 endifC Check to see both inputs are numeric. if (mxIsNumeric(prhs(1)) .ne. 1) then call mexErr

Page 38

3 Creating Fortran MEX-Files3-22As this example shows, creating MEX-file gateways that handle multiple inputs and outputs is straightforward. All you

Page 39 - Prelink Stage

Examples of Fortran MEX-Files3-23C==============================================================CC Computational subroutine subroutine convec

Page 40 - Versioning MEX-Files

3 Creating Fortran MEX-Files3-24 endifC Check that inputs are both row vectors. mx = mxGetM(prhs(1)) nx = mxGetN(prhs(1)) my =

Page 41

Examples of Fortran MEX-Files3-25Entering these numbers at the MATLAB promptx = [3 - 1i, 4 + 2i, 7 - 3i]x = 3.0000 - 1.0000i 4.0000 + 2.0000i 7.

Page 42

3 Creating Fortran MEX-Files3-26C $Revision: 1.12 $C===============================================================C C dblmat.fC Examp

Page 43 - •See the

Examples of Fortran MEX-Files3-27 m_in = mxGetM(prhs(1)) n_in = mxGetN(prhs(1)) size = m_in * n_in pr_in = mxGetPr(prhs(1))C m

Page 44 - DLLs Not on Path on Windows

3 Creating Fortran MEX-Files3-28For an input 2-by-3 matrixx = [1 2 3; 4 5 6];typingy = dblmat(x)yieldsy = 2 4 6 8 10 12Note The

Page 45 - General Configuration Problem

Examples of Fortran MEX-Files3-29CC NOTE: The subroutine loadsparse() is in the file called C loadsparse.f. C This is a MEX-file for MATLA

Page 46 - MEX-files only

1 Calling C and Fortran Programs from MATLAB1-2Although MATLAB® is a complete, self-contained environment for programming and manipulating data, it is

Page 47

3 Creating Fortran MEX-Files3-30C Get the size and pointers to input data. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) pr = mxGetPr(prh

Page 48

Examples of Fortran MEX-Files3-31CC This is a MEX-file for MATLAB.C Copyright (c) 1984-2000 The MathWorks, Inc. C C=======================

Page 49

3 Creating Fortran MEX-Files3-32At the MATLAB prompt, enteringfull = eye(5)full = 1 0 0 0 0 0 1 0 0 0 0

Page 50

Examples of Fortran MEX-Files3-33CC NOTE: The subfunction fill() is in the file called fill.f.CC This is a MEX-file for MATLAB.C Copyright

Page 51

3 Creating Fortran MEX-Files3-34 call mxFreeMatrix(lhs(1)) return end C $Revision: 1.3 $C ========================================

Page 52 - Potential Memory Leaks

Examples of Fortran MEX-Files3-35Running this examplesincalldisplays the resultsNote It is possible to generate an object of type mxUNKNOWN_CLASS usi

Page 53

3 Creating Fortran MEX-Files3-36Advanced TopicsThese sections cover advanced features of MEX-files that you can use when your applications require sop

Page 54 - Additional Information

Advanced Topics3-37Memory ManagementAs of Version 5.2, MATLAB now implicitly destroys (by calling mxDestroyArray) any arrays created by a MEX-file tha

Page 55 - <matlab>/bin

3 Creating Fortran MEX-Files3-38Debugging Fortran Language MEX-FilesOn most platforms, it is now possible to debug MEX-files while they are running wi

Page 56 - <matlab>/extern/src

Debugging Fortran Language MEX-Files3-39Note The name mexFunction may be slightly altered by the compiler (i.e., it may have an underscore appended).

Page 57 - <matlab>\bin\win32

Introducing MEX-Files1-3Introducing MEX-FilesYou can call your own C or Fortran subroutines from MATLAB as if they were built-in functions. MATLAB cal

Page 58 - Examples From the Text

3 Creating Fortran MEX-Files3-404 From the Build menu, select Debug, and click Go.5 You will now be able to run your MEX-file in MATLAB and use the Mi

Page 59 - Engine and MAT Examples

4Calling MATLAB from C and Fortran ProgramsUsing the MATLAB Engine . . . . . . . . . . . . . 4-3The Engine Library . .

Page 60 - Technical Support

4 Calling MATLAB from C and Fortran Programs4-2The MATLAB engine library is a set of routines that allows you to call MATLAB from your own programs, t

Page 61 - Creating C Language

Using the MATLAB Engine4-3Using the MATLAB EngineSome of the things you can do with the MATLAB engine are:•Call a math routine, for example, to invert

Page 62

4 Calling MATLAB from C and Fortran Programs4-4The MATLAB engine also uses the mx prefixed API routines discussed in Chapter 2, “Creating C Language M

Page 63 - C MEX-Files

Using the MATLAB Engine4-5GUI-Intensive ApplicationsIf you have graphical user interface (GUI) intensive applications that execute a lot of callbacks

Page 64

4 Calling MATLAB from C and Fortran Programs4-6Examples of Calling Engine FunctionsThis section contains examples that illustrate how to call engine f

Page 65

Examples of Calling Engine Functions4-7int main(){ Engine *ep; mxArray *T = NULL, *result = NULL; char buffer[BUFSIZE]; double time[10] = { 0.0, 1

Page 66

4 Calling MATLAB from C and Fortran Programs4-8 /* * Evaluate a function of time, distance = (1/2)g.*t.^2 * (g is the acceleration due to gravity

Page 67 - Examples of C MEX-Files

Examples of Calling Engine Functions4-9 */ engOutputBuffer(ep, buffer, BUFSIZE); while (result == NULL) { char str[BUFSIZE]; /* * Get a

Page 68

1 Calling C and Fortran Programs from MATLAB1-4You can call MEX-files exactly as you would call any M-function. For example, a MEX-file called conv2.m

Page 69

4 Calling MATLAB from C and Fortran Programs4-10 /* * We're done! Free memory, close MATLAB engine and exit. */ printf("Done!\n")

Page 70 - that returns the values of

Examples of Calling Engine Functions4-11Entering X = 17.5 continues the program execution.X = 17.5 X = 17.5000 Retrieving X...X is class doubleDon

Page 71 - Passing Strings

4 Calling MATLAB from C and Fortran Programs4-12C Other variable declarations here double precision time(10), dist(10) integer engPutMat

Page 72

Examples of Calling Engine Functions4-13CC Plot the result.C if (engEvalString(ep, 'plot(T,D);') .ne. 0) then write(6,*) &ap

Page 73

4 Calling MATLAB from C and Fortran Programs4-14C D = engGetMatrix(ep, 'D') call mxCopyPtrToReal8(mxGetPr(D), dist, 10)

Page 74

Examples of Calling Engine Functions4-15The program continues withType 0 <return> to ExitType 1 <return> to continueEntering 1 at the prom

Page 75

4 Calling MATLAB from C and Fortran Programs4-16For example:1 Shut down any MATLAB sessions.2 From the Start button on the Windows menu bar, click Run

Page 76

Compiling and Linking Engine Programs4-17Compiling and Linking Engine ProgramsTo produce an executable version of an engine program, you must compile

Page 77

4 Calling MATLAB from C and Fortran Programs4-18#include <float.h>..._control87(MCW_EM,MCW_EM);...Compiling and Linking on UNIXUnder UNIX at run

Page 78

Compiling and Linking Engine Programs4-19Compiling and LinkingMATLAB provides an options file, engopts.sh, that lets you use the mex script to easily

Page 79

Introducing MEX-Files1-5Note mex routines are only available in MEX-functions.

Page 80 - The results of this input are

4 Calling MATLAB from C and Fortran Programs4-20

Page 81 - Handling Complex Data

5Calling Java from MATLABUsing Java from MATLAB: An Overview . . . . . . . 5-3Bringing Java Classes into MATLAB . . . . .

Page 82

5 Calling Java from MATLAB5-2This chapter describes how to use the MATLAB interface to Java classes and objects. This MATLAB capability enables you to

Page 83

Using Java from MATLAB: An Overview5-3Using Java from MATLAB: An OverviewJava Interface Is Integral to MATLABEvery installation of MATLAB includes a J

Page 84

5 Calling Java from MATLAB5-4•Java in a Nutshell (Second Edition), by David Flanagan•Teach Yourself Java in 21 Days, by Lemay and PerkinsAnother place

Page 85

Bringing Java Classes into MATLAB5-5Bringing Java Classes into MATLABYou can draw from an extensive collection of existing Java classes or create your

Page 86

5 Calling Java from MATLAB5-61.1.8 Java Virtual Machine from the web site at Sun Microsystems, (http://www.java.sun.com/jdk/). The Sun site also provi

Page 87

Bringing Java Classes into MATLAB5-7and JAR files, consult your Java development documentation or the JavaSoft web site. See also “To Learn More About

Page 88

5 Calling Java from MATLAB5-8When you use the which function on methods defined by Java classes, the function only acts on the classes currently loade

Page 89 - Handling Sparse Arrays

Bringing Java Classes into MATLAB5-9•java.lang.String•java.util.EnumerationA fully qualified name can be rather long, making commands and functions, s

Page 90

1 Calling C and Fortran Programs from MATLAB1-6MATLAB DataBefore you can program MEX-files, you must understand how MATLAB represents the many data ty

Page 91

5 Calling Java from MATLAB5-10Creating and Using Java ObjectsIn MATLAB, you create a Java object by calling one of the constructors of that class. You

Page 92

Creating and Using Java Objects5-11class, class_name, with the argument list that matches x1,...,xn, and returns a new object, J.J = javaObject('

Page 93

5 Calling Java from MATLAB5-12Note Typically, you will not need to use javaObject. The default MATLAB syntax for instantiating a Java class is somewh

Page 94

Creating and Using Java Objects5-13Concatenating Objects of the Same ClassIf all of the objects being operated on are of the same Java class, then the

Page 95

5 Calling Java from MATLAB5-14If there is no common, lower level parent, then the resultant class is java.lang.Object, which is the root of the entire

Page 96

Creating and Using Java Objects5-15Finding the Public Data Fields of an ObjectTo list the public fields that belong to a Java object, use the fieldnam

Page 97

5 Calling Java from MATLAB5-16'static final float BOTTOM_ALIGNMENT % Inherited from java.awt.Component''static final float LEFT_ALIG

Page 98 - Persistent Arrays

Creating and Using Java Objects5-17Accessing Data from a Static FieldIn Java, a static data field is a field that applies to an entire class of object

Page 99

5 Calling Java from MATLAB5-18frameClass = class(frame)frameClass = java.awt.FrameBecause this form of class also works on MATLAB objects, it does not

Page 100 - Hybrid Arrays

Invoking Methods on Java Objects5-19Invoking Methods on Java ObjectsThis section explains how to invoke an object’s methods in MATLAB. It also covers

Page 101 - Specifying the Function Name

MATLAB Data1-7its dimensions aresize(a)ans =3 5and its data is stored asData Types in MATLABComplex Double-Precision MatricesThe most common data

Page 102 - Handling Complex Numbers

5 Calling Java from MATLAB5-20title = getTitle(frame)title = Sample FrameAll of the programming examples in this chapter contain invocations of Java o

Page 103 - Advanced Topics

Invoking Methods on Java Objects5-21With javaMethod, you can also specify the method to be invoked at run-time. In this situation, your code calls jav

Page 104 - Building the MEX-File

5 Calling Java from MATLAB5-22Using the javaMethod Function on Static MethodsThe javaMethod function was introduced in section “Using the javaMethod F

Page 105

Invoking Methods on Java Objects5-23The following command lists information on all methods in the java.awt.MenuItem class.methodsview java.awt.MenuIte

Page 106 - Creating C Language MEX-Files

5 Calling Java from MATLAB5-24Each row in the window displays up to six fields of information describing the method. The table below lists the fields

Page 107 - Debugging on UNIX

Invoking Methods on Java Objects5-25For example, display a full description of all methods of the java.awt.Dimension object.methods java.awt.Dimension

Page 108 - Microsoft Compiler

5 Calling Java from MATLAB5-26If you use which -all for the method equals, with the String and java.awt.Frame classes loaded, you see the following di

Page 109 - Watcom Compiler

Invoking Methods on Java Objects5-27Changing the Effect of isequalThe MATLAB isequal function compares two or more arrays for equality in type, size,

Page 110

5 Calling Java from MATLAB5-28Note When you define a Java class for use in MATLAB, avoid giving any of its methods the same name as a MATLAB built-in

Page 111 - MEX-Files

Working with Java Arrays5-29Working with Java ArraysYou can pass singular Java objects to and from methods or you may pass them in an array, providing

Page 112 - 3 Creating Fortran MEX-Files

How to Contact The MathWorks:www.mathworks.com Webcomp.soft-sys.matlab [email protected] Technical [email protected] Product

Page 113 - Fortran MEX-Files

1 Calling C and Fortran Programs from MATLAB1-8•nzmax is an integer that contains the length of ir, pr, and, if it exists, pi. It is the maximum possi

Page 114

5 Calling Java from MATLAB5-30How MATLAB Represents the Java ArrayThe term java array refers to any array of Java objects returned from a call to a Ja

Page 115 - The Pointer Concept

Working with Java Arrays5-31Array Access from JavaArray Access from MATLABjArray[0][4][2]jArray(1,5,3)jArray[0][3]jArray(1,4)jArray[0]jArray[1]jArray[

Page 116 - The Gateway Routine

5 Calling Java from MATLAB5-32Array IndexingJava array indexing is different than MATLAB array indexing. Java array indices are zero-based, MATLAB arr

Page 117

Working with Java Arrays5-33When the size function is applied to a Java array of arrays, the resulting value describes the top level of the specified

Page 118

5 Calling Java from MATLAB5-34Creating an Array of Objects Within MATLABTo call a Java method that has one or more arguments defined as an array of Ja

Page 119 - Examples of Fortran MEX-Files

Working with Java Arrays5-35for m = 1:4 for n = 1:5 dblArray(m,n) = java.lang.Double((m*10) + n); endenddblArraydblArray =java.lang.Double[][

Page 120

5 Calling Java from MATLAB5-36This example first creates a scalar MATLAB array, and then successfully modifies it to be two-dimensional.matlabArray =

Page 121

Working with Java Arrays5-37element at the intersection of row 3 and column 4. Sometimes it is more advantageous to use just a single subscript. MATLA

Page 122

5 Calling Java from MATLAB5-38here, the statement dblArray(2,2:4) refers to a portion of the lower level array, dblArray(2). A new array, row2Array, i

Page 123

Working with Java Arrays5-39This works the same way on an N-dimensional Java array structure. Using the colon operator as a single subscripted index i

Page 124

MATLAB Data1-9Logical ArraysAny noncomplex numeric or sparse array can be flagged as logical. The storage for a logical array is the same as the stora

Page 125

5 Calling Java from MATLAB5-40The following example deposits the value 300 in the dblArray element at row 3, column 2. In Java, this would be dblArray

Page 126

Working with Java Arrays5-41 [ 21] [ 22] [ 23] [ 24] [ 25] [100] [200] [300] [400] [500] [ 41] [ 42] [ 43] [

Page 127 - Passing Matrices

5 Calling Java from MATLAB5-42can also assign [] to array elements. This stores the NULL value, rather than a 0-by-0 array, in the Java array element.

Page 128

Working with Java Arrays5-43The dblArray data structure s actually an array of five-element arrays of java.lang.Double objects. The empty array assign

Page 129

5 Calling Java from MATLAB5-44% Concatenate the two along the second dimension.d3 = cat(2,d1,d2)d3 =java.lang.Double[][]: [2] [4] [6] [ 8]

Page 130

Working with Java Arrays5-45java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [ 0] [ 0] [ 0] [ 0]Creat

Page 131

5 Calling Java from MATLAB5-46Passing Data to a Java MethodWhen you make a call from MATLAB to Java code, any MATLAB data types you pass in the call a

Page 132

Passing Data to a Java Method5-47scalar (1-by-1) arrays or matrices. All of the Java types can be scalar values or arrays. Data type conversion of arg

Page 133

5 Calling Java from MATLAB5-48Passing Built-In Data TypesJava has eight data types that are intrinsic to the language and are not represented as Java

Page 134

Passing Data to a Java Method5-49[poly.xpoints poly.ypoints] % Verify the coordinatesans =14 5542 1298 -2124 62MATLAB Arrays Are P

Page 135 - Dynamically Allocating Memory

1 Calling C and Fortran Programs from MATLAB1-10explore accepts any data type. Try using explore with these examples.explore([1 2 3 4 5])explore 1 2 3

Page 136

5 Calling Java from MATLAB5-50In the MATLAB call to this constructor, a character array specifying the URL is passed. MATLAB converts this array to a

Page 137

Passing Data to a Java Method5-51In each of these calls to menu1.add, an object that is an instance of the java.awt.MenuItem Java class is passed.menu

Page 138

5 Calling Java from MATLAB5-52The three calls to put from the preceding example can be rewritten ashTable.put(0, 1);hTable.put(1, 41.287);hTable.put(2

Page 139

Passing Data to a Java Method5-53Handling a Cell Array of Java ObjectsYou create a cell array of Java objects by using the MATLAB syntax {a1,a2,...}.

Page 140

5 Calling Java from MATLAB5-54determined solely by the number of nested arrays. For example, double[][] has dimension 2, and double has dimension 0.If

Page 141

Passing Data to a Java Method5-55First, MATLAB rejects all methods that have any argument types that are incompatible with the passed arguments (for e

Page 142

5 Calling Java from MATLAB5-56Handling Data Returned from a Java MethodIn many cases, data returned from Java is incompatible with the data types oper

Page 143

Handling Data Returned from a Java Method5-57Built-In Data TypesJava built-in data types are described in “Passing Built-In Data Types” on page 5-48.

Page 144

5 Calling Java from MATLAB5-58Converting to the MATLAB double Data TypeUsing the double function in MATLAB, you can convert any Java object or array o

Page 145

Handling Data Returned from a Java Method5-59method of the class to perform the conversion. If you write your own class definitions, then you can make

Page 146

Building MEX-Files1-11Building MEX-FilesThis section covers the following topics:•“Compiler Requirements”•“Testing Your Configuration on UNIX”•“Testin

Page 147 - Memory Management

5 Calling Java from MATLAB5-60pstruct.xpointsans = 14 42 98 124pstruct.xpoints(3) = 101;Converting to a MATLAB Cell ArrayUse the cell funct

Page 148

Handling Data Returned from a Java Method5-61% Convert each to cell arrayscellArray = {cell(dblArray), cell(ptArray), cell(strArray)}cellArray = {

Page 149 - Compaq Visual Fortran

5 Calling Java from MATLAB5-62Introduction to Programming ExamplesThe following programming examples demonstrate the MATLAB interface to Java classes

Page 150

Example – Reading a URL5-63Example – Reading a URLThis program, URLdemo, opens a connection to a web site specified by a URL (Uniform Resource Locator

Page 151 - Calling MATLAB from C

5 Calling Java from MATLAB5-64BufferedReader object to variable br. A buffered reader provides for efficient reading of characters, arrays, and lines.

Page 152

Example – Reading a URL5-65s =concept: not only can you point to a file in a directory, but that s =file and that directory can exist on any machine o

Page 153 - Using the MATLAB Engine

5 Calling Java from MATLAB5-66Example – Finding an Internet Protocol AddressThe resolveip function returns either the name or address of an IP (intern

Page 154 - Communicating with MATLAB

Example – Finding an Internet Protocol Address5-673. Display the Hostname or IP AddressThe example uses the MATLAB strcmp function to compare the inpu

Page 155 - GUI-Intensive Applications

5 Calling Java from MATLAB5-68Example – Communicating Through a Serial PortThe serialexample program uses classes of the Java API javax.comm package,

Page 156

Example – Communicating Through a Serial Port5-69Description of Serial ExampleThe major tasks performed by serialexample are:1. Define Variables for S

Page 157

1 Calling C and Fortran Programs from MATLAB1-12Testing Your Configuration on UNIXThe quickest way to check if your system is set up properly to creat

Page 158

5 Calling Java from MATLAB5-704. Configure the Serial PortThe next three statements call configuration methods on the SerialPort object serialPort. Th

Page 159

Example – Communicating Through a Serial Port5-717. Open an Input Stream and Determine Number of Bytes to ReadTo read the data expected from the oscil

Page 160 - Return continues the program

5 Calling Java from MATLAB5-72Running the serialexample ProgramThe value of result depends upon whether your system’s COM1 port is cabled to an oscill

Page 161

Example – Creating and Using a Phone Book5-73Example – Creating and Using a Phone BookThe example’s main function, phonebook, can be called either wit

Page 162

5 Calling Java from MATLAB5-74Description of Function phonebookThe major tasks performed by phonebook are:1. Determine the Data Directory and Full Fil

Page 163

Example – Creating and Using a Phone Book5-75 if r == 'y', try FOS = java.io.FileOutputStream(pbname); FOS.close

Page 164

5 Calling Java from MATLAB5-766. Display the Action Menu and Get the User’s SelectionWithin a while loop, several disp statements display a menu of ac

Page 165

Example – Creating and Using a Phone Book5-77Case 2 calls pb_add, which prompts the user for a new entry and then adds it to the phone book. case &a

Page 166 - OK. This starts MATLAB

5 Calling Java from MATLAB5-78object FOS and a descriptive header string. It then calls close on the FileOutputStream object, and returns. case &apo

Page 167

Example – Creating and Using a Phone Book5-79Description of Function pb_add1. Input the Entry to AddThe pb_add function takes one argument, the Proper

Page 168 - Setting Runtime Library Path

Building MEX-Files1-13 Options files control which compiler to use, the compiler and link command options, and the runtime libraries to link

Page 169 - Compiling and Linking

5 Calling Java from MATLAB5-80Description of Function pb_remove1. Look For the Key in the Phone BookArguments passed to pb_remove are the Properties o

Page 170

Example – Creating and Using a Phone Book5-81the name will be added to the phone book, and allows the user to enter the phone number(s) for the entry.

Page 171 - Calling Java from

5 Calling Java from MATLAB5-82pb_htable.put(pb_keyfilter(name),entry);disp ' 'disp(sprintf('The entry for %s has been changed', na

Page 172 - 5 Calling Java from MATLAB

Example – Creating and Using a Phone Book5-83Description of Function pb_keyfilterThe pb_keyfilter function takes an argument key, which is a name used

Page 173

5 Calling Java from MATLAB5-84 Phonebook Menu: 1. Look up a phone number 2. Add an entry to the phone book 3. Remove an entry from the ph

Page 174

Example – Creating and Using a Phone Book5-85 (508) 111-3456------------------------- ------------------------- Russell Reddy (617) 999-8765----------

Page 175 - Defining New Java Classes

5 Calling Java from MATLAB5-86

Page 176

6Importing and Exporting DataUsing MAT-Files . . . . . . . . . . . . . . . . . . 6-3Importing Data to MATLAB .

Page 177

6 Importing and Exporting Data6-2You can use MAT-files, the data file format MATLAB uses for saving data to disk, to import data to and export data fr

Page 178

Using MAT-Files6-3Using MAT-FilesThis section describes the various techniques for importing data to and exporting data from the MATLAB environment. T

Page 179

1 Calling C and Fortran Programs from MATLAB1-14Testing Your Configuration on WindowsBefore you can create MEX-files on the Windows platform, you must

Page 180 - Using the javaObject Function

6 Importing and Exporting Data6-4computer-readable form and you have to type it in. Essentially the same as the first method, this method has the adva

Page 181

Using MAT-Files6-5•Use the Save command.Save the data in ASCII form using the save command with the -ascii option. For example,A = rand(4,3);save temp

Page 182

6 Importing and Exporting Data6-6Both types of files can be transported directly between machines: M-files because they are platform independent and M

Page 183

Using MAT-Files6-7The MAT-file library contains routines for reading and writing MAT-files. They all begin with the three-letter prefix mat. These tab

Page 184

6 Importing and Exporting Data6-8Finding Associated FilesA collection of files associated with reading and writing MAT-files is located on your disk.

Page 185

Using MAT-Files6-9Include FilesThe include directory holds header files containing function declarations with prototypes for the routines that you can

Page 186 - Examples

6 Importing and Exporting Data6-10For additional information about the MATLAB API files and directories, see “Additional Information” on page 1-42.Tab

Page 187 - Assigning to a Static Field

Examples of MAT-Files6-11Examples of MAT-FilesThis section includes C and Fortran examples of writing, reading, and diagnosing MAT-files. The examples

Page 188

6 Importing and Exporting Data6-12#include <stdlib.h> /* For EXIT_FAILURE, EXIT_SUCCESS */#include "mat.h"#define BUFSIZE 256int main(

Page 189

Examples of MAT-Files6-13 pa3 = mxCreateString("MATLAB: the language of technical computing"); if (pa3 == NULL) {

Page 190

Building MEX-Files1-15to select one when you compile MEX-files. To select a compiler or change to existing default compiler, use mex –setup.This examp

Page 191

6 Importing and Exporting Data6-14 if (status != 0) { printf("%s : Error using matPutArray on line %d\n", __FILE__, __LINE__

Page 192

Examples of MAT-Files6-15 pa2 = matGetArray(pmat, "GlobalDouble"); if (pa2 == NULL) { printf("Error reading existing matrix Global

Page 193

6 Importing and Exporting Data6-16To produce an executable version of this example program, compile the file and link it with the appropriate library.

Page 194

Examples of MAT-Files6-17 * matClose * matGetDir * matGetNextArray * matGetNextArrayHeader * matOpen * * Copyright (c) 1984-1998 The MathWorks

Page 195

6 Importing and Exporting Data6-18 mxFree(dir); /* In order to use matGetNextXXX correctly, reopen file to read in headers. */ if (matClose(pm

Page 196

Examples of MAT-Files6-19 if (pmat == NULL) { printf("Error reopening file %s\n", file); return(1); } /* Read in each array. */ pr

Page 197

6 Importing and Exporting Data6-20 else { result = 0; printf("Usage: matdgns <matfile>"); printf("where <matfile>

Page 198

Examples of MAT-Files6-21Creating a MAT-File in FortranThis example creates a MAT-file, matdemo.mat.C $Revision: 1.6 $CC matdemo1.fCC This is

Page 199 - Working with Java Arrays

6 Importing and Exporting Data6-22 if (mp .eq. 0) then write(6,*) 'Can''t open ''matdemo.mat'' for writing.&a

Page 200

Examples of MAT-Files6-23 if (status .ne. 0) then write(6,*) 'Error closing MAT-file' stop end ifC mp = matOp

Page 201 - Array One-dimensional Array

1 Calling C and Fortran Programs from MATLAB1-16The default options file:"C:\WINNT\Profiles\username\ApplicationData\MathWorks\MATLAB\R12\mexopts

Page 202 - The Shape of the Java Array

6 Importing and Exporting Data6-24Once you have compiled and linked your MAT-file program, you can run the stand-alone application you have just produ

Page 203

Examples of MAT-Files6-25C--------------------------------------------------------------C $Revision: 1.7 $C program matdemo2C----------------

Page 204 - Using the javaArray Function

6 Importing and Exporting Data6-26CC Copy integer to character stringC do 20 i=1,ndir call mxCopyPtrToCharacter(adir(i), names(i), 32

Page 205

Examples of MAT-Files6-27 end doC stat = matClose(mp) if (stat .ne. 0) then write(6,*) 'Error closing ''matdemo.

Page 206

6 Importing and Exporting Data6-28Compiling and Linking MAT-File ProgramsThis section describes the steps required to compile and link MAT-file progra

Page 207 - Using the Colon Operator

Compiling and Linking MAT-File Programs6-29#include <float.h> . . ._control87(MCW_EM,MCW_EM); . . .Compiling and Linking on UNIXUnde

Page 208

6 Importing and Exporting Data6-30Using the Options FileMATLAB provides an options file, matopts.sh, that lets you use the mex script to easily compil

Page 209 - Using END in a Subscript

7ActiveX and DDE SupportIntroducing MATLAB ActiveX Integration . . . . . . 7-3ActiveX Concepts and Terminology . . . . . .

Page 210

7 ActiveX and DDE Support7-2ActiveX is a set of object-oriented technologies and tools that allow software developers to integrate application-specifi

Page 211 - Assigning the Empty Matrix

Introducing MATLAB ActiveX Integration7-3Introducing MATLAB ActiveX Integration ActiveX is a Microsoft Windows protocol for component integration. Usi

Page 212 - Subscripted Deletion

Building MEX-Files1-17In addition to running the mex script from the MATLAB prompt, you can also run the script from the system prompt.Specifying an O

Page 213 - Concatenating Java Arrays

7 ActiveX and DDE Support7-4•PropertiesRadius (integer) - sets the radius of the circle drawn by the controlLabel (string) - text to be drawn in the c

Page 214

Introducing MATLAB ActiveX Integration7-5In general, servers that are not controls will not be physically or visually embedded in the client applicati

Page 215

7 ActiveX and DDE Support7-6MATLAB ActiveX Client SupportIn order to use an ActiveX component with MATLAB or with any ActiveX client, you first need t

Page 216 - Passing Data to a Java Method

MATLAB ActiveX Client Support7-7The creation commands, actxcontrol and actxserver, both return a MATLAB activex object, which represents the default i

Page 217

7 ActiveX and DDE Support7-8Writing Event HandlersActiveX events are invoked when a control wants to notify its container that something of interest h

Page 218

Writing Event Handlers7-9function myclick(varargin)disp('Single click function')function my2click(varargin)disp('Double click function&

Page 219 - Passing String Arguments

7 ActiveX and DDE Support7-10Additional ActiveX Client InformationReleasing InterfacesEach ActiveX object can support one or more interfaces. In MATLA

Page 220 - Passing Strings in an Array

Additional ActiveX Client Information7-11activex object called hPlot.) In particular, this example iterates through a collection of Plot interfaces, i

Page 221

7 ActiveX and DDE Support7-12Using MATLAB As a DCOM Server ClientDistributed Component Object Model (DCOM) is an object distribution mechanism that al

Page 222 - Passing Objects in an Array

Additional ActiveX Client Information7-13MATLAB has been tested as a DCOM server with Windows NT 4.0 only. Additionally, MATLAB can be used as a DCOM

Page 223 - Other Data Conversion Topics

iContents1Calling C and Fortran Programs from MATLABIntroducing MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Using M

Page 224 - Empty Matrices and Nulls

1 Calling C and Fortran Programs from MATLAB1-18Microsoft C/C++, Version 5.0msvc50opts.batMicrosoft C/C++, Version 6.0msvc60opts.batWatcom C/C++, Vers

Page 225

7 ActiveX and DDE Support7-14% MATLAB ActiveX automation client example %% Open Excel, add workbook, change active worksheet, % get/put array, save.%

Page 226

Additional ActiveX Client Information7-15% Workbook.Saved = 1;% invoke(Workbook, 'Close');% Quit Excel.invoke(Excel, 'Quit');

Page 227 - Java Objects

7 ActiveX and DDE Support7-16MATLAB ActiveX Automation Server SupportMATLAB on Microsoft Windows supports ActiveX Automation server capabilities. Auto

Page 228

MATLAB ActiveX Automation Server Support7-17Note The first statement above should be declared in the general declarations section in order to keep th

Page 229

7 ActiveX and DDE Support7-18This method retrieves a full, one- or two-dimensional real or imaginary mxArray from the named workspace. The real and (o

Page 230

MATLAB ActiveX Automation Server Support7-19void PutFullMatrix([in] BSTR Name, [in] BSTR Workspace, [in] SAFEARRAY(double) pr, [in] SAFEARRAY(double)

Page 231

7 ActiveX and DDE Support7-20Note The first statement above should be declared in the general declarations section in order to keep the scope through

Page 232

Additional ActiveX Server Information7-21Additional ActiveX Server InformationLaunching the MATLAB ActiveX ServerFor MATLAB to act as an automation se

Page 233 - 1. Construct a URL Object

7 ActiveX and DDE Support7-22of a dedicated server running simultaneously, since the dedicated server is not shared by multiple clients.Using MATLAB A

Page 234

Dynamic Data Exchange (DDE)7-23Dynamic Data Exchange (DDE)MATLAB provides functions that enable MATLAB to access other Windows applications and for ot

Page 235

Building MEX-Files1-19An up-to-date list of options files is available from our FTP server, ftp://ftp.mathworks.com/pub/tech-support/docexamples/apigu

Page 236

7 ActiveX and DDE Support7-24The Service NameEvery application that can be a DDE server has a unique service name. The service name is usually the app

Page 237 - Running the Example

Dynamic Data Exchange (DDE)7-25•Metafilepict – Metafilepict format is a description of graphical data containing the drawing commands for graphics. As

Page 238

7 ActiveX and DDE Support7-26The DDE Name HierarchyWhen you access MATLAB as a server, you must specify its service name, topic, and item. The figure

Page 239 - 3. Open the Serial Port

Dynamic Data Exchange (DDE)7-27•FormatProvides a tab-delimited list of string names of all the formats supported by the server. MATLAB supports Text,

Page 240 - 4. Configure the Serial Port

7 ActiveX and DDE Support7-28require only the command. Where an item name is required, use EngEvalString. In both forms, the format of the command mus

Page 241 - 10. Close the Serial Port

Dynamic Data Exchange (DDE)7-29The table summarizes the DDE request parameters. Sending Data to MATLABClients send data to MATLAB using the DDE poke o

Page 242

7 ActiveX and DDE Support7-30Sub TextInput_KeyPress(KeyAscii As Integer)rem If the user presses the return keyrem in the TextInput control.If KeyAscii

Page 243

Dynamic Data Exchange (DDE)7-31Using MATLAB As a ClientFor MATLAB to act as a client application, you can use the MATLAB DDE client functions to estab

Page 244

7 ActiveX and DDE Support7-32.XLC and includes the full path if necessary. A Microsoft Excel item is a cell reference, which can be an individual cell

Page 245 - 4. Create a File Input Stream

Dynamic Data Exchange (DDE)7-33You set up and release advisory links with the ddeadv and ddeunadv functions. MATLAB only supports links when MATLAB is

Page 246

1 Calling C and Fortran Programs from MATLAB1-20Custom Building MEX-FilesThis section discusses in detail the process that the MEX-file build script u

Page 247

7 ActiveX and DDE Support7-34

Page 248

8Serial Port I/OIntroduction . . . . . . . . . . . . . . . . . . . . 8-2Overview of the Serial Port . .

Page 249 - 1. Input the Entry to Add

8 Serial Port I/O8-2IntroductionWhat Is MATLAB’s Serial Port Interface?MATLAB’s serial port interface provides direct access to peripheral devices suc

Page 250

8-3Using the Examples with Your DeviceMany of the examples in this section reflect specific peripheral devices connected to a PC serial port – in part

Page 251

8 Serial Port I/O8-4Overview of the Serial PortThis section provides an overview of the serial port. Topics include:•What is Serial Communication?•The

Page 252

Overview of the Serial Port8-5•The names, electrical characteristics, and functions of signals•The mechanical connections and pin assignmentsPrimary c

Page 253 - Running the phonebook Program

8 Serial Port I/O8-6If you connect two DTE’s or two DCE’s using a straight serial cable, then the TD pin on each device are connected to each other, a

Page 254

Overview of the Serial Port8-7The pin assignment scheme for a 9-pin male connector on a DTE is given below.The pins and signals associated with the 9-

Page 255

8 Serial Port I/O8-8Note The serial port pin and signal assignments are with respect to the DTE. For example, data is transmitted from the TD pin of

Page 256

Overview of the Serial Port8-9The “on” and “off” states for a data signal and for a control signal are shown below.The Data PinsMost serial port devic

Page 257 - Importing and Exporting

Custom Building MEX-Files1-21series of variable assignments; each variable represents a different logical piece of the build process.Table 1-3: MEX S

Page 258 - Importing and Exporting Data

8 Serial Port I/O8-10The RTS and CTS Pins. The RTS and CTS pins are used to signal whether the devices are ready to send or receive data. This type of

Page 259 - Using MAT-Files

Overview of the Serial Port8-11receiving a signal of a suitable frequency. CD is unasserted if the DCE is not receiving a suitable signal.RI is used t

Page 260 - Exporting Data from MATLAB

8 Serial Port I/O8-12When reading or writing data, you may need to specify a value, which can consist of one or more bytes. For example, if you read o

Page 261 - Use MATLAB I/O functions

Overview of the Serial Port8-131 The start bit is transmitted with a value of 0.2 The data bits are transmitted. The first data bit corresponds to the

Page 262 - MAT-File Interface Library

8 Serial Port I/O8-14eighth bit is used, it must have a value of 0. If the data is based on the extended ASCII character set, then eight bits must be

Page 263

Overview of the Serial Port8-15transmitting device to produce an even number of 1’s. If odd parity is selected, then the parity bit is set to 1 by the

Page 264 - Finding Associated Files

8 Serial Port I/O8-16To obtain information on the possible settings for COM1, select this port under the Ports list box and then select Settings.You c

Page 265 - Example Files

Overview of the Serial Port8-17Note If the setserial -ag command does not work, make sure that you have read and write permission for the port.For al

Page 266

8 Serial Port I/O8-18Getting Started with Serial I/OTo get you started with MATLAB’s serial port interface, this section provides the following inform

Page 267 - Examples of MAT-Files

Getting Started with Serial I/O8-19The Serial Port SessionThe serial port session comprises all the steps you are likely to take when communicating wi

Page 268

1 Calling C and Fortran Programs from MATLAB1-22Default Options File on UNIXThe default MEX options file provided with MATLAB is located in <matlab

Page 269

8 Serial Port I/O8-20Configuring and Returning PropertiesYou establish the desired serial port object behavior by configuring property values. You can

Page 270

Getting Started with Serial I/O8-21 RequestToSend: [ {on} | off ] StopBits TerminatorYou can use the get function to display one or more prop

Page 271

8 Serial Port I/O8-22 Parity = none PinStatus = [1x1 struct] PinStatusFcn = Port = COM1 ReadAsyncMode = continuous RequestToSend =

Page 272 - Reading a MAT-File in C

Getting Started with Serial I/O8-23Note that you can configure only one property value at a time using the dot notation.In practice, you can configure

Page 273

8 Serial Port I/O8-24Creating a Serial Port ObjectYou create a serial port object with the serial function. serial requires the name of the serial por

Page 274

Creating a Serial Port Object8-25Configuring Properties During Object CreationYou can configure serial port properties during object creation. serial

Page 275

8 Serial Port I/O8-26Creating an Array of Serial Port ObjectsIn MATLAB, you can create an array from existing variables by concatenating those variabl

Page 276

Connecting to the Device8-27Connecting to the DeviceBefore you can use the serial port object to write or read data, you must connect it to your devic

Page 277

8 Serial Port I/O8-28Configuring Communication SettingsBefore you can write or read data, both the serial port object and the device must have identic

Page 278

Writing and Reading Data8-29Writing and Reading DataFor many serial port applications, there are three important questions that you should consider wh

Page 279

Custom Building MEX-Files1-23mex uses the first occurrence of the options file it finds. If no options file is found, mex displays an error message. Y

Page 280 - Reading a MAT-File in Fortran

8 Serial Port I/O8-30access to the command line, and you can issue additional commands while the read or write function executes in the background.The

Page 281

Writing and Reading Data8-31For example, since serial ports have separate read and write pins, you can simultaneously read and write data. This is ill

Page 282

8 Serial Port I/O8-32The properties associated with writing data are given below.The Output Buffer and Data FlowThe output buffer is computer memory a

Page 283

Writing and Reading Data8-33For example, suppose you write the string command *IDN? to the TDS 210 oscilloscope using the fprintf function. As shown b

Page 284

8 Serial Port I/O8-34As shown below, after the string is written to the output buffer, it is then written to the device via the serial port.Writing Te

Page 285

Writing and Reading Data8-35Note that the ValuesSent property value includes the terminator since each occurrence of \n in the command sent to the dev

Page 286 - Using the Options File

8 Serial Port I/O8-36Writing Binary DataYou use the fwrite function to write binary data to the device. Writing binary data means writing numerical va

Page 287 - ActiveX and DDE Support

Writing and Reading Data8-37The functions associated with reading data are given below.The properties associated with reading data are given below.Tab

Page 288 - 7 ActiveX and DDE Support

8 Serial Port I/O8-38The Input Buffer and Data FlowThe input buffer is computer memory allocated by the serial port object to store data that is to be

Page 289 - ActiveX Interfaces

Writing and Reading Data8-39Note that for a given read operation, you may not know the number of bytes returned by the device. Therefore, you may need

Page 290

1 Calling C and Fortran Programs from MATLAB1-24in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB. Under Windo

Page 291

8 Serial Port I/O8-40You can verify the number of values read from the device – including the terminator – with the ValuesReceived property.s.ValuesRe

Page 292 - Manipulating the Interface

Writing and Reading Data8-41Asynchronous operations do not block access to the MATLAB command line. Additionally, while an asynchronous read operation

Page 293

8 Serial Port I/O8-42s.BytesAvailableans = 69You can return the data to MATLAB using any of the synchronous read functions. However, if you use fge

Page 294 - Writing Event Handlers

Writing and Reading Data8-43fopen(s)3. Write and read data – Write the *IDN? command to the instrument using fprintf, and then read back the result of

Page 295

8 Serial Port I/O8-44delete(s)clear sExample: Parsing Input Data Using strreadThis example illustrates how to use the strread function to parse and fo

Page 296

Writing and Reading Data8-45hfc = 0par = 'NONE'tm = 'LF'4. Disconnect and clean up – When you no longer need s, you sh

Page 297 - Converting Data

8 Serial Port I/O8-46fopen(s)4. Write and read data – Configure the scope to transfer the screen display as a bitmap. fprintf(s,'HARDCOPY:PORT RS

Page 298

Writing and Reading Data8-47Since the scope returns the screen display data using only two colors, an appropriate colormap is selected.mymap = [0 0 0;

Page 299 - MATLAB Sample Control

8 Serial Port I/O8-48Events and CallbacksYou can enhance the power and flexibility of your serial port application by using events. An event occurs af

Page 300

Events and Callbacks8-49Event Types and Callback PropertiesThe serial port event types and associated callback properties are described below.Break-In

Page 301 - % Quit Excel

Custom Building MEX-Files1-25Build OptionsFor customizing the build process, you should modify the options file. The options file contains the compile

Page 302

8 Serial Port I/O8-50buffer. If BytesAvailableFcnMode is terminator, then the callback function executes every time the character specified by the Ter

Page 303

Events and Callbacks8-51Functions” on page 8-52, these two fields are associated with a structure that you define in the callback function header. Ref

Page 304

8 Serial Port I/O8-52The AbsTime Field. AbsTime is defined for all events, and indicates the absolute time the event occurred. The absolute time is re

Page 305

Events and Callbacks8-53You pass additional parameters to the callback function by including both the callback function and the parameters as elements

Page 306

8 Serial Port I/O8-54Example: Using Events and CallbacksThis example uses the M-file callback function instrcallback to display event-related informat

Page 307

Events and Callbacks8-55Read the data from the input buffer.out = fscanf(s)out =9600;0;0;NONE;LF5. Disconnect and clean up – When you no longer need s

Page 308

8 Serial Port I/O8-56Using Control PinsAs described in “Serial Port Signals and Pin Assignments” on page 8-6, 9-pin serial ports include six control p

Page 309 - Dynamic Data Exchange (DDE)

Using Control Pins8-571. Create the serial port objects – After the modems are powered on, the serial port object s1 is created for the first modem, a

Page 310 - Clipboard Formats

8 Serial Port I/O8-58Write the ata command to the second modem. This command puts the modem in “answer mode,” which forces it to connect to the first

Page 311 - Accessing MATLAB As a Server

Using Control Pins8-59fclose([s1 s2])delete([s1 s2])clear s1 s2Controlling the Flow of Data: HandshakingData flow control or handshaking is a method u

Page 312 - MATLAB System Topic

1 Calling C and Fortran Programs from MATLAB1-26For specifics on the default settings for these variables, you can:•Examine the options file in <ma

Page 313 - MATLAB Engine Topic

8 Serial Port I/O8-60Note Some devices also use the DTR and DSR pins for handshaking. However, these pins are typically used to indicate that the sys

Page 314 - Requesting Data from MATLAB

Using Control Pins8-61Example: Using Software HandshakingSuppose you want to use software flow control with the example described in “Example: Reading

Page 315 - Sending Data to MATLAB

8 Serial Port I/O8-62Debugging: Recording Information to DiskWhile the serial port object is connected to the device, you can record this information

Page 316

Debugging: Recording Information to Disk8-63fprintf(s,'RS232?')rs232 = fscanf(s);End the serial port session.fclose(s)delete(s)clear sYou ca

Page 317 - Using MATLAB As a Client

8 Serial Port I/O8-64The Record File FormatThe record file is an ASCII file that contains a record of one or more serial port sessions. You specify th

Page 318

Debugging: Recording Information to Disk8-65Example: Recording Information to DiskThis example illustrates how to record information transferred betwe

Page 319

8 Serial Port I/O8-66char(ptop)'ans =2.0199999809E0The recording state is toggled from on to off. Since the RecordMode value is index, the record

Page 320

Debugging: Recording Information to Disk8-67 MEASUREMENT:IMMED:SOURCE CH25 > 26 ascii values. MEASUREMENT:IMMED:SOURCE?6 < 4 a

Page 321

8 Serial Port I/O8-68Saving and LoadingYou can save serial port objects to a MAT-file just as you would any workspace variable – using the save comman

Page 322 - Introduction

Disconnecting and Cleaning Up8-69Disconnecting and Cleaning UpWhen you no longer need your serial port object, you should disconnect it from the devic

Page 323

Custom Building MEX-Files1-27and the DEBUGFLAGS are used if you set the -g switch on the mex command line.Prelink StageThe prelink stage dynamically c

Page 324 - Overview of the Serial Port

8 Serial Port I/O8-70Property ReferenceThis section includes information to help you learn about serial port properties. The information is organized

Page 325

Property Reference8-71Serial Port Object PropertiesThe serial port object properties are briefly described below, and organized into categories based

Page 326 - 8 Serial Port I/O

8 Serial Port I/O8-72Read PropertiesBytesAvailableIndicate the number of bytes available in the input bufferInputBufferSize Specify the size of the in

Page 327

Property Reference8-73OutputEmptyFcn Specify the M-file callback function to execute when the output buffer is emptyPinStatusFcn Specify the M-file ca

Page 328 - Signal States

8 Serial Port I/O8-74General Purpose Properties ByteOrderSpecify the order in which the device stores bytesName Specify a descriptive name for the ser

Page 329 - The Control Pins

I-1 IndexSymbols%val 3-5, 3-8allocating memory 3-25DIGITAL Visual Fortran 3-8AActiveXautomation client 7-4automation server 7-4, 7-16callback 7-

Page 330

IndexI-2accessing elements of 5-36assigningthe empty matrix 5-41values to 5-39with single subscripts 5-40comparison with MATLAB arrays 5-30concatenati

Page 331 - Bytes Versus Values

IndexI-3calling user-defined functions 2-33handling 8-, 16-, 32-bit data 2-23handling arrays 2-25handling complex data 2-21handling sparse arrays 2-29

Page 332 - How Are the Bits Transmitted?

IndexI-4UNIX 1-12Windows 1-14, 1-16control pinsserial port object, using 8-56convec.c 2-21convec.f 3-22conversation (DDE) 7-23conversion, datain Java

Page 333 - Data Bits

IndexI-5ddeunadv 7-31debugging C language MEX-files 2-47UNIX 2-47Windows 2-48debugging Fortran language MEX-filesUNIX 3-38Windows 3-39DEC Alphadeclari

Page 334 - The Parity Bit

ii ContentsExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-46Technical Support . . . . . . . . . . .

Page 335 - Windows Platform

1 Calling C and Fortran Programs from MATLAB1-28for -output to work. If this environment is not set, the compiler default is to use the name of the fi

Page 336 - UNIX Platform

IndexI-6from Fortran program 4-11engine functions 4-3–4-4engine library 4-2communicating with MATLABUNIX 4-4Windows 4-4engOpen 4-3, 4-4engOpenSingleUs

Page 337 - Selected Bibliography

IndexI-7passing matrices 3-17passing multiple values 3-19passing scalar 2-7, 3-10passing strings 3-12Fortran language MEX-files 3-3components 3-3fread

Page 338

IndexI-8LLAPACK and BLAS functions 2-40building MEX files for 2-44example of 2-46handling complex numbers 2-42passing arguments 2-41specifying the fun

Page 339 - , or readasync function

IndexI-9MAT-file 6-6reading arrays from 6-6saving arrays to 6-6moving data between platforms 6-5–6-6stand-alone applications 6-2, 6-3string 1-7using a

Page 340

IndexI-10-U<name> 1-22-v 1-22-V4 1-22mex directory 1-47mex.bat 2-9mex.m 2-9mex.sh 2-9mexAtExit 2-39register a function 2-39mexaxp extension 1-3m

Page 341

IndexI-11msvc60engmatopts.bat 1-18msvc60opts.bat 1-18multidimensional arrays 1-8mx directory 1-47mxArray 1-6, 3-7accessing data 2-3contents 1-6imprope

Page 342 - Configuring Property Values

IndexI-12specifying 1-17when to specify 1-17overloading Java methods 5-54Pparity bit 8-14passing data to Java methods 5-46passstr.f 3-15persistent arr

Page 343 - Default Property Values

IndexI-13recording information to disk 8-62using control pins 8-56using events and callbacks 8-48writing and reading data 8-29writing binary data 8-36

Page 344 - Creating a Serial Port Object

IndexI-14watcopts.bat 1-18watengmatopts.bat 1-19whichusing with Java methods 5-25WindowsActiveX 7-16automation 7-16directory organization 1-44mex -set

Page 345

Custom Building MEX-Files1-293 Add the .DEF file to the project.4 Locate the .LIB files for the compiler version you are using under matlabroot\extern

Page 346

1 Calling C and Fortran Programs from MATLAB1-30mex -setupFollow the menus and choose either Microsoft Visual C/C++ 5.0 or 6.0. This configures mex to

Page 347 - Connecting to the Device

Custom Building MEX-Files1-31For additional information on the MATLAB add-in for Visual Studio:•See the MATLABAddin.hlp file in the <matlab>\bin

Page 348

1 Calling C and Fortran Programs from MATLAB1-32TroubleshootingThis section explains how to troubleshoot some of the more common problems you may enco

Page 349 - function

Troubleshooting1-33mex.bat: internal error in sub get_compiler_info(): don't recognize <string>then you need to disable your antivirus soft

Page 350

1 Calling C and Fortran Programs from MATLAB1-34Figure 1-1: Troubleshooting MEX-File Creation ProblemsProblems 1 through 5 refer to specific sections

Page 351 - Writing Data

Troubleshooting1-35MathWorks Technical Support Web site at http://www.mathworks.com/support.Problem 1 - Compiling a MathWorks Program FailsThe most co

Page 352

1 Calling C and Fortran Programs from MATLAB1-36symbols or unresolved references. Be sure to link against the library that defines the function in que

Page 353 - Writing and Reading Data

Troubleshooting1-37•Run MATLAB within a debugging environment. This process is already described in the chapters on creating C and Fortran MEX-files,

Page 354 - Writing Text Data

iii3Creating Fortran MEX-FilesFortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3The Components of a Fortr

Page 355

1 Calling C and Fortran Programs from MATLAB1-38We highly recommend that you fix code in your MEX-files that produces any of the warnings discussed in

Page 356 - Writing Binary Data

Troubleshooting1-39SolutionCall mxDestroyArray instead. mxDestroyArray(temp); /* CORRECT */Incorrectly Constructing a Cell or Structure mxArrayYou

Page 357

1 Calling C and Fortran Programs from MATLAB1-40Creating a Temporary mxArray with Improper DataYou cannot call mxDestroyArray on an mxArray whose data

Page 358

Troubleshooting1-41For example,pr = mxCalloc(5*5, sizeof(double));... <load data into pr>plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);mxSetPr(plhs

Page 359 - Reading Text Data

1 Calling C and Fortran Programs from MATLAB1-42Additional InformationThe following sections describe how to find additional information and assistanc

Page 360

Additional Information1-43<matlab>/binThe <matlab>/bin directory contains two files that are relevant for the MATLAB API.mex UNIX shell sc

Page 361 - A read operation with fscanf

1 Calling C and Fortran Programs from MATLAB1-44<matlab>/extern/includeThe <matlab>/extern/include directory contains the header files for

Page 362 - , then you must issue the

Additional Information1-45<matlab>\bin\win32The <matlab>\bin\win32 directory contains the mex.bat batch file that builds C and Fortran fil

Page 363

1 Calling C and Fortran Programs from MATLAB1-46<matlab>\extern\includeThe <matlab>\extern\include directory contains the header files for

Page 364 - . RS232?

Additional Information1-47MEX Reference ExamplesThe mex subdirectory of /extern/examples directory contains MEX-file examples. It includes the example

Page 365 - Example: Reading Binary Data

iv ContentsCalling MATLAB From a Fortran Application . . . . . . . . . . . . 4-11Attaching to an Existing MATLAB Session . . . . . . . . . . . . .

Page 366 - Viewing the Bitmap Data

1 Calling C and Fortran Programs from MATLAB1-48Technical SupportThe MathWorks provides additional Technical Support through its web site. A few of th

Page 367

2Creating C Language MEX-FilesC MEX-Files . . . . . . . . . . . . . . . . . . . . 2-3The Components of a C

Page 368 - Events and Callbacks

2 Creating C Language MEX-Files2-2This chapter describes how to write MEX-files in the C programming language. It discusses the MEX-file itself, how t

Page 369

C MEX-Files2-3C MEX-FilesC MEX-files are built by using the mex script to compile your C source code with additional calls to API routines.The Compone

Page 370

2 Creating C Language MEX-Files2-4Figure 2-1: C MEX Cycleconst mxArray *AA = prhs[0]MATLAB A call toMEX-file func:[C,D]=func(A,B)tells MATLAB to pass

Page 371

C MEX-Files2-5Required Arguments to a MEX-FileThe two components of the MEX-file may be separate or combined. In either case, the files must contain t

Page 372

2 Creating C Language MEX-Files2-6For example, if you invoke a MEX-file from the MATLAB workspace with the commandx = fun(y,z);the MATLAB interpreter

Page 373

Examples of C MEX-Files2-7Examples of C MEX-FilesThe following sections include information and examples describing how to pass and manipulate the dif

Page 374

2 Creating C Language MEX-Files2-8{ y[0] = 2.0*x[0]; return;}Below is the same function written in the MEX-file format.#include "mex.h"/*

Page 375 - MATLAB workspace

Examples of C MEX-Files2-9 if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows == 1 && ncols == 1) ) { mexErrMsgTxt("Inpu

Page 376 - Using Control Pins

vJava Methods That Affect MATLAB Commands . . . . . . . . . . . 5-26How MATLAB Handles Undefined Methods . . . . . . . . . . . . . . 5-27How MATLAB

Page 377

2 Creating C Language MEX-Files2-10In the above example, scalars are viewed as 1-by-1 matrices. Alternatively, you can use a special API function call

Page 378

Examples of C MEX-Files2-11 /* Call the timestwo_alt subroutine. */ timestwo_alt(y,x);}This example passes the input scalar x by value into the time

Page 379 - Hardware Handshaking

2 Creating C Language MEX-Files2-12Note MATLAB automatically frees up memory allocated with the mx allocation routines (mxCalloc, mxMalloc, mxRealloc

Page 380 - Software Handshaking

Examples of C MEX-Files2-13 status = mxGetString(prhs[0], input_buf, buflen); if(status != 0) mexWarnMsgTxt("Not enough space. String is tr

Page 381

2 Creating C Language MEX-Files2-14and so on. Likewise, prhs[0] contains a pointer to the first right-hand side argument, prhs[1] points to the second

Page 382

Examples of C MEX-Files2-15void xtimesy(double x, double *y, double *z, int m, int n){ int i,j,count = 0; for(i = 0; i < n; i++) { for(j = 0

Page 383 - End the serial port session

2 Creating C Language MEX-Files2-16 /* Create a pointer to the input matrix y. */ y = mxGetPr(prhs[1]); /* Get the dimensions of the matrix input

Page 384

Examples of C MEX-Files2-17This example takes an m-by-n structure matrix as input and returns a new 1-by-1 structure that contains these fields:•Strin

Page 385

2 Creating C Language MEX-Files2-18 /* Check proper input and output */ if(nrhs != 1) mexErrMsgTxt("One input required."); else if

Page 386 - The Record File Contents

Examples of C MEX-Files2-19 mexErrMsgTxt("Inconsistent data type in above field!"); } else if(!mxIsChar(tmp) &&a

Page 387

vi ContentsExample – Communicating Through a Serial Port . . . . . . . 5-68Description of Serial Example . . . . . . . . . . . . . . . . . . . . . .

Page 388 - Saving and Loading

2 Creating C Language MEX-Files2-20 if(mxIsChar(tmp)) { mxSetCell(fout, jstruct, mxDuplicateArray(tmp)); } else { size_t s

Page 389 - Disconnecting and Cleaning Up

Examples of C MEX-Files2-21Handling Complex DataComplex data from MATLAB is separated into real and imaginary parts. MATLAB’s API provides two functio

Page 390 - Property Reference

2 Creating C Language MEX-Files2-22Below is the gateway routine that calls this complex convolution./* The gateway routine. */void mexFunction( int nl

Page 391 - Serial Port Object Properties

Examples of C MEX-Files2-23 /* Call the C subroutine. */ convec(xr, xi, nx, yr, yi, ny, zr, zi); return;}Entering these numbers at the MATLAB promp

Page 392

2 Creating C Language MEX-Files2-24arithmetic on data of 8-, 16- or 32-bit precision in MEX-files and return the result to MATLAB, which will recogniz

Page 393

Examples of C MEX-Files2-25/* The gataway function */void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ){

Page 394

2 Creating C Language MEX-Files2-26data types in MATLAB, arrays can be passed into and out of MEX-files written in C. You can manipulate multidimensio

Page 395 - Index

Examples of C MEX-Files2-27#define IsNonZero(d) ((d) != 0.0)#endifvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray

Page 396

2 Creating C Language MEX-Files2-28 /* Get the number of dimensions in the input argument. Allocate the space for the return argument */ number

Page 397

Examples of C MEX-Files2-29This example determines the position of all nonzero elements in the matrix. Running the MEX-file on this matrix producesnz

Page 398

vii7ActiveX and DDE SupportIntroducing MATLAB ActiveX Integration . . . . . . . . . . . . . . 7-3ActiveX Concepts and Terminology . . . . . . . .

Page 399

2 Creating C Language MEX-Files2-30* *=============================================================*//* $Revision: 1.5 $ */#include <math.h> /*

Page 400

Examples of C MEX-Files2-31 } /* Check data type of input argument. */ if(!(mxIsDouble(prhs[0]))) { mexErrMsgTxt("Input argument must be of

Page 401

2 Creating C Language MEX-Files2-32 if(IsNonZero(pr[i]) || (cmplx && IsNonZero(pi[i]))) { /* Check to see if non-zero element will

Page 402

Examples of C MEX-Files2-33At the MATLAB prompt, enteringfull = eye(5)full = 1 0 0 0 0 0 1 0 0 0 0 0

Page 403

2 Creating C Language MEX-Files2-34 * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. *==================================

Page 404

Examples of C MEX-Files2-35 mxDestroyArray(lhs[0]); return;}Running this examplesincalldisplays the resultsNote It is possible to generate an obj

Page 405

2 Creating C Language MEX-Files2-36MATLAB displays the following warning message.Warning: One or more output arguments not assigned during call to &ap

Page 406

Advanced Topics2-37Advanced TopicsThese sections cover advanced features of MEX-files that you can use when your applications require sophisticated ME

Page 407

2 Creating C Language MEX-Files2-38Memory ManagementMemory management within MEX-files is not unlike memory management for regular C or Fortran applic

Page 408

Advanced Topics2-39creates persistent objects should register a function, using mexAtExit, which will dispose of the objects. (You can use a mexAtExit

Commentaires sur ces manuels

Pas de commentaire