ComputationVisualizationProgrammingExternal Interfaces Version 6
viii Contents8Serial Port I/OIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2What Is MATLAB’s Ser
2 Creating C Language MEX-Files2-40Hybrid ArraysFunctions such as mxSetPr, mxSetData, and mxSetCell allow the direct placement of memory pieces into a
Advanced Topics2-41This section explains how to write and build MEX-files that call LAPACK and BLAS functions. It provides information on:•Specifying
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])
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
2 Creating C Language MEX-Files2-44Preserving Input Values from ModificationMany LAPACK and BLAS functions modify the values of arguments passed in to
Advanced Topics2-45mex myCmexFile.c <matlab>/extern/lib/win32/microsoft/msvc60/libmwlapack.libFor IBM_RS, use the following syntax.mex myCmexFil
2 Creating C Language MEX-Files2-46mex myCmexFile.c <matlab>/extern/examples/refbook/fort.c -I<matlab>/extern/examples/refbook Example – S
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
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
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
ixEvents and Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-48Example: Introduction to Events and Callbacks . . . . .
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
3Creating Fortran MEX-FilesFortran MEX-Files . . . . . . . . . . . . . . . . . 3-3The Components of a Fortran MEX
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
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
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
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
3 Creating Fortran MEX-Files3-6The Gateway RoutineThe entry point to the gateway subroutine must be named mexFunction and must contain these parameter
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
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
Examples of Fortran MEX-Files3-9Examples of Fortran MEX-FilesThe following sections include information and examples describing how to pass and manipu
x Contents
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
Examples of Fortran MEX-Files3-11C Check for proper number of arguments. if(nrhs .ne. 1) then call mexErrMsgTxt('One input requ
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
Examples of Fortran MEX-Files3-13Below is the gateway routine that calls the computational routine.C The gateway routine subroutine mexFuncti
3 Creating Fortran MEX-Files3-14C Initialize outbuf_buf to blanks. This is necessary on some C compilers. output_buf = ' 'C
Examples of Fortran MEX-Files3-15MEX-file. Consequently, when returning to MATLAB, the output matrix must be transposed.This example places a string a
3 Creating Fortran MEX-Files3-16 character*15 string(5)C Create the string to passed into MATLAB. string(1) = 'MATLAB &apos
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
3 Creating Fortran MEX-Files3-18 integer x_pr, y_prC--------------------------------------------------------------C integer nlhs, nrhs
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
1Calling C and Fortran Programs from MATLABIntroducing MEX-Files . . . . . . . . . . . . . . . 1-3Using MEX-Files .
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
Examples of Fortran MEX-Files3-21 endifC Check to see both inputs are numeric. if (mxIsNumeric(prhs(1)) .ne. 1) then call mexErr
3 Creating Fortran MEX-Files3-22As this example shows, creating MEX-file gateways that handle multiple inputs and outputs is straightforward. All you
Examples of Fortran MEX-Files3-23C==============================================================CC Computational subroutine subroutine convec
3 Creating Fortran MEX-Files3-24 endifC Check that inputs are both row vectors. mx = mxGetM(prhs(1)) nx = mxGetN(prhs(1)) my =
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.
3 Creating Fortran MEX-Files3-26C $Revision: 1.12 $C===============================================================C C dblmat.fC Examp
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
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
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
1 Calling C and Fortran Programs from MATLAB1-2Although MATLAB® is a complete, self-contained environment for programming and manipulating data, it is
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
Examples of Fortran MEX-Files3-31CC This is a MEX-file for MATLAB.C Copyright (c) 1984-2000 The MathWorks, Inc. C C=======================
3 Creating Fortran MEX-Files3-32At the MATLAB prompt, enteringfull = eye(5)full = 1 0 0 0 0 0 1 0 0 0 0
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
3 Creating Fortran MEX-Files3-34 call mxFreeMatrix(lhs(1)) return end C $Revision: 1.3 $C ========================================
Examples of Fortran MEX-Files3-35Running this examplesincalldisplays the resultsNote It is possible to generate an object of type mxUNKNOWN_CLASS usi
3 Creating Fortran MEX-Files3-36Advanced TopicsThese sections cover advanced features of MEX-files that you can use when your applications require sop
Advanced Topics3-37Memory ManagementAs of Version 5.2, MATLAB now implicitly destroys (by calling mxDestroyArray) any arrays created by a MEX-file tha
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
Debugging Fortran Language MEX-Files3-39Note The name mexFunction may be slightly altered by the compiler (i.e., it may have an underscore appended).
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
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
4Calling MATLAB from C and Fortran ProgramsUsing the MATLAB Engine . . . . . . . . . . . . . 4-3The Engine Library . .
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
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
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
Using the MATLAB Engine4-5GUI-Intensive ApplicationsIf you have graphical user interface (GUI) intensive applications that execute a lot of callbacks
4 Calling MATLAB from C and Fortran Programs4-6Examples of Calling Engine FunctionsThis section contains examples that illustrate how to call engine f
Examples of Calling Engine Functions4-7int main(){ Engine *ep; mxArray *T = NULL, *result = NULL; char buffer[BUFSIZE]; double time[10] = { 0.0, 1
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
Examples of Calling Engine Functions4-9 */ engOutputBuffer(ep, buffer, BUFSIZE); while (result == NULL) { char str[BUFSIZE]; /* * Get a
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
4 Calling MATLAB from C and Fortran Programs4-10 /* * We're done! Free memory, close MATLAB engine and exit. */ printf("Done!\n")
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
4 Calling MATLAB from C and Fortran Programs4-12C Other variable declarations here double precision time(10), dist(10) integer engPutMat
Examples of Calling Engine Functions4-13CC Plot the result.C if (engEvalString(ep, 'plot(T,D);') .ne. 0) then write(6,*) &ap
4 Calling MATLAB from C and Fortran Programs4-14C D = engGetMatrix(ep, 'D') call mxCopyPtrToReal8(mxGetPr(D), dist, 10)
Examples of Calling Engine Functions4-15The program continues withType 0 <return> to ExitType 1 <return> to continueEntering 1 at the prom
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
Compiling and Linking Engine Programs4-17Compiling and Linking Engine ProgramsTo produce an executable version of an engine program, you must compile
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
Compiling and Linking Engine Programs4-19Compiling and LinkingMATLAB provides an options file, engopts.sh, that lets you use the mex script to easily
Introducing MEX-Files1-5Note mex routines are only available in MEX-functions.
4 Calling MATLAB from C and Fortran Programs4-20
5Calling Java from MATLABUsing Java from MATLAB: An Overview . . . . . . . 5-3Bringing Java Classes into MATLAB . . . . .
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
Using Java from MATLAB: An Overview5-3Using Java from MATLAB: An OverviewJava Interface Is Integral to MATLABEvery installation of MATLAB includes a J
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
Bringing Java Classes into MATLAB5-5Bringing Java Classes into MATLABYou can draw from an extensive collection of existing Java classes or create your
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
Bringing Java Classes into MATLAB5-7and JAR files, consult your Java development documentation or the JavaSoft web site. See also “To Learn More About
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
Bringing Java Classes into MATLAB5-9•java.lang.String•java.util.EnumerationA fully qualified name can be rather long, making commands and functions, s
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
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
Creating and Using Java Objects5-11class, class_name, with the argument list that matches x1,...,xn, and returns a new object, J.J = javaObject('
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
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
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
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
5 Calling Java from MATLAB5-16'static final float BOTTOM_ALIGNMENT % Inherited from java.awt.Component''static final float LEFT_ALIG
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
5 Calling Java from MATLAB5-18frameClass = class(frame)frameClass = java.awt.FrameBecause this form of class also works on MATLAB objects, it does not
Invoking Methods on Java Objects5-19Invoking Methods on Java ObjectsThis section explains how to invoke an object’s methods in MATLAB. It also covers
MATLAB Data1-7its dimensions aresize(a)ans =3 5and its data is stored asData Types in MATLABComplex Double-Precision MatricesThe most common data
5 Calling Java from MATLAB5-20title = getTitle(frame)title = Sample FrameAll of the programming examples in this chapter contain invocations of Java o
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
5 Calling Java from MATLAB5-22Using the javaMethod Function on Static MethodsThe javaMethod function was introduced in section “Using the javaMethod F
Invoking Methods on Java Objects5-23The following command lists information on all methods in the java.awt.MenuItem class.methodsview java.awt.MenuIte
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
Invoking Methods on Java Objects5-25For example, display a full description of all methods of the java.awt.Dimension object.methods java.awt.Dimension
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
Invoking Methods on Java Objects5-27Changing the Effect of isequalThe MATLAB isequal function compares two or more arrays for equality in type, size,
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
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
How to Contact The MathWorks:www.mathworks.com Webcomp.soft-sys.matlab [email protected] Technical [email protected] Product
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
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
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[
5 Calling Java from MATLAB5-32Array IndexingJava array indexing is different than MATLAB array indexing. Java array indices are zero-based, MATLAB arr
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
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
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[][
5 Calling Java from MATLAB5-36This example first creates a scalar MATLAB array, and then successfully modifies it to be two-dimensional.matlabArray =
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
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
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
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
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
Working with Java Arrays5-41 [ 21] [ 22] [ 23] [ 24] [ 25] [100] [200] [300] [400] [500] [ 41] [ 42] [ 43] [
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.
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
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]
Working with Java Arrays5-45java.lang.Double[][]: [11] [12] [13] [14] [21] [22] [23] [24] [ 0] [ 0] [ 0] [ 0]Creat
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
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
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
Passing Data to a Java Method5-49[poly.xpoints poly.ypoints] % Verify the coordinatesans =14 5542 1298 -2124 62MATLAB Arrays Are P
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
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
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
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
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,...}.
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
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
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
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.
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
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
Building MEX-Files1-11Building MEX-FilesThis section covers the following topics:•“Compiler Requirements”•“Testing Your Configuration on UNIX”•“Testin
5 Calling Java from MATLAB5-60pstruct.xpointsans = 14 42 98 124pstruct.xpoints(3) = 101;Converting to a MATLAB Cell ArrayUse the cell funct
Handling Data Returned from a Java Method5-61% Convert each to cell arrayscellArray = {cell(dblArray), cell(ptArray), cell(strArray)}cellArray = {
5 Calling Java from MATLAB5-62Introduction to Programming ExamplesThe following programming examples demonstrate the MATLAB interface to Java classes
Example – Reading a URL5-63Example – Reading a URLThis program, URLdemo, opens a connection to a web site specified by a URL (Uniform Resource Locator
5 Calling Java from MATLAB5-64BufferedReader object to variable br. A buffered reader provides for efficient reading of characters, arrays, and lines.
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
5 Calling Java from MATLAB5-66Example – Finding an Internet Protocol AddressThe resolveip function returns either the name or address of an IP (intern
Example – Finding an Internet Protocol Address5-673. Display the Hostname or IP AddressThe example uses the MATLAB strcmp function to compare the inpu
5 Calling Java from MATLAB5-68Example – Communicating Through a Serial PortThe serialexample program uses classes of the Java API javax.comm package,
Example – Communicating Through a Serial Port5-69Description of Serial ExampleThe major tasks performed by serialexample are:1. Define Variables for S
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
5 Calling Java from MATLAB5-704. Configure the Serial PortThe next three statements call configuration methods on the SerialPort object serialPort. Th
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
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
Example – Creating and Using a Phone Book5-73Example – Creating and Using a Phone BookThe example’s main function, phonebook, can be called either wit
5 Calling Java from MATLAB5-74Description of Function phonebookThe major tasks performed by phonebook are:1. Determine the Data Directory and Full Fil
Example – Creating and Using a Phone Book5-75 if r == 'y', try FOS = java.io.FileOutputStream(pbname); FOS.close
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
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
5 Calling Java from MATLAB5-78object FOS and a descriptive header string. It then calls close on the FileOutputStream object, and returns. case &apo
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
Building MEX-Files1-13 Options files control which compiler to use, the compiler and link command options, and the runtime libraries to link
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
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.
5 Calling Java from MATLAB5-82pb_htable.put(pb_keyfilter(name),entry);disp ' 'disp(sprintf('The entry for %s has been changed', na
Example – Creating and Using a Phone Book5-83Description of Function pb_keyfilterThe pb_keyfilter function takes an argument key, which is a name used
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
Example – Creating and Using a Phone Book5-85 (508) 111-3456------------------------- ------------------------- Russell Reddy (617) 999-8765----------
5 Calling Java from MATLAB5-86
6Importing and Exporting DataUsing MAT-Files . . . . . . . . . . . . . . . . . . 6-3Importing Data to MATLAB .
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
Using MAT-Files6-3Using MAT-FilesThis section describes the various techniques for importing data to and exporting data from the MATLAB environment. T
1 Calling C and Fortran Programs from MATLAB1-14Testing Your Configuration on WindowsBefore you can create MEX-files on the Windows platform, you must
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
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
6 Importing and Exporting Data6-6Both types of files can be transported directly between machines: M-files because they are platform independent and M
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
6 Importing and Exporting Data6-8Finding Associated FilesA collection of files associated with reading and writing MAT-files is located on your disk.
Using MAT-Files6-9Include FilesThe include directory holds header files containing function declarations with prototypes for the routines that you can
6 Importing and Exporting Data6-10For additional information about the MATLAB API files and directories, see “Additional Information” on page 1-42.Tab
Examples of MAT-Files6-11Examples of MAT-FilesThis section includes C and Fortran examples of writing, reading, and diagnosing MAT-files. The examples
6 Importing and Exporting Data6-12#include <stdlib.h> /* For EXIT_FAILURE, EXIT_SUCCESS */#include "mat.h"#define BUFSIZE 256int main(
Examples of MAT-Files6-13 pa3 = mxCreateString("MATLAB: the language of technical computing"); if (pa3 == NULL) {
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
6 Importing and Exporting Data6-14 if (status != 0) { printf("%s : Error using matPutArray on line %d\n", __FILE__, __LINE__
Examples of MAT-Files6-15 pa2 = matGetArray(pmat, "GlobalDouble"); if (pa2 == NULL) { printf("Error reading existing matrix Global
6 Importing and Exporting Data6-16To produce an executable version of this example program, compile the file and link it with the appropriate library.
Examples of MAT-Files6-17 * matClose * matGetDir * matGetNextArray * matGetNextArrayHeader * matOpen * * Copyright (c) 1984-1998 The MathWorks
6 Importing and Exporting Data6-18 mxFree(dir); /* In order to use matGetNextXXX correctly, reopen file to read in headers. */ if (matClose(pm
Examples of MAT-Files6-19 if (pmat == NULL) { printf("Error reopening file %s\n", file); return(1); } /* Read in each array. */ pr
6 Importing and Exporting Data6-20 else { result = 0; printf("Usage: matdgns <matfile>"); printf("where <matfile>
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
6 Importing and Exporting Data6-22 if (mp .eq. 0) then write(6,*) 'Can''t open ''matdemo.mat'' for writing.&a
Examples of MAT-Files6-23 if (status .ne. 0) then write(6,*) 'Error closing MAT-file' stop end ifC mp = matOp
1 Calling C and Fortran Programs from MATLAB1-16The default options file:"C:\WINNT\Profiles\username\ApplicationData\MathWorks\MATLAB\R12\mexopts
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
Examples of MAT-Files6-25C--------------------------------------------------------------C $Revision: 1.7 $C program matdemo2C----------------
6 Importing and Exporting Data6-26CC Copy integer to character stringC do 20 i=1,ndir call mxCopyPtrToCharacter(adir(i), names(i), 32
Examples of MAT-Files6-27 end doC stat = matClose(mp) if (stat .ne. 0) then write(6,*) 'Error closing ''matdemo.
6 Importing and Exporting Data6-28Compiling and Linking MAT-File ProgramsThis section describes the steps required to compile and link MAT-file progra
Compiling and Linking MAT-File Programs6-29#include <float.h> . . ._control87(MCW_EM,MCW_EM); . . .Compiling and Linking on UNIXUnde
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
7ActiveX and DDE SupportIntroducing MATLAB ActiveX Integration . . . . . . 7-3ActiveX Concepts and Terminology . . . . . .
7 ActiveX and DDE Support7-2ActiveX is a set of object-oriented technologies and tools that allow software developers to integrate application-specifi
Introducing MATLAB ActiveX Integration7-3Introducing MATLAB ActiveX Integration ActiveX is a Microsoft Windows protocol for component integration. Usi
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
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
Introducing MATLAB ActiveX Integration7-5In general, servers that are not controls will not be physically or visually embedded in the client applicati
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
MATLAB ActiveX Client Support7-7The creation commands, actxcontrol and actxserver, both return a MATLAB activex object, which represents the default i
7 ActiveX and DDE Support7-8Writing Event HandlersActiveX events are invoked when a control wants to notify its container that something of interest h
Writing Event Handlers7-9function myclick(varargin)disp('Single click function')function my2click(varargin)disp('Double click function&
7 ActiveX and DDE Support7-10Additional ActiveX Client InformationReleasing InterfacesEach ActiveX object can support one or more interfaces. In MATLA
Additional ActiveX Client Information7-11activex object called hPlot.) In particular, this example iterates through a collection of Plot interfaces, i
7 ActiveX and DDE Support7-12Using MATLAB As a DCOM Server ClientDistributed Component Object Model (DCOM) is an object distribution mechanism that al
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
iContents1Calling C and Fortran Programs from MATLABIntroducing MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Using M
1 Calling C and Fortran Programs from MATLAB1-18Microsoft C/C++, Version 5.0msvc50opts.batMicrosoft C/C++, Version 6.0msvc60opts.batWatcom C/C++, Vers
7 ActiveX and DDE Support7-14% MATLAB ActiveX automation client example %% Open Excel, add workbook, change active worksheet, % get/put array, save.%
Additional ActiveX Client Information7-15% Workbook.Saved = 1;% invoke(Workbook, 'Close');% Quit Excel.invoke(Excel, 'Quit');
7 ActiveX and DDE Support7-16MATLAB ActiveX Automation Server SupportMATLAB on Microsoft Windows supports ActiveX Automation server capabilities. Auto
MATLAB ActiveX Automation Server Support7-17Note The first statement above should be declared in the general declarations section in order to keep th
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
MATLAB ActiveX Automation Server Support7-19void PutFullMatrix([in] BSTR Name, [in] BSTR Workspace, [in] SAFEARRAY(double) pr, [in] SAFEARRAY(double)
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
Additional ActiveX Server Information7-21Additional ActiveX Server InformationLaunching the MATLAB ActiveX ServerFor MATLAB to act as an automation se
7 ActiveX and DDE Support7-22of a dedicated server running simultaneously, since the dedicated server is not shared by multiple clients.Using MATLAB A
Dynamic Data Exchange (DDE)7-23Dynamic Data Exchange (DDE)MATLAB provides functions that enable MATLAB to access other Windows applications and for ot
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
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
Dynamic Data Exchange (DDE)7-25•Metafilepict – Metafilepict format is a description of graphical data containing the drawing commands for graphics. As
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
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,
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
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
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
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
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
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
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
7 ActiveX and DDE Support7-34
8Serial Port I/OIntroduction . . . . . . . . . . . . . . . . . . . . 8-2Overview of the Serial Port . .
8 Serial Port I/O8-2IntroductionWhat Is MATLAB’s Serial Port Interface?MATLAB’s serial port interface provides direct access to peripheral devices suc
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
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
Overview of the Serial Port8-5•The names, electrical characteristics, and functions of signals•The mechanical connections and pin assignmentsPrimary c
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
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-
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
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
Custom Building MEX-Files1-21series of variable assignments; each variable represents a different logical piece of the build process.Table 1-3: MEX S
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
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
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
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
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
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
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
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
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
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
1 Calling C and Fortran Programs from MATLAB1-22Default Options File on UNIXThe default MEX options file provided with MATLAB is located in <matlab
8 Serial Port I/O8-20Configuring and Returning PropertiesYou establish the desired serial port object behavior by configuring property values. You can
Getting Started with Serial I/O8-21 RequestToSend: [ {on} | off ] StopBits TerminatorYou can use the get function to display one or more prop
8 Serial Port I/O8-22 Parity = none PinStatus = [1x1 struct] PinStatusFcn = Port = COM1 ReadAsyncMode = continuous RequestToSend =
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
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
Creating a Serial Port Object8-25Configuring Properties During Object CreationYou can configure serial port properties during object creation. serial
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
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
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
Writing and Reading Data8-29Writing and Reading DataFor many serial port applications, there are three important questions that you should consider wh
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
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
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
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
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
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
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
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
Writing and Reading Data8-37The functions associated with reading data are given below.The properties associated with reading data are given below.Tab
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
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
1 Calling C and Fortran Programs from MATLAB1-24in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB. Under Windo
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
Writing and Reading Data8-41Asynchronous operations do not block access to the MATLAB command line. Additionally, while an asynchronous read operation
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
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
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
Writing and Reading Data8-45hfc = 0par = 'NONE'tm = 'LF'4. Disconnect and clean up – When you no longer need s, you sh
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
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;
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
Events and Callbacks8-49Event Types and Callback PropertiesThe serial port event types and associated callback properties are described below.Break-In
Custom Building MEX-Files1-25Build OptionsFor customizing the build process, you should modify the options file. The options file contains the compile
8 Serial Port I/O8-50buffer. If BytesAvailableFcnMode is terminator, then the callback function executes every time the character specified by the Ter
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
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
Events and Callbacks8-53You pass additional parameters to the callback function by including both the callback function and the parameters as elements
8 Serial Port I/O8-54Example: Using Events and CallbacksThis example uses the M-file callback function instrcallback to display event-related informat
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
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
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
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
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
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
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
Using Control Pins8-61Example: Using Software HandshakingSuppose you want to use software flow control with the example described in “Example: Reading
8 Serial Port I/O8-62Debugging: Recording Information to DiskWhile the serial port object is connected to the device, you can record this information
Debugging: Recording Information to Disk8-63fprintf(s,'RS232?')rs232 = fscanf(s);End the serial port session.fclose(s)delete(s)clear sYou ca
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
Debugging: Recording Information to Disk8-65Example: Recording Information to DiskThis example illustrates how to record information transferred betwe
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
Debugging: Recording Information to Disk8-67 MEASUREMENT:IMMED:SOURCE CH25 > 26 ascii values. MEASUREMENT:IMMED:SOURCE?6 < 4 a
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
Disconnecting and Cleaning Up8-69Disconnecting and Cleaning UpWhen you no longer need your serial port object, you should disconnect it from the devic
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
8 Serial Port I/O8-70Property ReferenceThis section includes information to help you learn about serial port properties. The information is organized
Property Reference8-71Serial Port Object PropertiesThe serial port object properties are briefly described below, and organized into categories based
8 Serial Port I/O8-72Read PropertiesBytesAvailableIndicate the number of bytes available in the input bufferInputBufferSize Specify the size of the in
Property Reference8-73OutputEmptyFcn Specify the M-file callback function to execute when the output buffer is emptyPinStatusFcn Specify the M-file ca
8 Serial Port I/O8-74General Purpose Properties ByteOrderSpecify the order in which the device stores bytesName Specify a descriptive name for the ser
I-1 IndexSymbols%val 3-5, 3-8allocating memory 3-25DIGITAL Visual Fortran 3-8AActiveXautomation client 7-4automation server 7-4, 7-16callback 7-
IndexI-2accessing elements of 5-36assigningthe empty matrix 5-41values to 5-39with single subscripts 5-40comparison with MATLAB arrays 5-30concatenati
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
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
IndexI-5ddeunadv 7-31debugging C language MEX-files 2-47UNIX 2-47Windows 2-48debugging Fortran language MEX-filesUNIX 3-38Windows 3-39DEC Alphadeclari
ii ContentsExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-46Technical Support . . . . . . . . . . .
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
IndexI-6from Fortran program 4-11engine functions 4-3–4-4engine library 4-2communicating with MATLABUNIX 4-4Windows 4-4engOpen 4-3, 4-4engOpenSingleUs
IndexI-7passing matrices 3-17passing multiple values 3-19passing scalar 2-7, 3-10passing strings 3-12Fortran language MEX-files 3-3components 3-3fread
IndexI-8LLAPACK and BLAS functions 2-40building MEX files for 2-44example of 2-46handling complex numbers 2-42passing arguments 2-41specifying the fun
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
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
IndexI-11msvc60engmatopts.bat 1-18msvc60opts.bat 1-18multidimensional arrays 1-8mx directory 1-47mxArray 1-6, 3-7accessing data 2-3contents 1-6imprope
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
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
IndexI-14watcopts.bat 1-18watengmatopts.bat 1-19whichusing with Java methods 5-25WindowsActiveX 7-16automation 7-16directory organization 1-44mex -set
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
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
Custom Building MEX-Files1-31For additional information on the MATLAB add-in for Visual Studio:•See the MATLABAddin.hlp file in the <matlab>\bin
1 Calling C and Fortran Programs from MATLAB1-32TroubleshootingThis section explains how to troubleshoot some of the more common problems you may enco
Troubleshooting1-33mex.bat: internal error in sub get_compiler_info(): don't recognize <string>then you need to disable your antivirus soft
1 Calling C and Fortran Programs from MATLAB1-34Figure 1-1: Troubleshooting MEX-File Creation ProblemsProblems 1 through 5 refer to specific sections
Troubleshooting1-35MathWorks Technical Support Web site at http://www.mathworks.com/support.Problem 1 - Compiling a MathWorks Program FailsThe most co
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
Troubleshooting1-37•Run MATLAB within a debugging environment. This process is already described in the chapters on creating C and Fortran MEX-files,
iii3Creating Fortran MEX-FilesFortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3The Components of a Fortr
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
Troubleshooting1-39SolutionCall mxDestroyArray instead. mxDestroyArray(temp); /* CORRECT */Incorrectly Constructing a Cell or Structure mxArrayYou
1 Calling C and Fortran Programs from MATLAB1-40Creating a Temporary mxArray with Improper DataYou cannot call mxDestroyArray on an mxArray whose data
Troubleshooting1-41For example,pr = mxCalloc(5*5, sizeof(double));... <load data into pr>plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);mxSetPr(plhs
1 Calling C and Fortran Programs from MATLAB1-42Additional InformationThe following sections describe how to find additional information and assistanc
Additional Information1-43<matlab>/binThe <matlab>/bin directory contains two files that are relevant for the MATLAB API.mex UNIX shell sc
1 Calling C and Fortran Programs from MATLAB1-44<matlab>/extern/includeThe <matlab>/extern/include directory contains the header files for
Additional Information1-45<matlab>\bin\win32The <matlab>\bin\win32 directory contains the mex.bat batch file that builds C and Fortran fil
1 Calling C and Fortran Programs from MATLAB1-46<matlab>\extern\includeThe <matlab>\extern\include directory contains the header files for
Additional Information1-47MEX Reference ExamplesThe mex subdirectory of /extern/examples directory contains MEX-file examples. It includes the example
iv ContentsCalling MATLAB From a Fortran Application . . . . . . . . . . . . 4-11Attaching to an Existing MATLAB Session . . . . . . . . . . . . .
1 Calling C and Fortran Programs from MATLAB1-48Technical SupportThe MathWorks provides additional Technical Support through its web site. A few of th
2Creating C Language MEX-FilesC MEX-Files . . . . . . . . . . . . . . . . . . . . 2-3The Components of a C
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
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
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
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
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
Examples of C MEX-Files2-7Examples of C MEX-FilesThe following sections include information and examples describing how to pass and manipulate the dif
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"/*
Examples of C MEX-Files2-9 if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows == 1 && ncols == 1) ) { mexErrMsgTxt("Inpu
vJava Methods That Affect MATLAB Commands . . . . . . . . . . . 5-26How MATLAB Handles Undefined Methods . . . . . . . . . . . . . . 5-27How MATLAB
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
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
2 Creating C Language MEX-Files2-12Note MATLAB automatically frees up memory allocated with the mx allocation routines (mxCalloc, mxMalloc, mxRealloc
Examples of C MEX-Files2-13 status = mxGetString(prhs[0], input_buf, buflen); if(status != 0) mexWarnMsgTxt("Not enough space. String is tr
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
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
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
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
2 Creating C Language MEX-Files2-18 /* Check proper input and output */ if(nrhs != 1) mexErrMsgTxt("One input required."); else if
Examples of C MEX-Files2-19 mexErrMsgTxt("Inconsistent data type in above field!"); } else if(!mxIsChar(tmp) &&a
vi ContentsExample – Communicating Through a Serial Port . . . . . . . 5-68Description of Serial Example . . . . . . . . . . . . . . . . . . . . . .
2 Creating C Language MEX-Files2-20 if(mxIsChar(tmp)) { mxSetCell(fout, jstruct, mxDuplicateArray(tmp)); } else { size_t s
Examples of C MEX-Files2-21Handling Complex DataComplex data from MATLAB is separated into real and imaginary parts. MATLAB’s API provides two functio
2 Creating C Language MEX-Files2-22Below is the gateway routine that calls this complex convolution./* The gateway routine. */void mexFunction( int nl
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
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
Examples of C MEX-Files2-25/* The gataway function */void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ){
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
Examples of C MEX-Files2-27#define IsNonZero(d) ((d) != 0.0)#endifvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray
2 Creating C Language MEX-Files2-28 /* Get the number of dimensions in the input argument. Allocate the space for the return argument */ number
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
vii7ActiveX and DDE SupportIntroducing MATLAB ActiveX Integration . . . . . . . . . . . . . . 7-3ActiveX Concepts and Terminology . . . . . . . .
2 Creating C Language MEX-Files2-30* *=============================================================*//* $Revision: 1.5 $ */#include <math.h> /*
Examples of C MEX-Files2-31 } /* Check data type of input argument. */ if(!(mxIsDouble(prhs[0]))) { mexErrMsgTxt("Input argument must be of
2 Creating C Language MEX-Files2-32 if(IsNonZero(pr[i]) || (cmplx && IsNonZero(pi[i]))) { /* Check to see if non-zero element will
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
2 Creating C Language MEX-Files2-34 * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. *==================================
Examples of C MEX-Files2-35 mxDestroyArray(lhs[0]); return;}Running this examplesincalldisplays the resultsNote It is possible to generate an obj
2 Creating C Language MEX-Files2-36MATLAB displays the following warning message.Warning: One or more output arguments not assigned during call to &ap
Advanced Topics2-37Advanced TopicsThese sections cover advanced features of MEX-files that you can use when your applications require sophisticated ME
2 Creating C Language MEX-Files2-38Memory ManagementMemory management within MEX-files is not unlike memory management for regular C or Fortran applic
Advanced Topics2-39creates persistent objects should register a function, using mexAtExit, which will dispose of the objects. (You can use a mexAtExit
Komentarze do niniejszej Instrukcji