Computation Visualization Programming External Interfaces Version 6
How to Contact The MathWorks: www.mathworks.com comp.soft-sys.matlab Web Newsgroup info@mathworks.com Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information 508-647-7000 Phone 508-647-7001 Fax The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 Mail support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.
Contents Calling C and Fortran Programs from MATLAB 1 Introducing MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 Using MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 The Distinction Between mx and mex Prefixes . . . . . . . . . . . . . 1-4 MATLAB Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The MATLAB Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Storage . . . . .
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-46 Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48 Creating C Language MEX-Files 2 C MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 The Components of a C MEX-File . . . . . . . . . . . . . . . . . . . . . . . . 2-3 Required Arguments to a MEX-File . . . . . . . . . . . . . . . . . . . . . .
Creating Fortran MEX-Files 3 Fortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 The Components of a Fortran MEX-File . . . . . . . . . . . . . . . . . . 3-3 The %val Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8 Examples of Fortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . 3-9 A First Example — Passing a Scalar . . . . . . . . . . . . . . . . . . . . 3-10 Passing Strings . . . . . . . . . . . . . . . . . . . .
Calling MATLAB From a Fortran Application . . . . . . . . . . . . 4-11 Attaching to an Existing MATLAB Session . . . . . . . . . . . . . . . 4-15 Compiling and Linking Engine Programs . . . . . . . . . . . . . . Masking Floating-Point Exceptions . . . . . . . . . . . . . . . . . . . . . Compiling and Linking on UNIX . . . . . . . . . . . . . . . . . . . . . . . Compiling and Linking on Windows . . . . . . . . . . . . . . . . . . . . .
Java Methods That Affect MATLAB Commands . . . . . . . . . . . 5-26 How MATLAB Handles Undefined Methods . . . . . . . . . . . . . . 5-27 How MATLAB Handles Java Exceptions . . . . . . . . . . . . . . . . . 5-28 Working with Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . How MATLAB Represents the Java Array . . . . . . . . . . . . . . . Creating an Array of Objects Within MATLAB . . . . . . . . . . . . Accessing Elements of a Java Array . . . . . . . . . . . . . . . . . . . . .
Example – Communicating Through a Serial Port . . . . . . . 5-68 Description of Serial Example . . . . . . . . . . . . . . . . . . . . . . . . . . 5-69 Running the serialexample Program . . . . . . . . . . . . . . . . . . . . 5-72 Example – Creating and Using a Phone Book . . . . . . . . . . . Description of Function phonebook . . . . . . . . . . . . . . . . . . . . . . Description of Function pb_lookup . . . . . . . . . . . . . . . . . . . . . . Description of Function pb_add . . . . . . . . . . . . . . .
ActiveX and DDE Support 7 Introducing MATLAB ActiveX Integration . . . . . . . . . . . . . . 7-3 ActiveX Concepts and Terminology . . . . . . . . . . . . . . . . . . . . . . 7-3 MATLAB ActiveX Support Overview . . . . . . . . . . . . . . . . . . . . . 7-4 MATLAB ActiveX Client Support . . . . . . . . . . . . . . . . . . . . . . . 7-6 Using ActiveX Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6 Writing Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Serial Port I/O 8 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is MATLAB’s Serial Port Interface? . . . . . . . . . . . . . . . . . Supported Serial Port Interface Standards . . . . . . . . . . . . . . . . Supported Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the Examples with Your Device . . . . . . . . . . . . . . . . . . . . 8-2 8-2 8-2 8-2 8-3 Overview of the Serial Port . . . . . . . . . . . . . . . . .
Events and Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example: Introduction to Events and Callbacks . . . . . . . . . . . Event Types and Callback Properties . . . . . . . . . . . . . . . . . . . . Storing Event Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and Executing Callback Functions . . . . . . . . . . . . . . Enabling Callback Functions After They Error . . . . . . . . . . . . Example: Using Events and Callbacks . . . . . . . . . . . .
x Contents
1 Calling C and Fortran Programs from MATLAB Introducing MEX-Files . . . . . . . . . . . . . . . 1-3 Using MEX-Files . . . . . . . . . . . . . . . . . . . 1-3 The Distinction Between mx and mex Prefixes . . . . . . . 1-4 MATLAB Data . . . The MATLAB Array . Data Storage . . . . Data Types in MATLAB Using Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building MEX-Files . . .
1 Calling C and Fortran Programs from MATLAB Although MATLAB® is a complete, self-contained environment for programming and manipulating data, it is often useful to interact with data and programs external to the MATLAB environment. MATLAB provides an interface to external programs written in the C and Fortran languages.
Introducing MEX-Files Introducing MEX-Files You can call your own C or Fortran subroutines from MATLAB as if they were built-in functions. MATLAB callable C and Fortran programs are referred to as MEX-files. MEX-files are dynamically linked subroutines that the MATLAB interpreter can automatically load and execute. MEX-files have several applications: • Large pre-existing C and Fortran programs can be called from MATLAB without having to be rewritten as M-files.
1 Calling C and Fortran Programs from MATLAB Table 1-1: MEX-File Extensions (Continued) Platform MEX-File Extension Solaris mexsol Windows dll You can call MEX-files exactly as you would call any M-function. For example, a MEX-file called conv2.mex on your disk in the MATLAB datafun toolbox directory performs a 2-D convolution of matrices. conv2.m only contains the help text documentation.
Introducing MEX-Files Note mex routines are only available in MEX-functions.
1 Calling C and Fortran Programs from MATLAB MATLAB Data Before you can program MEX-files, you must understand how MATLAB represents the many data types it supports. This section discusses the following topics: • “The MATLAB Array” • “Data Storage” • “Data Types in MATLAB” • “Using Data Types” The MATLAB Array The MATLAB language works with only a single object type: the MATLAB array.
MATLAB Data its dimensions are size(a) ans = 3 5 and its data is stored as h f p o l o u o r s o c e r h Data Types in MATLAB Complex Double-Precision Matrices The most common data type in MATLAB is the complex double-precision, nonsparse matrix. These matrices are of type double and have dimensions m-by-n, where m is the number of rows and n is the number of columns.
1 Calling C and Fortran Programs from MATLAB • nzmax is an integer that contains the length of ir, pr, and, if it exists, pi. It is the maximum possible number of nonzero elements in the sparse matrix. • ir points to an integer array of length nzmax containing the row indices of the corresponding elements in pr and pi. • jc points to an integer array of length N+1 that contains column index information.
MATLAB Data Logical Arrays Any noncomplex numeric or sparse array can be flagged as logical. The storage for a logical array is the same as the storage for a nonlogical array. Empty Arrays MATLAB arrays of any type can be empty. An empty mxArray is one with at least one dimension equal to zero. For example, a double-precision mxArray of type double, where m and n equal 0 and pr is NULL, is an empty array.
1 Calling C and Fortran Programs from MATLAB explore accepts any data type. Try using explore with these examples.
Building MEX-Files Building MEX-Files This section covers the following topics: • “Compiler Requirements” • “Testing Your Configuration on UNIX” • “Testing Your Configuration on Windows” • “Specifying an Options File” Compiler Requirements Your installed version of MATLAB contains all the tools you need to work with the API. MATLAB includes a C compiler for the PC called Lcc, but does not include a Fortran compiler. If you choose to use your own C compiler, it must be an ANSI C compiler.
1 Calling C and Fortran Programs from MATLAB Testing Your Configuration on UNIX The quickest way to check if your system is set up properly to create MEX-files is by trying the actual process. There is C source code for an example, yprime.c, and its Fortran counterpart, yprimef.F and yprimefg.F, included in the /extern/examples/mex directory, where represents the top-level directory where MATLAB is installed on your system. To compile and link the example source files, yprime.
Building MEX-Files Options files control which compiler to use, the compiler and link command options, and the runtime libraries to link against. To override the default options file, use the 'mex -f' command (see 'mex -help' for more information). The options files available for mex are: 1: /bin/gccopts.sh : Template Options file for building gcc MEXfiles 2: /bin/mexopts.
1 Calling C and Fortran Programs from MATLAB Testing Your Configuration on Windows Before you can create MEX-files on the Windows platform, you must configure the default options file, mexopts.bat, for your compiler. The switch, setup, provides an easy way for you to configure the default options file. To configure or change the options file at anytime, run mex -setup from either the MATLAB or DOS command prompt.
Building MEX-Files to select one when you compile MEX-files. To select a compiler or change to existing default compiler, use mex –setup. This example shows the process of setting your default compiler to the Microsoft Visual C++ Version 6.0 compiler. mex -setup Please choose your compiler for building external interface (MEX) files. Would you like mex to locate installed compilers [y]/n? n Select a compiler: [1] Borland C++Builder version 5.0 [2] Borland C++Builder version 4.
1 Calling C and Fortran Programs from MATLAB The default options file: "C:\WINNT\Profiles\username\ApplicationData\MathWorks\MATLAB\R12 \mexopts.bat" is being updated from ... If the specified compiler cannot be located, you are given the message: The default location for compiler-name is directory-name, but that directory does not exist on this machine. Use directory-name anyway [y]/n? Using the setup option sets your default compiler so that the new compiler is used every time you use the mex script.
Building MEX-Files In addition to running the mex script from the MATLAB prompt, you can also run the script from the system prompt. Specifying an Options File You can use the -f option to specify an options file on either UNIX or Windows. To use the -f option, at the MATLAB prompt type mex filename -f and specify the name of the options file along with its pathname. The Options Files table, below, contains a list of the options files included with MATLAB.
1 Calling C and Fortran Programs from MATLAB Table 1-2: Options Files (Continued) Platform 1-18 Compiler Options File Microsoft C/C++, Version 5.0 msvc50opts.bat Microsoft C/C++, Version 6.0 msvc60opts.bat Watcom C/C++, Version 10.6 watcopts.bat Watcom C/C++, Version 11 wat11copts.bat DIGITAL Visual Fortran, Version 5.0 df50opts.bat Compaq Visual Fortran, Version 6.1 df60opts.bat Borland C, Version 5.0 & 5.2, for Engine and MAT stand-alone programs bccengmatopts.bat Borland C, Version 5.
Building MEX-Files Table 1-2: Options Files (Continued) Platform UNIX Compiler Options File Watcom C for Engine and MAT stand-alone programs, Version 10.6 watengmatopts.bat Watcom C for Engine and MAT stand-alone programs, Version 11 wat11engmatopts.bat DIGITAL Visual Fortran for MAT stand-alone programs, Version 5.0 df50engmatopts.bat Compaq Visual Fortran for MAT stand-alone programs, Version 6.1 df60engmatopts.bat System ANSI Compiler mexopts.sh GCC gccopts.
1 Calling C and Fortran Programs from MATLAB Custom Building MEX-Files This section discusses in detail the process that the MEX-file build script uses. It covers the following topics: • “Who Should Read This Chapter” • “MEX Script Switches” • “Default Options File on UNIX” • “Default Options File on Windows” • “Custom Building on UNIX” • “Custom Building on Windows” Who Should Read This Chapter In general, the defaults that come with MATLAB should be sufficient for building most MEX-files.
Custom Building MEX-Files series of variable assignments; each variable represents a different logical piece of the build process. Table 1-3: MEX Script Switches Switch Function @ Include the contents of the text file as command line arguments to the mex script. -argcheck Perform argument checking on MATLAB API functions (C functions only). -c Compile only; do not link. -D[#] Define C preprocessor macro [as having value ].
1 Calling C and Fortran Programs from MATLAB Table 1-3: MEX Script Switches (Continued) Switch Function # Override options file setting for variable . This option is equivalent to #, which temporarily sets the environment variable to for the duration of the call to mex. can refer to another environment variable by prepending the name of the variable with a $, e.g., COMPFLAGS#"$COMPFLAGS -myswitch".
Custom Building MEX-Files mex uses the first occurrence of the options file it finds. If no options file is found, mex displays an error message. You can directly specify the name of the options file using the -f switch. For specific information on the default settings for the MATLAB supported compilers, you can examine the options file in /bin/mexopts.sh, or you can invoke the mex script in verbose mode (-v).
1 Calling C and Fortran Programs from MATLAB in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB. Under Windows NT and Windows 95/98 with user profiles enabled, your user profile directory is %windir%\Profiles\username. Under Windows 95/98 with user profiles disabled, your user profile directory is %windir%. Under Windows 95/98, you can determine whether or not user profiles are enabled by using the Passwords control panel.
Custom Building MEX-Files Build Options For customizing the build process, you should modify the options file. The options file contains the compiler-specific flags corresponding to the general steps outlined above. The options file consists of a series of variable assignments; each variable represents a different logical piece of the build process. The options files provided with MATLAB are located in /bin.
1 Calling C and Fortran Programs from MATLAB Variable C Compiler Fortran Compiler Linker Debugging CDEBUGFLAGS FDEBUGFLAGS LDDEBUGFLAGS Additional libraries CLIBS FLIBS ---- For specifics on the default settings for these variables, you can: • Examine the options file in /bin/mexopts.
Custom Building MEX-Files and the DEBUGFLAGS are used if you set the -g switch on the mex command line. Prelink Stage The prelink stage dynamically creates import libraries to import the required function into the MEX, MAT, or engine file. All MEX-files link against MATLAB only. MAT stand-alone programs link against libmx.dll (array access library) and libmat.dll (MAT-functions). Engine stand-alone programs link against libmx.dll (array access library) and libeng.dll for engine functions.
1 Calling C and Fortran Programs from MATLAB for -output to work. If this environment is not set, the compiler default is to use the name of the first program in the command line. Even if this is set, it can be overridden by specifying the mex -output switch. Linking DLLs to MEX-Files To link a DLL to a MEX-file, list the DLL’s .lib file on the command line. Versioning MEX-Files The mex script can build your MEX-file with a resource file that contains versioning and other essential information.
Custom Building MEX-Files 3 Add the .DEF file to the project. 4 Locate the .LIB files for the compiler version you are using under matlabroot\extern\lib\win32\microsoft. For example, for version 6.0, these files are in the msvc60 subdirectory. 5 From this directory, add libmx.lib, libmex.lib, and libmat.lib to the library modules in the LINK settings option. 6 Add the MATLAB include directory, MATLAB\EXTERN\INCLUDE to the include path in the Settings C/C++ Preprocessor option.
1 Calling C and Fortran Programs from MATLAB mex -setup Follow the menus and choose either Microsoft Visual C/C++ 5.0 or 6.0. This configures mex to use the selected Microsoft compiler and also installs the necessary add-in files in your Microsoft Visual C/C++ directories. 2 To configure the MATLAB add-in for Visual Studio to work with Microsoft Visual C/C++: a Select Tools -> Customize from the MSVC menu. b Click on the Add-ins and Macro Files tab.
Custom Building MEX-Files For additional information on the MATLAB add-in for Visual Studio: • See the MATLABAddin.hlp file in the \bin\win32 directory, or • Click on the Help icon in the MATLAB add-in for Visual Studio toolbar.
1 Calling C and Fortran Programs from MATLAB Troubleshooting This section explains how to troubleshoot some of the more common problems you may encounter. It addresses the following topics: • “Configuration Issues” • “Understanding MEX-File Problems” • “Compiler and Platform-Specific Issues” • “Memory Management Compatibility Issues” Configuration Issues This section focuses on some common problems that might occur when creating MEX-files.
Troubleshooting mex.bat: internal error in sub get_compiler_info(): don't recognize then you need to disable your antivirus software temporarily and reenter the command. After you have successfully run the mex operation, you can re-enable your antivirus software. Alternatively, you can open a separate MS-DOS window and enter the mex command from that window. General Configuration Problem Make sure you followed the configuration steps for your platform described in this chapter.
1 Calling C and Fortran Programs from MATLAB Start Can you compile and run timestwo.c or timestwo.f? no 1 Are you using a supported compiler ? Acquire a supported compiler. See “Supported Compilers” for details. no Stop yes Double check your configuration.
Troubleshooting MathWorks Technical Support Web site at http://www.mathworks.com/ support. Problem 1 - Compiling a MathWorks Program Fails The most common configuration problem in creating C MEX-files on UNIX involves using a non-ANSI C compiler, or failing to pass to the compiler a flag that tells it to compile ANSI C code.
1 Calling C and Fortran Programs from MATLAB symbols or unresolved references. Be sure to link against the library that defines the function in question. On Windows, MATLAB will fail to load MEX-files if it cannot find all DLLs referenced by the MEX-file; the DLLs must be on the path or in the same directory as the MEX-file. This is also true for third party DLLs.
Troubleshooting • Run MATLAB within a debugging environment. This process is already described in the chapters on creating C and Fortran MEX-files, respectively. Problem 5 - Program Generates Incorrect Results If your program generates the wrong answer(s), there are several possible causes. First, there could be an error in the computational logic. Second, the program could be reading from an uninitialized section of memory.
1 Calling C and Fortran Programs from MATLAB We highly recommend that you fix code in your MEX-files that produces any of the warnings discussed in the following sections. For additional information, see “Memory Management” on page 2-38 in Creating C Language MEX-Files. Note Currently, the following warnings are enabled by default for backwards compatibility reasons. In future releases of MATLAB, the warnings will be disabled by default.
Troubleshooting Solution Call mxDestroyArray instead. mxDestroyArray(temp); /* CORRECT */ Incorrectly Constructing a Cell or Structure mxArray You cannot call mxSetCell or mxSetField variants with prhs[] as the member array. Warning Warning: You are attempting to use an array from another scope (most likely an input argument) as a member of a cell array or structure. You need to make a copy of the array first.
1 Calling C and Fortran Programs from MATLAB Creating a Temporary mxArray with Improper Data You cannot call mxDestroyArray on an mxArray whose data was not allocated by an API routine. Warning Warning: You have attempted to point the data of an array to a block of memory not allocated through the MATLAB API. MATLAB will attempt to fix the problem and continue, but this will result in memory faults in future releases.
Troubleshooting For example, pr = mxCalloc(5*5, sizeof(double)); ... plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL); mxSetPr(plhs[0], pr); /* INCORRECT */ will now leak 5*5*8 bytes of memory, where 8 bytes is the size of a double. You can avoid that memory leak by changing the code plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL); pr = mxGetPr(plhs[0]); ... or alternatively pr = mxCalloc(5*5, sizeof(double)); ...
1 Calling C and Fortran Programs from MATLAB Additional Information The following sections describe how to find additional information and assistance in building your applications. It covers the following topics: • “Files and Directories - UNIX Systems” • “Files and Directories - Windows Systems” • “Examples” • “Technical Support” Files and Directories - UNIX Systems This section describes the directory organization and purpose of the files associated with the MATLAB API on UNIX systems.
Additional Information /bin The /bin directory contains two files that are relevant for the MATLAB API. mex UNIX shell script that creates MEX-files from C or Fortran MEX-file source code. See “Introducing MEX-Files” on page 1-3 for more details on mex. matlab UNIX shell script that initializes your environment and then invokes the MATLAB interpreter. This directory also contains the preconfigured options files that the mex script uses with particular compilers.
1 Calling C and Fortran Programs from MATLAB /extern/include The /extern/include directory contains the header files for developing C and C++ applications that interface with MATLAB. The relevant header files for the MATLAB API are: engine.h Header file for MATLAB engine programs. Contains function prototypes for engine routines. mat.h Header file for programs accessing MAT-files. Contains function prototypes for mat routines. matrix.
Additional Information bin win32 mexopts extern include src examples eng_mat mex mx refbook \bin\win32 The \bin\win32 directory contains the mex.bat batch file that builds C and Fortran files into MEX-files. Also, this directory contains mex.pl, which is a Perl script used by mex.bat. \bin\win32\mexopts The \bin\win32\mexopts directory contains the preconfigured options files that the mex script uses with particular compilers.
1 Calling C and Fortran Programs from MATLAB \extern\include The \extern\include directory contains the header files for developing C and C++ applications that interface with MATLAB. The relevant header files for the MATLAB API (MEX-files, engine, and MAT-files) are: engine.h Header file for MATLAB engine programs. Contains function prototypes for engine routines. mat.h Header file for programs accessing MAT-files. Contains function prototypes for mat routines. matrix.
Additional Information MEX Reference Examples The mex subdirectory of /extern/examples directory contains MEX-file examples. It includes the examples described in the online External Interfaces/ API reference pages for MEX interface functions (the functions beginning with the mex prefix). You can find the most recent versions of these examples using the anonymous FTP server location ftp://ftp.mathworks.
1 Calling C and Fortran Programs from MATLAB Technical Support The MathWorks provides additional Technical Support through its web site. A few of the services provided are as follows: • FAQ (Frequently Asked Questions) This is a list of the most frequently asked questions received by our Technical Support staff, along with answers from the solutions database. http://www.mathworks.com/support/index.
2 Creating C Language MEX-Files C MEX-Files . . . . . . . . . . . . . . . . . . . . 2-3 The Components of a C MEX-File . . . . . . . . . . . . 2-3 Required Arguments to a MEX-File . . . . . . . . . . . 2-5 Examples of C MEX-Files . . . . . . . . . A First Example — Passing a Scalar . . . . . . Passing Strings . . . . . . . . . . . . . . Passing Two or More Inputs or Outputs . . . . Passing Structures and Cell Arrays . . . . . . Handling Complex Data . . . . . . . . . . . Handling 8-,16-, and 32-Bit Data . .
2 Creating C Language MEX-Files This chapter describes how to write MEX-files in the C programming language. It discusses the MEX-file itself, how these C language files interact with MATLAB, how to pass and manipulate arguments of different data types, how to debug your MEX-file programs, and several other, more advanced topics.
C MEX-Files C MEX-Files C MEX-files are built by using the mex script to compile your C source code with additional calls to API routines. The Components of a C MEX-File The source code for a MEX-file consists of two distinct parts: • A computational routine that contains the code for performing the computations that you want implemented in the MEX-file. Computations can be numerical computations as well as inputting and outputting data.
2 Creating C Language MEX-Files MATLAB A call to MEX-file func: [C,D]=func(A,B) tells MATLAB to pass variables A and B to your MEX-file. C and D are left unassigned. INPUTS const mxArray *B B = prhs[1] const mxArray *A A = prhs[0] func.c void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) In the gateway routine: • Use the mxCreate functions to create the MATLAB arrays for your output arguments. Set plhs[0], [1], … to the pointers to the newly created MATLAB arrays.
C MEX-Files Required Arguments to a MEX-File The two components of the MEX-file may be separate or combined. In either case, the files must contain the #include "mex.h" header so that the entry point and interface routines are declared properly. The name of the gateway routine must always be mexFunction and must contain these parameters. void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* more C code ...
2 Creating C Language MEX-Files For example, if you invoke a MEX-file from the MATLAB workspace with the command x = fun(y,z); the MATLAB interpreter calls mexFunction with the arguments nlhs = 1 nrhs = 2 plhs prhs • • • Ø Y Z plhs 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 pointer to an mxArray named Y and the second element is a pointer to an mxArray named Z.
Examples of C MEX-Files Examples of C MEX-Files The following sections include information and examples describing how to pass and manipulate the different data types when working with MEX-files.
2 Creating C Language MEX-Files { y[0] = 2.0*x[0]; return; } Below is the same function written in the MEX-file format. #include "mex.h" /* * timestwo.c - example found in API guide * * Computational function that takes a scalar and doubles it. * * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. */ /* $Revision: 1.8 $ */ void timestwo(double y[], double x[]) { y[0] = 2.
Examples of C MEX-Files if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows == 1 && ncols == 1) ) { mexErrMsgTxt("Input must be a noncomplex scalar double."); } /* Create matrix for the return argument. */ plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL); /* Assign pointers to each input and output. */ x = mxGetPr(prhs[0]); y = mxGetPr(plhs[0]); /* Call the timestwo subroutine. */ timestwo(y,x); } In C, function argument checking is done at compile time.
2 Creating C Language MEX-Files In the above example, scalars are viewed as 1-by-1 matrices. Alternatively, you can use a special API function called mxGetScalar that returns the values of scalars instead of pointers to copies of scalar variables. This is the alternative code (error checking has been omitted for brevity). #include "mex.h" /* * timestwoalt.c - example found in API guide * * Use mxGetScalar to return the values of scalars instead of * pointers to copies of scalar variables.
Examples of C MEX-Files /* Call the timestwo_alt subroutine. */ timestwo_alt(y,x); } This example passes the input scalar x by value into the timestwo_alt subroutine, but passes the output scalar y by reference. Passing Strings Any MATLAB data type can be passed to and from MEX-files. For example, this C code accepts a string and returns the characters in reverse order. /* $Revision: 1.10 $ */ /*============================================================= * revord.
2 Creating C Language MEX-Files Note MATLAB automatically frees up memory allocated with the mx allocation routines (mxCalloc, mxMalloc, mxRealloc) upon exiting your MEX-file. If you don’t want this to happen, use the API function mexMakeMemoryPersistent. Below is the gateway routine that calls the C computational routine revord. void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { char *input_buf, *output_buf; int buflen,status; /* Check for proper number of arguments.
Examples of C MEX-Files status = mxGetString(prhs[0], input_buf, buflen); if(status != 0) mexWarnMsgTxt("Not enough space. String is truncated."); /* Call the C subroutine. */ revord(input_buf, buflen, output_buf); /* Set C-style string output_buf to MATLAB mexFunction output*/ plhs[0] = mxCreateString(output_buf); return; } The gateway routine allocates memory for the input and output strings. Since these are C strings, they need to be one greater than the number of elements in the MATLAB string.
2 Creating C Language MEX-Files and so on. Likewise, prhs[0] contains a pointer to the first right-hand side argument, prhs[1] points to the second, and so on. This example, xtimesy, multiplies an input scalar by an input scalar or matrix and outputs a matrix. For example, using xtimesy with two scalars gives x = 7; y = 7; z = xtimesy(x,y) z = 49 Using xtimesy with a scalar and a matrix gives x = 9; y = ones(3); z = xtimesy(x,y) z = 9 9 9 9 9 9 9 9 9 This is the corresponding MEX-file C code.
Examples of C MEX-Files void 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; j < m; j++) { *(z+count) = x * *(y+count); count++; } } } /* The gateway routine */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *y,*z; double x; int status,mrows,ncols; /* Check for proper number of arguments. */ /* NOTE: You do not need an else statement when using mexErrMsgTxt within an if statement.
2 Creating C Language MEX-Files /* Create a pointer to the input matrix y. */ y = mxGetPr(prhs[1]); /* Get the dimensions of the matrix input y. */ mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); /* Set the output pointer to the output matrix. */ plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL); /* Create a C pointer to a copy of the output matrix. */ z = mxGetPr(plhs[0]); /* Call the C subroutine.
Examples of C MEX-Files This example takes an m-by-n structure matrix as input and returns a new 1-by-1 structure that contains these fields: • String input generates an m-by-n cell array • Numeric input (noncomplex, scalar values) generates an m-by-n vector of numbers with the same class ID as the input, for example int, double, and so on. * ============================================================= * phonebook.
2 Creating C Language MEX-Files /* Check proper input and output */ if(nrhs != 1) mexErrMsgTxt("One input required."); else if(nlhs > 1) mexErrMsgTxt("Too many output arguments."); else if(!mxIsStruct(prhs[0])) mexErrMsgTxt("Input must be a structure.
Examples of C MEX-Files mexErrMsgTxt("Inconsistent data type in above field!"); } else if(!mxIsChar(tmp) && ((mxIsComplex(tmp) || mxGetNumberOfElements(tmp) != 1))) { mexPrintf("%s%d\t%s%d\n", "FIELD:", ifield+1, "STRUCT INDEX :", jstruct+1); mexErrMsgTxt("Numeric data in above field " "must be scalar and noncomplex!"); } } } } /* Allocate memory for storing pointers */ fnames = mxCalloc(nfields, sizeof(*fnames)); /* Get field name pointers */ for(ifield = 0; ifield < nfields; ifield++) { fnames[ifield] =
2 Creating C Language MEX-Files if(mxIsChar(tmp)) { mxSetCell(fout, jstruct, mxDuplicateArray(tmp)); } else { size_t sizebuf; sizebuf = mxGetElementSize(tmp); memcpy(pdata, mxGetData(tmp), sizebuf); pdata += sizebuf; } } /* Set each field in output structure */ mxSetFieldByNumber(plhs[0], 0, ifield, fout); } mxFree(classIDflags); return; } To see how this program works, enter this structure. friends(1).name = 'Jordan Robert'; friends(1).phone = 3386; friends(2).name = 'Mary Smith'; friends(2).
Examples of C MEX-Files Handling Complex Data Complex data from MATLAB is separated into real and imaginary parts. MATLAB’s API provides two functions, mxGetPr and mxGetPi, that return pointers (of type double *) to the real and imaginary parts of your data. This example takes two complex row vectors and convolves them. /* $Revision: 1.8 $ */ /*========================================================= * convec.
2 Creating C Language MEX-Files Below is the gateway routine that calls this complex convolution. /* The gateway routine. */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *xr, *xi, *yr, *yi, *zr, *zi; int rows, cols, nx, ny; /* Check for the proper number of arguments. */ if(nrhs != 2) mexErrMsgTxt("Two inputs required."); if(nlhs > 1) mexErrMsgTxt("Too many output arguments."); /* Check that both inputs are row vectors.
Examples of C MEX-Files /* Call the C subroutine. */ convec(xr, xi, nx, yr, yi, ny, zr, zi); return; } Entering these numbers at the MATLAB prompt x = [3.000 - 1.000i, 4.000 + 2.000i, 7.000 - 3.000i]; y = [8.000 - 6.000i, 12.000 + 16.000i, 40.000 - 42.000i]; and invoking the new MEX-file z = convec(x,y) results in z = 1.0e+02 * Columns 1 through 4 0.1800 - 0.2600i 0.9600 + 0.2800i 1.3200 - 1.4400i 3.7600 - 0.1200i Column 5 1.5400 - 4.
2 Creating C Language MEX-Files arithmetic on data of 8-, 16- or 32-bit precision in MEX-files and return the result to MATLAB, which will recognize the correct data class. Although from within MATLAB it is not currently possible to perform arithmetic or to call MATLAB functions that perform data manipulation on data of 8-, 16-, or 32-bit precision, you can display the data at the MATLAB prompt and save it in a MAT-file.
Examples of C MEX-Files /* The gataway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { const int dims[] = {2,2}; unsigned char *start_of_pr; unsigned short data[] = {1,2,3,4}; int bytes_to_copy; /* Call the computational subroutine. */ dbl_elem(data); /* Create a 2-by-2 array of unsigned 16-bit integers. */ plhs[0] = mxCreateNumericArray(NDIMS,dims, mxUINT16_CLASS,mxREAL); /* Populate the real part of the created array.
2 Creating C Language MEX-Files data types in MATLAB, arrays can be passed into and out of MEX-files written in C. You can manipulate multidimensional numerical arrays by using mxGetData and mxGetImagData to return pointers to the real and imaginary parts of the data stored in the original multidimensional array. This example takes an N-dimensional array of doubles and returns the indices for the nonzero elements in the array. /*============================================================= * findnz.
Examples of C MEX-Files #define IsNonZero(d) ((d) != 0.0) #endif void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Declare variables. */ int elements, j, number_of_dims, cmplx; int nnz = 0, count = 0; double *pr, *pi, *pind; const int *dim_array; /* Check for proper number of input and output arguments. */ if(nrhs != 1) { mexErrMsgTxt("One input argument required."); } if(nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } /* Check data type of input argument.
2 Creating C Language MEX-Files /* Get the number of dimensions in the input argument. Allocate the space for the return argument */ number_of_dims = mxGetNumberOfDimensions(prhs[0]); plhs[0] = mxCreateDoubleMatrix(nnz, number_of_dims, mxREAL); pind = mxGetPr(plhs[0]); /* Get the number of dimensions in the input argument. */ dim_array = mxGetDimensions(prhs[0]); /* Fill in the indices to return to MATLAB. This loops through * the elements and checks for non-zero values.
Examples of C MEX-Files This example determines the position of all nonzero elements in the matrix. Running the MEX-file on this matrix produces nz = findnz(matrix) nz = 1 1 4 1 5 1 2 2 3 2 5 2 1 3 2 3 3 3 4 3 5 3 2 4 3 4 4 4 Handling Sparse Arrays The MATLAB API provides a set of functions that allow you to create and manipulate sparse arrays from within your MEX-files. These API routines access and manipulate ir and jc, two of the parameters associated with sparse arrays.
2 Creating C Language MEX-Files * *=============================================================*/ /* $Revision: 1.5 $ */ #include /* Needed for the ceil() prototype. */ #include "mex.h" /* If you are using a compiler that equates NaN to be zero, you * must compile this example using the flag -DNAN_EQUALS_ZERO. * For example: * * mex -DNAN_EQUALS_ZERO fulltosparse.c * * This will correctly define the IsNonZero macro for your C * compiler.
Examples of C MEX-Files } /* Check data type of input argument. */ if(!(mxIsDouble(prhs[0]))) { mexErrMsgTxt("Input argument must be of type double."); } if(mxGetNumberOfDimensions(prhs[0]) != 2) { mexErrMsgTxt("Input argument must be two dimensional\n"); } /* Get the size and pointers to input data. */ m = mxGetM(prhs[0]); n = mxGetN(prhs[0]); pr = mxGetPr(prhs[0]); pi = mxGetPi(prhs[0]); cmplx = (pi == NULL ? 0 : 1); /* Allocate space for sparse matrix. * NOTE: Assume at most 20% of the data is sparse.
2 Creating C Language MEX-Files if(IsNonZero(pr[i]) || (cmplx && IsNonZero(pi[i]))) { /* Check to see if non-zero element will fit in * allocated output array. If not, increase * percent_sparse by 10%, recalculate nzmax, and augment * the sparse array. */ if(k >= nzmax) { int oldnzmax = nzmax; percent_sparse += 0.1; nzmax = (int)ceil((double)m*(double)n*percent_sparse); /* Make sure nzmax increases atleast by 1.
Examples of C MEX-Files At the MATLAB prompt, entering full = eye(5) full = 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 creates a full, 5-by-5 identity matrix. Using fulltosparse on the full matrix produces the corresponding sparse matrix. spar = fulltosparse(full) spar = (1,1) 1 (2,2) 1 (3,3) 1 (4,4) 1 (5,5) 1 Calling Functions from C MEX-Files It is possible to call MATLAB functions, operators, M-files, and other MEX-files from within your C source code by using the API function mexCallMATLAB.
2 Creating C Language MEX-Files * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. *============================================================*/ #include "mex.h" #define MAX 1000 /* Subroutine for filling up data */ void fill( double *pr, int *pm, int *pn, int max ) { int i; /* You can fill up to max elements, so (*pr) <= max. */ *pm = max/2; *pn = 1; for(i = 0; i < (*pm); i++) pr[i] = i*(4*3.
Examples of C MEX-Files mxDestroyArray(lhs[0]); return; } Running this example sincall displays the results Note It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLAB. See the example below. The following example creates an M-file that returns two variables but only assigns one of them a value.
2 Creating C Language MEX-Files MATLAB displays the following warning message. Warning: One or more output arguments not assigned during call to 'foo'. If you then call foo using mexCallMATLAB, the unassigned output variable will now be of type mxUNKNOWN_CLASS.
Advanced Topics Advanced Topics These sections cover advanced features of MEX-files that you can use when your applications require sophisticated MEX-files. Help Files • Because the MATLAB interpreter chooses the MEX-file when both an M-file and a MEX-file with the same name are encountered in the same directory, it is possible to use M-files for documenting the behavior of your MEX-files.
2 Creating C Language MEX-Files Memory Management Memory management within MEX-files is not unlike memory management for regular C or Fortran applications. However, there are special considerations because the MEX-file must exist within the context of a larger application, i.e., MATLAB itself.
Advanced Topics creates persistent objects should register a function, using mexAtExit, which will dispose of the objects. (You can use a mexAtExit function to dispose of other resources as well; for example, you can use mexAtExit to close an open file.) For example, here is a simple MEX-file that creates a persistent array and properly disposes of it. #include "mex.
2 Creating C Language MEX-Files Hybrid Arrays Functions such as mxSetPr, mxSetData, and mxSetCell allow the direct placement of memory pieces into an mxArray. mxDestroyArray will destroy these pieces along with the entire array. Because of this, it is possible to create an array that cannot be destroyed, i.e., an array on which it is not safe to call mxDestroyArray. Such an array is called a hybrid array, because it contains both destroyable and nondestroyable components.
Advanced Topics This section explains how to write and build MEX-files that call LAPACK and BLAS functions. It provides information on: • Specifying the Function Name • Passing Arguments to Fortran from C • Handling Complex Numbers • Building the MEX-File It also provides a symmetric indefinite factorization example that uses functions from LAPACK.
2 Creating C Language MEX-Files B m p n = = = = mxGetPr(prhs[1]); mxGetM(prhs[0]); mxGetN(prhs[0]); mxGetN(prhs[1]); if(p != mxGetM( prhs[1])) { mexErrMsgTxt("Inner dimensions of matrix multiply do not match"); } plhs[0] = mxCreateDoubleMatrix( m, n, mxREAL ); C = mxGetPr( plhs[0] ); /* Pass all arguments to Fortran by reference */ dgemm (chn, chn, &m, &n, &p, &one, A, &m, B, &p, &zero, C, &m); } Handling Complex Numbers MATLAB stores complex numbers differently than Fortran.
Advanced Topics format, which takes twice the space. See the allocation of zout in the example that follows. 2 Once the variable is returned to MATLAB, convert its storage so that it is compatible with MATLAB. Use the fort2mat function for this. Example – Passing Complex Variables. The example below shows how to call an LAPACK function from MATLAB, passing complex prhs[0] as input and receiving complex plhs[0] as output.
2 Creating C Language MEX-Files Preserving Input Values from Modification Many LAPACK and BLAS functions modify the values of arguments passed in to them. It is advisable to make a copy of arguments that can be modified prior to passing them to the function. For complex inputs, this point is moot since the mat2fort version of the input is a new piece of memory, but for real data this is not the case. The following example calls an LAPACK function that modifies the first input argument.
Advanced Topics mex myCmexFile.c /extern/lib/win32/microsoft/msvc60/ libmwlapack.lib For IBM_RS, use the following syntax. mex myCmexFile.c -L/bin/ibm_rs -lmwlapack On all other platforms, you can build your MEX-file as you would any other C MEX-file. For example, mex myCmexFile.c MEX-Files That Perform Complex Number Conversion. MATLAB supplies the files fort.c and fort.h, which provide routines for conversion between MATLAB and FORTRAN complex data structures.
2 Creating C Language MEX-Files mex myCmexFile.c /extern/examples/refbook/fort.c -I/extern/examples/refbook Example – Symmetric Indefinite Factorization Using LAPACK You will find an example C MEX-file that calls two LAPACK functions in the directory /extern/examples/refbook, where stands for the MATLAB root directory. There are two versions of this file: • utdu_slv.c – calls functions zhesvx and dsysvx, and thus is compatible with the PC, HP, and IBM platforms.
Debugging C Language MEX-Files Debugging C Language MEX-Files On most platforms, it is now possible to debug MEX-files while they are running within MATLAB. Complete source code debugging, including setting breakpoints, examining variables, and stepping through the source code line-by-line, is now available. Note The section entitled, “Troubleshooting” on page 1-32, provides additional information on isolating problems with MEX-files.
2 Creating C Language MEX-Files Note The tick marks used are back ticks (‘), not single quotes ('). You may need to tell the debugger where the MEX-file was loaded or the name of the MEX-file, in which case MATLAB will display the appropriate command for you to use. At this point, you are ready to start debugging. You can list the source code for your MEX-file and set breakpoints in it. It is often convenient to set one at mexFunction so that you stop at the beginning of the gateway routine.
Debugging C Language MEX-Files edit boxes. In the edit box labeled Executable for debug session, enter the full path to where MATLAB resides. All other edit boxes should be empty. 3 Open the source files and set a break point on the desired line of code by right-clicking with your mouse on the line of code. 4 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 Microsoft debugging environment.
2 Creating C Language MEX-Files 5 When MATLAB starts, in the command window change directories to where your MEX-file resides and run your MEX-file. If a message similar to the following appears, ignore the message and click OK. LDR: Automatic DLL Relocation in matlab.exe LDR: DLL filename.dll base relocated due to collision with matlab.exe 6 Open the file you want to debug and set breakpoints in the source code.
3 Creating Fortran MEX-Files Fortran MEX-Files . . . . . . . . . . . . . . . . . 3-3 The Components of a Fortran MEX-File . . . . . . . . . 3-3 The %val Construct . . . . . . . . . . . . . . . . . . 3-8 Examples of Fortran MEX-Files . . . A First Example — Passing a Scalar . . . Passing Strings . . . . . . . . . . . Passing Arrays of Strings . . . . . . . Passing Matrices . . . . . . . . . . . Passing Two or More Inputs or Outputs . Handling Complex Data . . . . . . . . Dynamically Allocating Memory . . . .
3 Creating Fortran MEX-Files This chapter describes how to write MEX-files in the Fortran programming language. It discusses the MEX-file itself, how these Fortran language files interact with MATLAB, how to pass and manipulate arguments of different data types, how to debug your MEX-file programs, and several other, more advanced topics.
Fortran MEX-Files Fortran MEX-Files Fortran MEX-files are built by using the mex script to compile your Fortran source code with additional calls to API routines. MEX-files in Fortran can only create double-precision data and strings, unlike their C counterparts, which can create any data type supported by MATLAB. You can treat Fortran MEX-files, once compiled, exactly like M-functions. The Components of a Fortran MEX-File This section discusses the specific elements needed in a Fortran MEX-file.
3 Creating Fortran MEX-Files MATLAB A call to MEX-file func: [C,D]=func(A,B) tells MATLAB to pass variables A and B to your MEX-file. C and D are left unassigned. INPUTS integer B B = prhs(2) integer A A = prhs(1) func.f subroutine mexFunction( nlhs, plhs, nrhs, prhs) integer plhs(*), prhs(*), nlhs, nrhs In the gateway routine: • Use the mxCreate functions to create the MATLAB arrays for your output arguments. Set plhs(1), (2), … to the pointers to the newly created MATLAB arrays.
Fortran MEX-Files The Pointer Concept The MATLAB API works with a unique data type, the mxArray. Because there is no way to create a new data type in Fortran, MATLAB passes a special identifier, called a pointer, to a Fortran program. You can get information about an mxArray by passing this pointer to various API functions called Access Routines. These access routines allow you to get a native Fortran data type containing exactly the information you want, i.e.
3 Creating Fortran MEX-Files The Gateway Routine The entry point to the gateway subroutine must be named mexFunction and must contain these parameters. subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer plhs(*), prhs(*) integer nlhs, nrhs Note Fortran is case-insensitive. This document uses mixed-case function names for ease of reading. In a Fortran MEX-file, the parameters nlhs and nrhs contain the number of left- and right-hand arguments with which the MEX-file is invoked.
Fortran MEX-Files plhs 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 pointer to an mxArray named Y and the second element is a pointer to an mxArray named Z. The parameter plhs points at nothing because the output x is not created until the subroutine executes. It is the responsibility of the gateway routine to create an output array and to set a pointer to that array in plhs(1).
3 Creating Fortran MEX-Files When a MEX-file completes its task, it returns control to MATLAB. Any MATLAB arrays that are created by the MEX-file that are not returned to MATLAB through the left-hand side arguments are automatically destroyed. The %val Construct The %val construct is supported by most, but not all, Fortran compilers. DIGITAL Visual Fortran does support the construct. %val causes the value of the variable, rather than the address of the variable, to be passed to the subroutine.
Examples of Fortran MEX-Files Examples of Fortran MEX-Files The following sections include information and examples describing how to pass and manipulate the different data types when working with MEX-files.
3 Creating Fortran MEX-Files A First Example — Passing a Scalar Let’s look at a simple example of Fortran code and its MEX-file equivalent. Here is a Fortran computational routine that takes a scalar and doubles it. subroutine timestwo(y, x) real*8 x, y C y = 2.0 * x return end Below is the same function written in the MEX-file format. C-------------------------------------------------------------C timestwo.f C C Multiply the input argument by 2. C C C This is a MEX-file for MATLAB.
Examples of Fortran MEX-Files C Check for proper number of arguments. if(nrhs .ne. 1) then call mexErrMsgTxt('One input required.') elseif(nlhs .ne. 1) then call mexErrMsgTxt('One output required.') endif C Get the size of the input array. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) size = m*n C Check to ensure the input is a number. if(mxIsNumeric(prhs(1)) .eq. 0) then call mexErrMsgTxt('Input must be a number.') endif C Create matrix for the return argument.
3 Creating Fortran MEX-Files To compile and link this example source file, at the MATLAB prompt type mex timestwo.f This carries out the necessary steps to create the MEX-file called timestwo with an extension corresponding to the machine type on which you’re running. You can now call timestwo as if it were an M-function. x = 2; y = timestwo(x) y = 4 Passing Strings Passing strings from MATLAB to a Fortran MEX-file is straightforward.
Examples of Fortran MEX-Files Below is the gateway routine that calls the computational routine. C The gateway routine subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer nlhs, nrhs C-------------------------------------------------------------C (pointer) Replace integer by integer*8 on the DEC Alpha C platform.
3 Creating Fortran MEX-Files C C Initialize outbuf_buf to blanks. This is necessary on some compilers. output_buf = ' ' C Call the computational subroutine. call revord(input_buf, strlen, output_buf) C Set output_buf to MATLAB mexFunction output. plhs(1) = mxCreateString(output_buf) return end After checking for the correct number of inputs, this MEX-file gateway routine verifies that the input was either a row or column vector string.
Examples of Fortran MEX-Files MEX-file. Consequently, when returning to MATLAB, the output matrix must be transposed. This example places a string array/character matrix into MATLAB as output arguments rather than placing it directly into the workspace. Inside MATLAB, call this function by typing passstr; You will get the matrix mystring of size 5-by-15. There are some manipulations that need to be done here. The original string matrix is of the size 5-by-15.
3 Creating Fortran MEX-Files character*15 string(5) C Create the string to passed into MATLAB. string(1) = 'MATLAB ' string(2) = 'The Scientific ' string(3) = 'Computing ' string(4) = 'Environment ' string(5) = ' by TMW, Inc.' C Concatenate the set of 5 strings into a long string. thestring = string(1) do 10 i = 2, 6 thestring = thestring(:((i-1)*15)) // string(i) continue 10 C C Create the string matrix to be passed into MATLAB. Set the matrix size to be M=15 and N=5.
Examples of Fortran MEX-Files Passing Matrices In MATLAB, you can pass matrices into and out of MEX-files written in Fortran. You can manipulate the MATLAB arrays by using mxGetPr and mxGetPi to assign pointers to the real and imaginary parts of the data stored in the MATLAB arrays. You can create new MATLAB arrays from within your MEX-file by using mxCreateFull. This example takes a real 2-by-3 matrix and squares each element. C-------------------------------------------------------------C C matsq.
3 Creating Fortran MEX-Files integer x_pr, y_pr C-------------------------------------------------------------C integer nlhs, nrhs integer mxGetM, mxGetN, mxIsNumeric integer m, n, size real*8 x(1000), y(1000) 3-18 C Check for proper number of arguments. if(nrhs .ne. 1) then call mexErrMsgTxt('One input required.') elseif(nlhs .ne. 1) then call mexErrMsgTxt('One output required.') endif C Get the size of the input array.
Examples of Fortran MEX-Files C Load the data into y_pr, which is the output to MATLAB. call mxCopyReal8ToPtr(y, y_pr, size) return end After performing error checking to ensure that the correct number of inputs and outputs was assigned to the gateway subroutine and to verify the input was in fact a numeric matrix, matsq.f creates a matrix for the argument returned from the computational subroutine. The input matrix data is then copied to a Fortran matrix by using mxCopyPtrToReal8.
3 Creating Fortran MEX-Files 10 20 do 20 i=1,m do 10 j=1,n z(i,j)=x*y(i,j) continue continue return end Below is the gateway routine that calls xtimesy, the computation subroutine that multiplies a scalar by a scalar or matrix. C-------------------------------------------------------------C C xtimesy.f C C Multiply the first input by the second input. C C C This is a MEX file for MATLAB. Copyright (c) 1984-2000 The MathWorks, Inc. $Revision: 1.
Examples of Fortran MEX-Files endif C Check to see both inputs are numeric. if (mxIsNumeric(prhs(1)) .ne. 1) then call mexErrMsgTxt('Input # 1 is not a numeric.') elseif (mxIsNumeric(prhs(2)) .ne. 1) then call mexErrMsgTxt('Input #2 is not a numeric array.') endif C Check that input #1 is a scalar. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) if(n .ne. 1 .or. m .ne. 1) then call mexErrMsgTxt('Input #1 is not a scalar.') endif C Get the size of the input matrix.
3 Creating Fortran MEX-Files As this example shows, creating MEX-file gateways that handle multiple inputs and outputs is straightforward. All you need to do is keep track of which indices of the vectors prhs and plhs correspond to which input and output arguments of your function. In this example, the input variable x corresponds to prhs(1) and the input variable y to prhs(2).
Examples of Fortran MEX-Files C============================================================== C C Computational subroutine subroutine convec(x, y, z, nx, ny) complex*16 x(*), y(*), z(*) integer nx, ny C 10 20 30 Initialize the output array. do 10 i=1,nx+ny-1 z(i) = (0.0,0.0) continue do 30 i=1,nx do 20 j=1,ny z(i+j-1) = z(i+j-1) + x(i) * y(j) continue continue return end C The gateway routine.
3 Creating Fortran MEX-Files endif C Check that inputs are both row vectors. mx = mxGetM(prhs(1)) nx = mxGetN(prhs(1)) my = mxGetM(prhs(2)) ny = mxGetN(prhs(2)) nz = nx+ny-1 C Only handle row vector input. if(mx .ne. 1 .or. my .ne. 1) then call mexErrMsgTxt('Both inputs must be row vector.') Check sizes of the two input. elseif(nx .gt. 100 .or. ny .gt. 100) then call mexErrMsgTxt('Inputs must have less than 100 elements.') Check to see both inputs are complex. elseif ((mxIsComplex(prhs(1)) .ne. 1) .or.
Examples of Fortran MEX-Files Entering these numbers at the MATLAB prompt x = [3 - 1i, 4 + 2i, 7 - 3i] x = 3.0000 - 1.0000i 4.0000 + 2.0000i 7.0000 - 3.0000i y = [8 - 6i, 12 + 16i, 40 - 42i] y = 8.0000 - 6.0000i 12.0000 +16.0000i 40.0000 -42.0000i and invoking the new MEX-file z = convec(x, y) results in z = 1.0e+02 * Columns 1 through 4 0.1800 - 0.2600i 3.7600 - 0.1200i 0.9600 + 0.2800i 1.3200 - 1.4400i Column 5 1.5400 - 4.1400i which agrees with the results the built-in MATLAB function conv.
3 Creating Fortran MEX-Files C $Revision: 1.12 $ C=============================================================== C C dblmat.f C Example for illustrating how to use %val. C Doubles the input matrix. The demo only handles real part C of input. C NOTE: If your Fortran compiler does not support %val, C use mxCopy_routine. C C NOTE: The subroutine compute() is in the file called C compute.f. C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc.
Examples of Fortran MEX-Files m_in = mxGetM(prhs(1)) n_in = mxGetN(prhs(1)) size = m_in * n_in pr_in = mxGetPr(prhs(1)) mxCreateFull dynamically allocates memory. plhs(1) = mxCreateFull(m_in, n_in, 0) pr_out = mxGetPr(plhs(1)) C C Call the computational routine. call compute(%val(pr_out), %val(pr_in), size) return end C $Revision: 1.3 $ C=============================================================== C C compute.f C C This subroutine doubles the input matrix.
3 Creating Fortran MEX-Files For an input 2-by-3 matrix x = [1 2 3; 4 5 6]; typing y = dblmat(x) yields y = 2 8 4 10 6 12 Note The dblmat.f example, as well as fulltosparse.f and sincall.f, are split into two parts, the gateway and the computational subroutine, because of restrictions in some compilers. Handling Sparse Matrices The MATLAB API provides a set of functions that allow you to create and manipulate sparse matrices from within your MEX-files.
Examples of Fortran MEX-Files C C NOTE: The subroutine loadsparse() is in the file called C loadsparse.f. C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C C=============================================================== C The gateway routine.
3 Creating Fortran MEX-Files C C C C C C Get the size and pointers to input data. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) pr = mxGetPr(prhs(1)) Allocate space. NOTE: Assume at most 20% of the data is sparse. nzmax = dble(m*n) *.20 + .5 NOTE: The maximum number of non-zero elements cannot be less than the number of columns in the matrix. if (n .gt. nzmax) then nzmax = n endif plhs(1) = mxCreateSparse(m,n,nzmax,0) sr = mxGetPr(plhs(1)) irs = mxGetIr(plhs(1)) jcs = mxGetJc(plhs(1)) Load the sparse data.
Examples of Fortran MEX-Files C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C C=============================================================== C Load sparse data subroutine. function loadsparse(a,b,ir,jc,m,n,nzmax) integer nzmax, m, n integer ir(*), jc(*) real*8 a(*), b(*) integer i, j, k C C C 200 100 C 300 Copy nonzeros. k = 1 do 100 j=1,n NOTE: Sparse indexing is zero based. jc(j) = k-1 do 200 i=1,m if (a((j-1)*m+i).ne. 0.0) then if (k .gt.
3 Creating Fortran MEX-Files At the MATLAB prompt, entering full = eye(5) full = 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 creates a full, 5-by-5 identity matrix. Using fulltosparse on the full matrix produces the corresponding sparse matrix.
Examples of Fortran MEX-Files C C NOTE: The subfunction fill() is in the file called fill.f. C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C C ============================================================== C Gateway subroutine subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer nlhs, nrhs C--------------------------------------------------------------C (pointer) Replace integer by integer*8 on the DEC Alpha C platform.
3 Creating Fortran MEX-Files call mxFreeMatrix(lhs(1)) return end C $Revision: 1.3 $ C ================================================================ C C fill.f C This is the subfunction called by sincall that fills the C mxArray with data. Your version of fill can load your data C however you would like. C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C C ================================================================ C Subroutine for filling up data.
Examples of Fortran MEX-Files Running this example sincall displays the results Note It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLAB. See the example below. The following example creates an M-file that returns two variables but only assigns one of them a value. function [a,b]=foo[c] a=2*c; MATLAB displays the following warning message. Warning: One or more output arguments not assigned during call to 'foo'.
3 Creating Fortran MEX-Files Advanced Topics These sections cover advanced features of MEX-files that you can use when your applications require sophisticated MEX-files. Help Files Because the MATLAB interpreter chooses the MEX-file when both an M-file and a MEX-file with the same name are encountered in the same directory, it is possible to use M-files for documenting the behavior of your MEX-files.
Advanced Topics Memory Management As of Version 5.2, MATLAB now implicitly destroys (by calling mxDestroyArray) any arrays created by a MEX-file that are not returned in the left-hand side list (plhs()). Consequently, any misconstructed arrays left over at the end of a MEX-file’s execution have the potential to cause memory errors. In general, we recommend that MEX-files destroy their own temporary arrays and clean up their own temporary memory.
3 Creating Fortran MEX-Files Debugging Fortran Language MEX-Files On most platforms, it is now possible to debug MEX-files while they are running within MATLAB. Complete source code debugging, including setting breakpoints, examining variables, and stepping through the source code line-by-line, is now available. Note The section on “Troubleshooting” on page 1-32 provides additional information on isolating problems with MEX-files.
Debugging Fortran Language MEX-Files Note The name mexFunction may be slightly altered by the compiler (i.e., it may have an underscore appended). To determine how this symbol appears in a given MEX-file, use the UNIX command nm | grep -i mexfunction To proceed from the breakpoint, issue a continue command to the debugger. Once you hit one of your breakpoints, you can make full use of any facilities your debugger provides to examine variables, display memory, or inspect registers.
3 Creating Fortran MEX-Files 4 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 Microsoft debugging environment. For more information on how to debug in the Microsoft environment, see the Microsoft Development Studio documentation.
4 Calling MATLAB from C and Fortran Programs Using the MATLAB Engine . . . . . . . . . . . . . 4-3 The Engine Library . . . . . . . . . . . . . . . . . . 4-3 GUI-Intensive Applications . . . . . . . . . . . . . . 4-5 Examples of Calling Engine Functions . Calling MATLAB From a C Application . . Calling MATLAB From a Fortran Application Attaching to an Existing MATLAB Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 4-6 4-11 4-15 Compiling and Linking Engine Programs .
4 Calling MATLAB from C and Fortran Programs The MATLAB engine library is a set of routines that allows you to call MATLAB from your own programs, thereby employing MATLAB as a computation engine. MATLAB engine programs are C or Fortran programs that communicate with a separate MATLAB process via pipes (in UNIX) and through ActiveX on Windows.
Using the MATLAB Engine Using the MATLAB Engine Some of the things you can do with the MATLAB engine are: • Call a math routine, for example, to invert an array or to compute an FFT from your own program. When employed in this manner, MATLAB is a powerful and programmable mathematical subroutine library.
4 Calling MATLAB from C and Fortran Programs Table 4-1: C Engine Routines (Continued) Function Purpose engEvalString Execute a MATLAB command engOutputBuffer Create a buffer to store MATLAB text output engOpenSingleUse Start a MATLAB engine session for single, nonshared use engGetVisible Determine visibility of MATLAB engine session engSetVisible Show or hide MATLAB engine session Table 4-2: Fortran Engine Routines Function Purpose engOpen Start up MATLAB engine engClose Shut down MATLAB
Using the MATLAB Engine GUI-Intensive Applications If you have graphical user interface (GUI) intensive applications that execute a lot of callbacks through the MATLAB engine, you should force these callbacks to be evaluated in the context of the base workspace. Use evalin to specify that the base workspace is to be used in evaluating the callback expression, as follows.
4 Calling MATLAB from C and Fortran Programs Examples of Calling Engine Functions This section contains examples that illustrate how to call engine functions from C and Fortran programs. The examples cover the following topics: • “Calling MATLAB From a C Application” • “Calling MATLAB From a Fortran Application” • “Attaching to an Existing MATLAB Session” It is important to understand the sequence of steps you must follow when using the engine functions.
Examples of Calling Engine Functions int main() { Engine *ep; mxArray *T = NULL, *result = NULL; char buffer[BUFSIZE]; double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; /* * Start the MATLAB engine locally by executing the string * "matlab". * * To start the session on a remote host, use the name of * the host as the string rather than \0. * * For more complicated cases, use any string with whitespace, * and that string will be executed literally to start MATLAB.
4 Calling MATLAB from C and Fortran Programs /* * Evaluate a function of time, distance = (1/2)g.*t.^2 * (g is the acceleration due to gravity). */ engEvalString(ep, "D = .5.*(-9.8).*T.^2;"); /* * Plot the result. */ engEvalString(ep, "plot(T,D);"); engEvalString(ep, "title('Position vs. Time for a falling object');"); engEvalString(ep, "xlabel('Time (seconds)');"); engEvalString(ep, "ylabel('Position (meters)');"); /* * Use fgetc() to make sure that we pause long enough to be * able to see the plot.
Examples of Calling Engine Functions */ engOutputBuffer(ep, buffer, BUFSIZE); while (result == NULL) { char str[BUFSIZE]; /* * Get a string input from the user. */ printf("Enter a MATLAB command to evaluate. This command should\n"); printf("create a variable X. This program will then determine\n"); printf("what kind of variable you created.\n"); printf("For example: X = 1:5\n"); printf(">> "); fgets(str, BUFSIZE-1, stdin); /* * Evaluate input with engEvalString.
4 Calling MATLAB from C and Fortran Programs /* * We're done! Free memory, close MATLAB engine and exit. */ printf("Done!\n"); mxDestroyArray(result); engClose(ep); return EXIT_SUCCESS; } The first part of this program launches MATLAB and sends it data. MATLAB then analyzes the data and plots the results. The program then continues with Press Return to continue Pressing Return continues the program. Done for Part I. Enter a MATLAB command to evaluate. This command should create a variable X.
Examples of Calling Engine Functions Entering X = 17.5 continues the program execution. X = 17.5 X = 17.5000 Retrieving X... X is class double Done! Finally, the program frees memory, closes the MATLAB engine, and exits. Calling MATLAB From a Fortran Application This program, fengdemo.f, illustrates how to call the engine functions from a stand-alone Fortran program. C C C fengdemo.f C C This program illustrates how to call the MATLAB C Engine functions from a Fortran program.
4 Calling MATLAB from C and Fortran Programs C Other variable declarations here double precision time(10), dist(10) integer engPutMatrix, engEvalString, engClose integer temp, status data time / 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 / C ep = engOpen('matlab ') C if (ep .eq. 0) then write(6,*) 'Can''t start MATLAB engine' stop endif C T = mxCreateFull(1, 10, 0) call mxSetName(T, 'T') call mxCopyReal8ToPtr(time, mxGetPr(T), 10) C C C C Place the variable T into the MATLAB workspace.
Examples of Calling Engine Functions C C C Plot the result. if (engEvalString(ep, 'plot(T,D);') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'title(''Position vs. Time'')') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'xlabel(''Time (seconds)'')') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'ylabel(''Position (meters)'')') .ne.
4 Calling MATLAB from C and Fortran Programs C 20 10 D = engGetMatrix(ep, 'D') call mxCopyPtrToReal8(mxGetPr(D), dist, 10) print *, 'MATLAB computed the following distances:' print *, ' time(s) distance(m)' do 10 i=1,10 print 20, time(i), dist(i) format(' ', G10.3, G10.3) continue C C call mxFreeMatrix(T) call mxFreeMatrix(D) status = engClose(ep) C if (status .ne. 0) then write(6,*) 'engClose failed' stop endif C stop end Executing this program launches MATLAB, sends it data, and plots the results.
Examples of Calling Engine Functions The program continues with Type 0 to Exit Type 1 to continue Entering 1 at the prompt continues the program execution. 1 MATLAB computed the following distances: time(s) distance(m) 1.00 -4.90 2.00 -19.6 3.00 -44.1 4.00 -78.4 5.00 -123. 6.00 -176. 7.00 -240. 8.00 -314. 9.00 -397. 10.0 -490. Finally, the program frees memory, closes the MATLAB engine, and exits.
4 Calling MATLAB from C and Fortran Programs For example: 1 Shut down any MATLAB sessions. 2 From the Start button on the Windows menu bar, click Run. 3 In the Open field, type d:\matlab\bin\win32\matlab.exe /Automation where d:\matlab\bin\win32 represents the path to the MATLAB executable. 4 Click OK. This starts MATLAB. 5 In MATLAB, change directories to $MATLAB/extern/examples/eng_mat, where $MATLAB is the MATLAB root directory. 6 Compile the engwindemo.c example.
Compiling and Linking Engine Programs Compiling and Linking Engine Programs To produce an executable version of an engine program, you must compile it and link it with the appropriate library. This section describes the steps required to compile and link engine programs on UNIX and Windows systems. It begins by looking at a special consideration for compilers that do not mask floating-point exceptions.
4 Calling MATLAB from C and Fortran Programs #include . . . _control87(MCW_EM,MCW_EM); . . . Compiling and Linking on UNIX Under UNIX at runtime, you must tell the system where the API shared libraries reside. These sections provide the necessary UNIX commands depending on your shell and system architecture.
Compiling and Linking Engine Programs Compiling and Linking MATLAB provides an options file, engopts.sh, that lets you use the mex script to easily compile and link engine applications. For example, to compile and link the engdemo.c example, you can use mex -f /bin/engopts.sh /engdemo.c where specifies the complete path to the specified file.
4 Calling MATLAB from C and Fortran Programs 4-20
5 Calling Java from MATLAB Using Java from MATLAB: An Overview . . . . . . . 5-3 Bringing Java Classes into MATLAB . . . . . . . . . 5-5 Creating and Using Java Objects . . . . . . . . . . 5-10 Invoking Methods on Java Objects . . . . . . . . . . 5-19 Working with Java Arrays . . . . . . . . . . . . . 5-29 Passing Data to a Java Method . . . . . . . . . . . 5-46 Handling Data Returned from a Java Method . . . . . 5-56 Introduction to Programming Examples . . . . . . . 5-62 Example – Reading a URL . .
5 Calling Java from MATLAB This chapter describes how to use the MATLAB interface to Java classes and objects. This MATLAB capability enables you to conveniently bring Java classes into the MATLAB environment, to construct objects from those classes, to call methods on the Java objects, and to save Java objects for later reloading — all accomplished with MATLAB functions and commands.
Using Java from MATLAB: An Overview Using Java from MATLAB: An Overview Java Interface Is Integral to MATLAB Every installation of MATLAB includes a Java Virtual Machine (JVM), so that you can use the Java interpreter via MATLAB commands, and you can create and run programs that create and access Java objects. For information on MATLAB installation, see the MATLAB installation documentation for your platform.
5 Calling Java from MATLAB • Java in a Nutshell (Second Edition), by David Flanagan • Teach Yourself Java in 21 Days, by Lemay and Perkins Another place to find information is the JavaSoft Web site. http://www.javasoft.
Bringing Java Classes into MATLAB Bringing Java Classes into MATLAB You can draw from an extensive collection of existing Java classes or create your own class definitions to use with MATLAB. This section explains how to go about finding the class definitions that you need or how to create classes of your own design. Once you have the classes you need, defined in either individual .class files, packages, or Java Archive files, you will see how to make them available within the MATLAB environment.
5 Calling Java from MATLAB 1.1.8 Java Virtual Machine from the web site at Sun Microsystems, (http:// www.java.sun.com/jdk/). The Sun site also provides documentation for the Java language and classes that you will need for development. After you create class definitions in .java files, use your Java compiler to produce .class files from them. The next step is to make the class definitions in those .class files available for you to use in MATLAB.
Bringing Java Classes into MATLAB and JAR files, consult your Java development documentation or the JavaSoft web site. See also “To Learn More About Java Programming” on page 5-3. To make the contents of a JAR file available for use in MATLAB, add to classpath.txt the full path, including full filename, for the JAR file. Note Note that the classpath.txt requirement for JAR files is different than that for .class files and packages, for which you do not specify any filename.
5 Calling Java from MATLAB When you use the which function on methods defined by Java classes, the function only acts on the classes currently loaded into the MATLAB working environment. In contrast, which always operates on MATLAB classes, whether or not they are loaded. Determining Which Classes Are Loaded At any time during a MATLAB session, you can obtain a listing of all the Java classes that are currently loaded. To do so, you use the inmem function, in the following form.
Bringing Java Classes into MATLAB • java.lang.String • java.util.Enumeration A fully qualified name can be rather long, making commands and functions, such as constructors, cumbersome to edit and to read. You can refer to classes by the class name alone (without a package name) if you, first, import the fully qualified name into MATLAB. The import command has the following forms. import pkg_name.* import pkg_name1.* pkg_name2.
5 Calling Java from MATLAB Creating and Using Java Objects In MATLAB, you create a Java object by calling one of the constructors of that class. You then use commands and programming statements to perform operations on these objects. You can also save your Java objects to a MAT-file and, in subsequent sessions, reload them into MATLAB.
Creating and Using Java Objects class, class_name, with the argument list that matches x1,...,xn, and returns a new object, J. J = javaObject('class_name',x1,...,xn); For example, to construct and return a Java object of class java.lang.String, you use strObj = javaObject('java.lang.
5 Calling Java from MATLAB Note Typically, you will not need to use javaObject. The default MATLAB syntax for instantiating a Java class is somewhat simpler and is preferable for most applications. Use javaObject primarily for the two cases described above. Java Objects Are References in MATLAB In MATLAB, Java objects are references and do not adhere to MATLAB copy-on-assignment and pass-by-value rules. For example, origFrame = java.awt.
Creating and Using Java Objects Concatenating Objects of the Same Class If all of the objects being operated on are of the same Java class, then the concatenation of those objects produces an array of objects from the same class. In the following example, the cat function concatenates two objects of the class java.awt.Point. The class of the result is also java.awt.Point. point1 = java.awt.Point(24,127); point2 = java.awt.Point(114,29); cat(1, point1, point2) ans = java.awt.Point[]: [1x1 java.awt.
5 Calling Java from MATLAB If there is no common, lower level parent, then the resultant class is java.lang.Object, which is the root of the entire Java class hierarchy. byte = java.lang.Byte(127); point = java.awt.Point(24,127); [byte; point] ans = java.lang.Object[]: [ 127] [1x1 java.awt.Point] Saving and Loading Java Objects to MAT-Files Use the MATLAB save function to save a Java object to a MAT-file. Use the load function to load it back into MATLAB from that MAT-file.
Creating and Using Java Objects Finding the Public Data Fields of an Object To list the public fields that belong to a Java object, use the fieldnames function, which takes either of these forms. names = fieldnames(obj) names = fieldnames(obj,'-full') Calling fieldnames without '-full' returns the names of all the data fields (including inherited) on the object.
5 Calling Java from MATLAB 'static final float BOTTOM_ALIGNMENT % Inherited from java.awt.Component' 'static final float LEFT_ALIGNMENT % Inherited from java.awt.Component' 'static final float RIGHT_ALIGNMENT % Inherited from java.awt.Component' . . . Accessing Private and Public Data Java API classes provide accessor methods you can use to read from and, where allowed, to modify private data fields. These are sometimes referred to as get and set methods, respectively.
Creating and Using Java Objects Accessing Data from a Static Field In Java, a static data field is a field that applies to an entire class of objects. Static fields are most commonly accessed in relation to the class name itself in Java. For example, the code below accesses the WIDTH field of the Frame class by referring to it in relation to the package and class names, java.awt.Frame, rather than an object instance. width = java.awt.Frame.WIDTH; In MATLAB, you can use that same syntax.
5 Calling Java from MATLAB frameClass = class(frame) frameClass = java.awt.Frame Because this form of class also works on MATLAB objects, it does not, in itself, tell you whether it is a Java class. To determine the type of class, use the isjava function, which has the form x = isjava(obj) isjava returns 1 if obj is Java, and 0 if it is not.
Invoking Methods on Java Objects Invoking Methods on Java Objects This section explains how to invoke an object’s methods in MATLAB. It also covers how to obtain information related to the methods that you’re using and how MATLAB handles certain types of nonstandard situations.
5 Calling Java from MATLAB title = getTitle(frame) title = Sample Frame All of the programming examples in this chapter contain invocations of Java object methods. For example, the code for Reading a URL contains a call, using MATLAB syntax, to the openStream method on a java.net.URL object, url. is = openStream(url) In another example, the code for “Example – Creating and Using a Phone Book” on page 5-73 contains a call, using Java syntax, to the load method on a java.utils.
Invoking Methods on Java Objects With javaMethod, you can also specify the method to be invoked at run-time. In this situation, your code calls javaMethod with a string variable in place of the method name argument. When you use javaMethod to invoke a static method, you can also use a string variable in place of the class name argument. Note Typically, you will not need to use javaMethod. The default MATLAB syntax for invoking a Java method is somewhat simpler and is preferable for most applications.
5 Calling Java from MATLAB Using the javaMethod Function on Static Methods The javaMethod function was introduced in section “Using the javaMethod Function on Nonstatic Methods” on page 5-20. You can also use this function to call static methods. The following syntax invokes the static method, method_name, in class, class_name, with the argument list that matches x1,...,xn. This returns the value X. X = javaMethod('method_name','class_name',x1,...
Invoking Methods on Java Objects The following command lists information on all methods in the java.awt.MenuItem class. methodsview java.awt.MenuItem A new window appears, listing one row of information for each method in the class. This is what the methodsview display looks like. The fieldnames shown at the top of the window are described following the figure.
5 Calling Java from MATLAB Each row in the window displays up to six fields of information describing the method. The table below lists the fields displayed in the methodsview window along with a description and examples of each field type. Table 5-1: Fields Displayed in the Methodsview Window Field Name Description Examples Qualifiers Method type qualifiers abstract, synchronized Return Type Data type returned by the method void, java.lang.
Invoking Methods on Java Objects For example, display a full description of all methods of the java.awt.Dimension object. methods java.awt.Dimension -full Methods for class java.awt.Dimension: Dimension() Dimension(java.awt.Dimension) Dimension(int,int) java.lang.Class getClass() % Inherited from java.lang.Object int hashCode() % Inherited from java.lang.Object boolean equals(java.lang.Object) java.lang.String toString() void notify() % Inherited from java.lang.
5 Calling Java from MATLAB If you use which -all for the method equals, with the String and java.awt.Frame classes loaded, you see the following display. which -all equals java.lang.String.equals java.awt.Frame.equals com.mathworks.ide.desktop.MLDesktop.equals % String method % Frame method % MLDesktop method The which function operates differently on Java classes than it does on MATLAB classes. MATLAB classes are always displayed by which, whether or not they are loaded.
Invoking Methods on Java Objects Changing the Effect of isequal The MATLAB isequal function compares two or more arrays for equality in type, size, and contents. This function can also be used to test Java objects for equality. When you compare two Java objects using isequal, MATLAB performs the comparison using the Java method, equals. MATLAB first determines the class of the objects specified in the command, and then uses the equals method implemented by that class.
5 Calling Java from MATLAB Note When you define a Java class for use in MATLAB, avoid giving any of its methods the same name as a MATLAB built-in function. How MATLAB Handles Java Exceptions If invoking a Java method or constructor throws an exception, MATLAB catches the exception and transforms it into a MATLAB error. MATLAB puts the text of the Java error message into its own error message.
Working with Java Arrays Working with Java Arrays You can pass singular Java objects to and from methods or you may pass them in an array, providing the method expects them in that form. This array must either be a Java array (returned from another method call or created within MATLAB) or, under certain circumstances, a MATLAB cell array. This section describes how to create and manipulate Java arrays in MATLAB. Later sections will describe how to use MATLAB cell arrays in calls to Java methods.
5 Calling Java from MATLAB How MATLAB Represents the Java Array The term java array refers to any array of Java objects returned from a call to a Java class constructor or method. You may also construct a Java array within MATLAB using the javaArray function. The structure of a Java array is significantly different from that of a MATLAB matrix or array. MATLAB hides these differences whenever possible, allowing you to operate on the arrays using the usual MATLAB command syntax.
Working with Java Arrays Array Access from Java Array Access from MATLAB jArray[0] jArray(1) jArray[1] jArray(2) jArray[2] jArray(3) Simple Array jArray[0][3] Array of Arrays jArray[0][4][2] Array of Arrays of Arrays One-dimensional Array jArray(1,4) Two-Dimensional Array jArray(1,5,3) Three-Dimensional Array 5-31
5 Calling Java from MATLAB Array Indexing Java array indexing is different than MATLAB array indexing. Java array indices are zero-based, MATLAB array indices are one-based. In Java programming, you access the elements of array y of length N using y[0] through y[N-1]. When working with this array in MATLAB, you access these same elements using the MATLAB indexing style of y(1) through y(N).
Working with Java Arrays When the size function is applied to a Java array of arrays, the resulting value describes the top level of the specified array. For the Java array shown here size(A) = 3x1 size(A(3)) = 5x1 size(A) returns the dimensions of the highest array level of A. The highest level of the array has a size of 3-by-1. size(A) ans = 3 1 To find the size of a lower level array, say the five-element array in row 3, refer to the row explicitly.
5 Calling Java from MATLAB Creating an Array of Objects Within MATLAB To call a Java method that has one or more arguments defined as an array of Java objects, you must, under most circumstances, pass your objects in a Java array. You can construct an array of objects in a call to a Java method or constructor. Or you can create the array within MATLAB. The MATLAB javaArray function lets you create a Java array structure that can be handled in MATLAB as a single multidimensional array.
Working with Java Arrays for m = 1:4 for n = 1:5 dblArray(m,n) = java.lang.Double((m*10) + n); end end dblArray dblArray = java.lang.Double[][]: [11] [12] [13] [21] [22] [23] [31] [32] [33] [41] [42] [43] [14] [24] [34] [44] [15] [25] [35] [45] Another Way to Create a Java Array You can also create an array of Java objects using syntax that is more typical to MATLAB. For example, the following syntax creates a 4-by-5 MATLAB array of type double and assigns zero to each element of the array.
5 Calling Java from MATLAB This example first creates a scalar MATLAB array, and then successfully modifies it to be two-dimensional. matlabArray = 0; matlabArray(4,5) = 0 matlabArray = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 When you try this with a Java array, you get an error. Similarly, you cannot create an array of Java arrays from a Java array, and so forth. javaArray = java.lang.Double(0); javaArray(4,5) = java.lang.Double(0); ??? Index exceeds Java array dimensions.
Working with Java Arrays element at the intersection of row 3 and column 4. Sometimes it is more advantageous to use just a single subscript. MATLAB provides this capability (see the section on “Advanced Indexing” in the Using MATLAB manual). Indexing into a MATLAB matrix using a single subscript references one element of the matrix. Using the MATLAB matrix shown here, matlabArray(3) returns a single element of the matrix. matlabArray = [11 12 13 14 15; 21 22 23 24 25; ...
5 Calling Java from MATLAB here, the statement dblArray(2,2:4) refers to a portion of the lower level array, dblArray(2). A new array, row2Array, is created from the elements in columns 2 through 4. dblArray dblArray = java.lang.Double[][]: [11] [12] [13] [21] [22] [23] [31] [32] [33] [41] [42] [43] [14] [24] [34] [44] [15] [25] [35] [45] row2Array = dblArray(2,2:4) row2Array = java.lang.
Working with Java Arrays This works the same way on an N-dimensional Java array structure. Using the colon operator as a single subscripted index into the array produces a linear array composed of all of the elements of the original array. Note Java and MATLAB arrays are stored differently in memory. This is reflected in the order they are given in a linear array. Java array elements are stored in an order that matches the rows of the matrix, (11, 12, 13, ... in the array shown above).
5 Calling Java from MATLAB The following example deposits the value 300 in the dblArray element at row 3, column 2. In Java, this would be dblArray[2][1]. dblArray(3,2) = java.lang.Double(300) dblArray = java.lang.Double[][]: [11] [ 12] [13] [14] [15] [21] [ 22] [23] [24] [25] [31] [300] [33] [34] [35] [41] [ 42] [43] [44] [45] You use the same syntax to assign to an element in an object’s data field.
Working with Java Arrays [ 21] [100] [ 41] [ 22] [200] [ 42] [ 23] [300] [ 43] [ 24] [400] [ 44] [ 25] [500] [ 45] Assigning to a Linear Array You can assign a value to every element of a multidimensional Java array by treating the array structure as if it were a single linear array. This entails replacing the single, numerical subscript with the MATLAB colon operator.
5 Calling Java from MATLAB can also assign [] to array elements. This stores the NULL value, rather than a 0-by-0 array, in the Java array element. Subscripted Deletion When you assign the empty matrix value to an entire row or column of a MATLAB array, you find that MATLAB actually removes the affected row or column from the array. In the example below, the empty matrix is assigned to all elements of the fourth column in the MATLAB matrix, matlabArray.
Working with Java Arrays The dblArray data structure s actually an array of five-element arrays of java.lang.Double objects. The empty array assignment placed the NULL value in the fourth element of each of the lower level arrays. Concatenating Java Arrays You can concatenate arrays of Java objects in the same way as arrays of other data types. (To understand how scalar Java objects are concatenated by MATLAB see “Concatenating Java Objects” on page 5-12.
5 Calling Java from MATLAB % Concatenate the two along the second dimension. d3 = cat(2,d1,d2) d3 = java.lang.Double[][]: [2] [4] [6] [3] [5] [7] [4] [6] [8] [ 8] [ 9] [10] [10] [11] [12] Creating a New Array Reference Because Java arrays in MATLAB are references, assigning an array variable to another variable results in a second reference to the array. Consider the following example where two separate array variables reference a common array. The original array, origArray, is created and initialized.
Working with Java Arrays java.lang.Double[][]: [11] [12] [13] [21] [22] [23] [ 0] [ 0] [ 0] [14] [24] [ 0] Creating a Copy of a Java Array You can create an entirely new array from an existing Java array by indexing into the array to describe a block of elements, (or subarray), and assigning this subarray to a variable. The assignment copies the values in the original array to the corresponding cells of the new array.
5 Calling Java from MATLAB Passing Data to a Java Method When you make a call from MATLAB to Java code, any MATLAB data types you pass in the call are converted to data types native to the Java language. MATLAB performs this conversion on each argument that is passed, except for those arguments that are already Java objects. This section describes the conversion that is performed on specific MATLAB data types and, at the end, also takes a look at how argument types affect calls made to overloaded methods.
Passing Data to a Java Method scalar (1-by-1) arrays or matrices. All of the Java types can be scalar values or arrays.
5 Calling Java from MATLAB Passing Built-In Data Types Java has eight data types that are intrinsic to the language and are not represented as Java objects. These are often referred to as built-in, or elemental, data types and they include boolean, byte, short, long, int, double, float, and char. MATLAB converts its own data types to these Java built-in types according to the table, “Conversion of MATLAB Types to Java Types” on page 5-47. Built-in types are in the first 10 rows of the table.
Passing Data to a Java Method [poly.xpoints poly.ypoints] ans = 14 55 42 12 98 -2 124 62 % Verify the coordinates MATLAB Arrays Are Passed by Value Since MATLAB arrays are passed by value, any changes that a Java method makes to them will not be visible to your MATLAB code. If you need to access changes that a Java method makes to an array, then, rather than passing a MATLAB array, you should create and pass a Java array, which is a reference.
5 Calling Java from MATLAB In the MATLAB call to this constructor, a character array specifying the URL is passed. MATLAB converts this array to a Java String object prior to calling the constructor. url = java.net.URL(... 'http://www.ncsa.uiuc.edu/demoweb/url-primer.html') Passing Strings in an Array When the method you are calling expects an argument of an array of type String, you can create such an array by packaging the strings together in a MATLAB cell array.
Passing Data to a Java Method In each of these calls to menu1.add, an object that is an instance of the java.awt.MenuItem Java class is passed. menu1 = java.awt.Menu('File Options'); menu1.add(java.awt.MenuItem('New')); menu1.add(java.awt.MenuItem('Open')); menu1.add(java.awt.MenuItem('Save')); menuBar=java.awt.MenuBar; menuBar.add(menu1); frame.setMenuBar(menuBar); Handling Objects of Class java.lang.Object A special case exists when the method being called takes an argument of the java.lang.
5 Calling Java from MATLAB The three calls to put from the preceding example can be rewritten as hTable.put(0, 1); hTable.put(1, 41.287); hTable.put(2, 'test string'); Passing Objects in an Array The only types of Java object arrays that you can pass to Java methods are Java arrays and MATLAB cell arrays.
Passing Data to a Java Method Handling a Cell Array of Java Objects You create a cell array of Java objects by using the MATLAB syntax {a1,a2,...}. You index into a cell array of Java objects in the usual way, with the syntax a{m,n,...}. The following example creates a cell array of two Frame objects, frame1 and frame2, and assigns it to variable frames. frame1 = java.awt.Frame('Frame A'); frame2 = java.awt.Frame('Frame B'); frameArray = {frame1, frame2} frameArray = [1x1 java.awt.Frame] [1x1 java.awt.
5 Calling Java from MATLAB determined solely by the number of nested arrays. For example, double[][] has dimension 2, and double has dimension 0. If the Java array’s number of dimensions exactly matches the MATLAB array’s number of dimensions n, then the conversion results in a Java array with n dimensions.
Passing Data to a Java Method First, MATLAB rejects all methods that have any argument types that are incompatible with the passed arguments (for example, if the method has a double argument and the passed argument is a char). Among the remaining methods, MATLAB selects the one with the highest fitness value, which is the sum of the fitness values of all its arguments.
5 Calling Java from MATLAB Handling Data Returned from a Java Method In many cases, data returned from Java is incompatible with the data types operated on within MATLAB. When this is the case, MATLAB converts the returned value to a data type native to the MATLAB language. This section describes the conversion performed on the various data types that can be returned from a call to a Java method.
Handling Data Returned from a Java Method Built-In Data Types Java built-in data types are described in “Passing Built-In Data Types” on page 5-48. Basically, this data type includes boolean, byte, short, long, int, double, float, and char. When the value returned from a method call is one of these Java built-in types, MATLAB converts it according to the table, “Conversion of Java Types to MATLAB Types” on page 5-56.
5 Calling Java from MATLAB Converting to the MATLAB double Data Type Using the double function in MATLAB, you can convert any Java object or array of objects to the MATLAB double data type. The action taken by the double function depends on the class of the object you specify: • If the object is an instance of a numeric class (java.lang.Number or one of the classes that inherit from that class), then MATLAB uses a preset conversion algorithm to convert the object to a MATLAB double.
Handling Data Returned from a Java Method method of the class to perform the conversion. If you write your own class definitions, then you can make use of this feature by writing a toChar method that performs the conversion according to your own needs. Note If the class of the specified object is not java.lang.String and it does not implement a toChar method, then an attempt to convert the object using the char function results in an error in MATLAB.
5 Calling Java from MATLAB pstruct.xpoints ans = 14 42 98 124 pstruct.xpoints(3) = 101; Converting to a MATLAB Cell Array Use the cell function to convert a Java array or Java object into a MATLAB cell array. Elements of the resulting cell array will be of the MATLAB type (if any) closest to the Java array elements or Java object. The syntax for the cell command is as follows, where object is a Java object or Java array of objects.
Handling Data Returned from a Java Method % Convert cellArray cellArray {1x10 each to cell arrays = {cell(dblArray), cell(ptArray), cell(strArray)} = cell} {3x1 cell} {2x2 cell} cellArray{1,1} ans = [7] [14] % Array of type double [21] cellArray{1,2} [28] [35] [42] [49] [56] [63] [70] % Array of type Java.awt.Point ans = [1x1 java.awt.Point] [1x1 java.awt.Point] [1x1 java.awt.
5 Calling Java from MATLAB Introduction to Programming Examples The following programming examples demonstrate the MATLAB interface to Java classes and objects: • “Example – Reading a URL” • “Example – Finding an Internet Protocol Address” • “Example – Communicating Through a Serial Port” • “Example – Creating and Using a Phone Book” Each example contains the following sections: • Overview - Describes what the example does and how it uses the Java interface to accomplish it.
Example – Reading a URL Example – Reading a URL This program, URLdemo, opens a connection to a web site specified by a URL (Uniform Resource Locator), for the purpose of reading text from a file at that site. It constructs an object of the Java API class, java.net.URL, which enables convenient handling of URLs. Then, it calls a method on the URL object, to open a connection. To read and display the lines of text at the site, URLdemo uses classes from the Java I/O package java.io.
5 Calling Java from MATLAB BufferedReader object to variable br. A buffered reader provides for efficient reading of characters, arrays, and lines. isr = java.io.InputStreamReader(is) br = java.io.BufferedReader(isr) 4. Read and Display Lines of Text The final statement reads and displays the first 10 lines of text from the site. Within a MATLAB for statement that iterates 10 times, the BufferedReader method readLine reads a line of text (terminated by a return and/or line feed character) from the site.
Example – Reading a URL s = concept: not only can you point to a file in a directory, but that s = file and that directory can exist on any machine on the network, s = can be served via any of several different methods, and might not s = even be something as simple as a file: URLs can also point to s = queries, documents stored deep within databases, the results of a s = finger or archie 5-65
5 Calling Java from MATLAB Example – Finding an Internet Protocol Address The resolveip function returns either the name or address of an IP (internet protocol) host. If you pass resolveip a hostname, it returns the IP address. If you pass resolveip an IP address, it returns the hostname. The function uses the Java API class java.net.InetAddress, which enables you to find an IP address for a hostname, or the hostname for a given IP address, without making DNS calls.
Example – Finding an Internet Protocol Address 3. Display the Hostname or IP Address The example uses the MATLAB strcmp function to compare the input argument to the resolved IP address. If it matches, MATLAB displays the hostname for the internet address. If the input does not match, MATLAB displays the IP address.
5 Calling Java from MATLAB Example – Communicating Through a Serial Port The serialexample program uses classes of the Java API javax.comm package, which support access to communications ports. After defining port configuration variables, serialexample constructs a javax.comm.CommPortIdentifier object, to manage the serial communications port. The program calls the open method on that object to return an object of the javax.comm.
Example – Communicating Through a Serial Port Description of Serial Example The major tasks performed by serialexample are: 1. Define Variables for Serial Port Configuration and Output The first five statements define variables for configuring the serial port. The first statement defines the baud rate to be 9600, the second defines number of data bits to be 8, and the third defines the number of stop bits to be 1.
5 Calling Java from MATLAB 4. Configure the Serial Port The next three statements call configuration methods on the SerialPort object serialPort. The first statement calls setSerialPortParams to set the baud rate, data bits, stop bits, and parity. The next two statements call setFlowControlMode to set the flow control, and then enableReceiveTimeout to set the timeout for receiving data. setSerialPortParams(serialPort, SerialPort_BAUD_9600,... SerialPort_DATABITS_8, SerialPort_STOPBITS_1,...
Example – Communicating Through a Serial Port 7. Open an Input Stream and Determine Number of Bytes to Read To read the data expected from the oscilloscope in response to the contrast query, the example opens an input stream by calling the static method, InputStream.getInputStream, to obtain an InputStream object for the serial port. Then, the example calls the method available on the InputStream object, in, and assigns the returned number of bytes to numAvail.
5 Calling Java from MATLAB Running the serialexample Program The value of result depends upon whether your system’s COM1 port is cabled to an oscilloscope. If you have run the example with an oscilloscope, you see the result of reading the serial port. result = 45 If you run the example without an oscilloscope attached, there is no data to read. In that case, you see an empty character array.
Example – Creating and Using a Phone Book Example – Creating and Using a Phone Book The example’s main function, phonebook, can be called either with no arguments, or with one argument, which is the key of an entry that exists in the phone book. The function first determines the directory to use for the phone book file. If no phone book file exists, it creates one by constructing a java.io.FileOutputStream object, and then closing the output stream.
5 Calling Java from MATLAB Description of Function phonebook The major tasks performed by phonebook are: 1. Determine the Data Directory and Full Filename The first statement assigns the phone book filename, 'myphonebook', to the variable pbname. If the phonebook program is running on a PC, it calls the java.lang.System static method getProperty to find the directory to use for the data dictionary. This will be set to the user’s current working directory.
Example – Creating and Using a Phone Book if r == 'y', try FOS = java.io.FileOutputStream(pbname); FOS.close catch error(sprintf('Failed to create %s', pbname)); end; else return; end; end; 3. Create a Hash Table The example constructs a java.util.Properties object to serve as the hash table for the data dictionary. pb_htable = java.util.Properties; 4.
5 Calling Java from MATLAB 6. Display the Action Menu and Get the User’s Selection Within a while loop, several disp statements display a menu of actions that the user can perform on the phone book. Then, an input statement requests the user’s typed selection. while 1 disp ' ' disp ' Phonebook Menu:' disp ' ' disp ' 1. Look up a phone number' disp ' 2. Add an entry to the phone book' disp ' 3. Remove an entry from the phone book' disp ' 4. Change the contents of an entry in the phone book' disp ' 5.
Example – Creating and Using a Phone Book Case 2 calls pb_add, which prompts the user for a new entry and then adds it to the phone book. case '2', pb_add(pb_htable); Case 3 uses input to prompt for the name of an entry to remove. If a name has not been entered, it calls disp to display an error message. If a name has been input, it passes it to pb_remove.
5 Calling Java from MATLAB object FOS and a descriptive header string. It then calls close on the FileOutputStream object, and returns. case '6', try FOS = java.io.FileOutputStream(pbname); catch error(sprintf('Failed to open %s for writing.',... pbname)); end; pb_htable.save(FOS,'Data file for phonebook program'); FOS.close; return; otherwise disp 'That selection is not on the menu.
Example – Creating and Using a Phone Book Description of Function pb_add 1. Input the Entry to Add The pb_add function takes one argument, the Properties object pb_htable. pb_add uses disp to prompt for an entry. Using the up-arrow (^) character as a line delimiter, input inputs a name to the variable entry. Then, within a while loop, it uses input to get another line of the entry into variable line.
5 Calling Java from MATLAB Description of Function pb_remove 1. Look For the Key in the Phone Book Arguments passed to pb_remove are the Properties object pb_htable and the name key for the entry to remove. The pb_remove function calls containsKey on pb_htable with the name key, on which support function pb_keyfilter is called to change spaces to underscores. If name is not in the phone book, disp displays a message and the function returns. function pb_remove(pb_htable,name) if ~pb_htable.
Example – Creating and Using a Phone Book the name will be added to the phone book, and allows the user to enter the phone number(s) for the entry. If the entry is found, in the else clause, pb_change calls pb_display to display the entry. It then uses input to ask the user to confirm the replacement. If the user enters anything other than y, the function returns. function pb_change(pb_htable,name) entry = pb_htable.
5 Calling Java from MATLAB pb_htable.put(pb_keyfilter(name),entry); disp ' ' disp(sprintf('The entry for %s has been changed', name)); Description of Function pb_listall The pb_listall function takes one argument, the Properties object pb_htable. The function calls propertyNames on the pb_htable object to return to enum a java.util.Enumeration object, which supports convenient enumeration of all the keys.
Example – Creating and Using a Phone Book Description of Function pb_keyfilter The pb_keyfilter function takes an argument key, which is a name used as a key in the hash table, and either filters it for storage or unfilters it for display. The filter, which replaces each space in the key with an underscore (_), makes the key usable with the methods of java.util.Properties.
5 Calling Java from MATLAB Phonebook Menu: 1. 2. 3. 4. 5. 6. Look up a phone number Add an entry to the phone book Remove an entry from the phone book Change the contents of an entry in the phone book Display entire contents of the phone book Exit this program Please type the number for a menu selection: 2 Type the name for the new entry, followed by Enter. Then, type the phone number(s), one per line. To complete the entry, type an extra Enter.
Example – Creating and Using a Phone Book (508) 111-3456 ------------------------------------------------Russell Reddy (617) 999-8765 ------------------------- 5-85
5 Calling Java from MATLAB 5-86
6 Importing and Exporting Data Using MAT-Files . . . . . . . . . . Importing Data to MATLAB . . . . . . Exporting Data from MATLAB . . . . . Exchanging Data Files Between Platforms Reading and Writing MAT-Files . . . . Finding Associated Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Examples of MAT-Files . . . Creating a MAT-File in C . . . Reading a MAT-File in C . . . Creating a MAT-File in Fortran .
6 Importing and Exporting Data You can use MAT-files, the data file format MATLAB uses for saving data to disk, to import data to and export data from the MATLAB environment. MAT-files provide a convenient mechanism for moving your MATLAB data between different platforms in a highly portable manner. In addition, they provide a means to import and export your data to other stand-alone MATLAB applications.
Using MAT-Files Using MAT-Files This section describes the various techniques for importing data to and exporting data from the MATLAB environment.
6 Importing and Exporting Data computer-readable form and you have to type it in. Essentially the same as the first method, this method has the advantage of allowing you to use your editor to change the data and correct mistakes. You can then just rerun your M-file to re-enter the data. • Load data from an ASCII flat file. A flat file stores the data in ASCII form, with fixed-length rows terminated with new lines (carriage returns) and with spaces separating the numbers.
Using MAT-Files • 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.dat A -ascii creates an ASCII file called temp.dat containing 1.3889088e-001 2.0276522e-001 1.9872174e-001 6.0379248e-001 2.7218792e-001 1.9881427e-001 1.5273927e-002 7.4678568e-001 4.4509643e-001 9.3181458e-001 4.6599434e-001 4.1864947e-001 The -ascii option supports two-dimensional double and character arrays only.
6 Importing and Exporting Data Both types of files can be transported directly between machines: M-files because they are platform independent and MAT-files because they contain a machine signature in the file header. MATLAB checks the signature when it loads a file and, if a signature indicates that a file is foreign, performs the necessary conversion. Using MATLAB across several different machine architectures requires a facility for exchanging both binary and ASCII data between the various machines.
Using MAT-Files The MAT-file library contains routines for reading and writing MAT-files. They all begin with the three-letter prefix mat. These tables list all the available MAT-functions and their purposes.
6 Importing and Exporting Data Table 6-2: Fortran MAT-File Routines (Continued) MAT-Function Purpose matGetDir Get a list of MATLAB arrays from a MAT-file matGetMatrix Get a named MATLAB array from a MAT-file matPutMatrix Put a MATLAB array into a MAT-file matGetNextMatrix Get the next sequential MATLAB array from a MAT-file matDeleteMatrix Remove a MATLAB array from a MAT-file matGetString Read a MATLAB string from a MAT-file matPutString Write a MATLAB string to a MAT-file Finding Associ
Using MAT-Files Include Files The include directory holds header files containing function declarations with prototypes for the routines that you can access in the API Library. These files are the same for both Windows and UNIX. Included in the subdirectory are: • matrix.h, the header file that defines MATLAB array access and creation methods • mat.
6 Importing and Exporting Data Table 6-4: C and Fortran Examples Library Description matcreat.c Example C program that demonstrates how to use the library routines to create a MAT-file that can be loaded into MATLAB matdgns.c Example C program that demonstrates how to use the library routines to read and diagnose a MAT-file matdemo1.f Example Fortran program that demonstrates how to call the MATLAB MAT-file functions from a Fortran program matdemo2.
Examples of MAT-Files Examples of MAT-Files This section includes C and Fortran examples of writing, reading, and diagnosing MAT-files. The examples cover the following topics: • “Creating a MAT-File in C” • “Reading a MAT-File in C” • “Creating a MAT-File in Fortran” • “Reading a MAT-File in Fortran” Creating a MAT-File in C This sample program illustrates how to use the library routines to create a MAT-file that can be loaded into MATLAB.
6 Importing and Exporting Data #include /* For EXIT_FAILURE, EXIT_SUCCESS */ #include "mat.h" #define BUFSIZE 256 int main() { MATFile *pmat; mxArray *pa1, *pa2, *pa3; double data[9] = { 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 }; const char *file = "mattest.mat"; char str[BUFSIZE]; int status; printf("Creating file %s...
Examples of MAT-Files pa3 = mxCreateString("MATLAB: the language of technical computing"); if (pa3 == NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create string mxArray.
6 Importing and Exporting Data if (status != 0) { printf("%s : Error using matPutArray on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } /* clean up */ mxDestroyArray(pa1); mxDestroyArray(pa2); mxDestroyArray(pa3); if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(EXIT_FAILURE); } /* * Reopen file and verify its contents with matGetArray */ pmat = matOpen(file, "r"); if (pmat == NULL) { printf("Error reopening file %s\n", file); return(EXIT_FAILURE); } /* * Read in each a
Examples of MAT-Files pa2 = matGetArray(pmat, "GlobalDouble"); if (pa2 == NULL) { printf("Error reading existing matrix GlobalDouble\n"); return(EXIT_FAILURE); } if (!(mxIsFromGlobalWS(pa2))) { printf("Error saving global matrix: result is not global\n"); return(EXIT_FAILURE); } pa3 = matGetArray(pmat, "LocalString"); if (pa3 == NULL) { printf("Error reading existing matrix LocalDouble\n"); return(EXIT_FAILURE); } status = mxGetString(pa3, str, sizeof(str)); if(status != 0) { printf("Not enough space.
6 Importing and Exporting Data To produce an executable version of this example program, compile the file and link it with the appropriate library. Details on how to compile and link MAT-file programs on the various platforms are discussed in the section, “Compiling and Linking MAT-File Programs” on page 6-28. Once you have compiled and linked your MAT-file program, you can run the stand-alone application you have just produced. This program creates a MAT-file, mattest.mat, that can be loaded into MATLAB.
Examples of MAT-Files * * * * * * * */ matClose matGetDir matGetNextArray matGetNextArrayHeader matOpen Copyright (c) 1984-1998 The MathWorks, Inc. #include #include #include #include "string.h" "mat.h" int diagnose(const char *file) { MATFile *pmat; char **dir; int ndir; int i; mxArray *pa; printf("Reading file %s...\n\n", file); /* Open file to get directory.
6 Importing and Exporting Data mxFree(dir); /* In order to use matGetNextXXX correctly, reopen file to read in headers. */ if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(1); } pmat = matOpen(file, "r"); if (pmat == NULL) { printf("Error reopening file %s\n", file); return(1); } /* Get headers of all variables.
Examples of MAT-Files if (pmat == NULL) { printf("Error reopening file %s\n", file); return(1); } /* Read in each array. */ printf("\nReading in the actual array contents:\n"); for (i=0; i
6 Importing and Exporting Data else { result = 0; printf("Usage: matdgns "); printf("where is the name of the MAT-file"); printf("to be diagnosed"); } return (result==0)?EXIT_SUCCESS:EXIT_FAILURE; } After compiling and linking this program, you can view its results. matdgns mattest.mat Reading file mattest.mat... Directory of mattest.
Examples of MAT-Files Creating a MAT-File in Fortran This example creates a MAT-file, matdemo.mat. C $Revision: 1.6 $ C C matdemo1.f C C This is a simple program that illustrates how to call the C MATLAB MAT-file functions from a Fortran program. This C demonstration focuses on writing MAT-files. C C Copyright (c) 1984-2000 The MathWorks, Inc. C C C C C matdemo1 - Create a new MAT-file from scratch.
6 Importing and Exporting Data if (mp .eq. 0) then write(6,*) 'Can''t open ''matdemo.mat'' for writing.' write(6,*) '(Do you have write permission in this directory?)' stop end if C C C Create variables.
Examples of MAT-Files if (status .ne. 0) then write(6,*) 'Error closing MAT-file' stop end if C mp = matOpen('matdemo.mat', 'r') if (status .ne. 0) then write(6,*) 'Can''t open ''matdemo.mat'' for reading.' stop end if C pa1 = matGetMatrix(mp, 'Numeric') if (mxIsNumeric(pa1) .eq. 0) then write(6,*) 'Invalid non-numeric matrix written to MAT-file' stop end if C pa2 = matGetMatrix(mp, 'String') if (mxIsString(pa2) .eq.
6 Importing and Exporting Data Once you have compiled and linked your MAT-file program, you can run the stand-alone application you have just produced. This program creates a MAT-file, matdemo.mat, that can be loaded into MATLAB. To run the application, depending on your platform, either double-click on its icon or enter matdemo1 at the system prompt. matdemo1 Creating MAT-file matdemo.mat ...
Examples of MAT-Files C-------------------------------------------------------------C $Revision: 1.7 $ C program matdemo2 C-------------------------------------------------------------C (integer) Replace integer by integer*8 on the DEC Alpha C platform.
6 Importing and Exporting Data C C C Copy integer to character string do 20 i=1,ndir call mxCopyPtrToCharacter(adir(i), names(i), 32) 20 continue C write(6,*) 'Directory of Mat-file:' do 30 i=1,ndir write(6,*) names(i) 30 continue C stat = matClose(mp) if (stat .ne. 0) then write(6,*) 'Error closing ''matdemo.mat''.' stop end if C C------------------------------------------------------------C Reopen file and read full arrays.
Examples of MAT-Files end do C stat = matClose(mp) if (stat .ne. 0) then write(6,*) 'Error closing ''matdemo.mat''.' stop end if stop C end After compiling and linking this program, you can view its results.
6 Importing and Exporting Data Compiling and Linking MAT-File Programs This section describes the steps required to compile and link MAT-file programs on UNIX and Windows systems. It begins by looking at a special consideration for compilers that do not mask floating-point exceptions.
Compiling and Linking MAT-File Programs #include . . . _control87(MCW_EM,MCW_EM); . . . Compiling and Linking on UNIX Under UNIX at runtime, you must tell the system where the API shared libraries reside. These sections provide the necessary UNIX commands depending on your shell and system architecture.
6 Importing and Exporting Data Using the Options File MATLAB provides an options file, matopts.sh, that lets you use the mex script to easily compile and link MAT-file applications. For example, to compile and link the matcreat.c example, you can use mex -f /bin/matopts.sh /matcreat.c where specifies the complete path to the specified file.
7 ActiveX and DDE Support Introducing MATLAB ActiveX Integration . . . . . . 7-3 ActiveX Concepts and Terminology . . . . . . . . . . . 7-3 MATLAB ActiveX Support Overview . . . . . . . . . . 7-4 MATLAB ActiveX Client Support . . . . . . . . . . 7-6 Using ActiveX Objects . . . . . . . . . . . . . . . . 7-6 Writing Event Handlers . . . . . . . . . . . . . . . 7-8 Additional ActiveX Client Information Releasing Interfaces . . . . . . . . . Using ActiveX Collections . . . . . . . Converting Data . . . . . . .
7 ActiveX and DDE Support ActiveX is a set of object-oriented technologies and tools that allow software developers to integrate application-specific components from different vendors into their own application solution. ActiveX Control components can be both visually and programmatically integrated into an ActiveX control container, such as a MATLAB figure window. ActiveX Automation allows MATLAB to both control and be controlled by other ActiveX components.
Introducing MATLAB ActiveX Integration Introducing MATLAB ActiveX Integration ActiveX is a Microsoft Windows protocol for component integration. Using ActiveX, developers and end users can select application-specific, ActiveX components produced by different vendors and seamlessly integrate them into a complete application solution. For example, a single application may require database access, mathematical analysis, and presentation quality business graphs.
7 ActiveX and DDE Support • Properties Radius (integer) - sets the radius of the circle drawn by the control Label (string) - text to be drawn in the control • Events Click - fired when the user clicks on the control One important characteristic of COM is that it defines an object model in which objects support multiple interfaces.
Introducing MATLAB ActiveX Integration In general, servers that are not controls will not be physically or visually embedded in the client application. (MATLAB is a good example — MATLAB is not itself a control, but it is a server. So, MATLAB cannot be physically embedded within another client. However, since MATLAB is a control container, other ActiveX controls can be embedded within MATLAB.
7 ActiveX and DDE Support MATLAB ActiveX Client Support In order to use an ActiveX component with MATLAB or with any ActiveX client, you first need to consult the documentation for that object and find out the name of the object itself (known as the ProgID), as well as the names of the interfaces, methods, properties, and events that the object uses. Once you have this information, you can integrate that object with MATLAB by using the ActiveX client support.
MATLAB ActiveX Client Support invoke Invokes a method on an interface or displays a list of methods load Initializes an ActiveX object from a file move Moves and/or resizes an ActiveX control in its parent window propedit Asks the control to display its built-in property page release Releases an activex object save Serializes an ActiveX control object to a file send Displays a list of events set Sets a property on an interface The creation commands, actxcontrol and actxserver, both return a
7 ActiveX and DDE Support Writing Event Handlers ActiveX events are invoked when a control wants to notify its container that something of interest has occurred. For example, many controls trigger an event when the user single-clicks on the control. In MATLAB, when a control is created, you may optionally supply a callback (also known as an event handler function) as the last argument to the actxcontrol command or a cell array that contains the event handlers.
Writing Event Handlers function myclick(varargin) disp('Single click function') function my2click(varargin) disp('Double click function') function mymoused(varargin) disp('You have reached the mouse down function') disp('The X position is: ') varargin(5) disp('The Y position is: ') varargin(6) You can use the same event handler for all the events you want to monitor using the cell array pairs. Response time will be better than using the callback style. For instance h = actxcontrol('SELECTOR.SelectorCtrl.
7 ActiveX and DDE Support Additional ActiveX Client Information Releasing Interfaces Each ActiveX object can support one or more interfaces. In MATLAB, an interface is represented by an instance of the activex class.
Additional ActiveX Client Information activex object called hPlot.) In particular, this example iterates through a collection of Plot interfaces, invokes the Redraw method for each interface, and then releases each interface.
7 ActiveX and DDE Support ActiveX Data Type MATLAB Variable Array of Currency Hresult Int/Unsigned (2, 4, 8) Bool Real (Single/Double Precision) Matrix of Double Variant Array of Variant Cell Array IDispatch * activex Object Empty Unknown Void Ptr Carray Userdefined Blob Stream Storage Streamed Object Stored Object Blob Object CF Not Converted (error) Using MATLAB As a DCOM Server Client Distributed Component Object Model (DCOM) is an object distribution mechanism that allows ActiveX clients to
Additional ActiveX Client Information MATLAB has been tested as a DCOM server with Windows NT 4.0 only. Additionally, MATLAB can be used as a DCOM client with remote automation servers if the operating system on which MATLAB is running is DCOM enabled. Note If you use MATLAB as a remote DCOM server, all MATLAB windows will appear on the remote machine. MATLAB ActiveX Support Limitations The following is a list of limitations of MATLAB ActiveX support: • MATLAB only supports indexed collections.
7 ActiveX and DDE Support % MATLAB ActiveX automation client example % % Open Excel, add workbook, change active worksheet, % get/put array, save. % First, open an Excel Server. Excel = actxserver('Excel.Application'); set(Excel, 'Visible', 1); % Insert a new workbook. Workbooks = Excel.Workbooks; Workbook = invoke(Workbooks, 'Add'); % Make the second sheet active. Sheets = Excel.ActiveWorkBook.Sheets; sheet2 = get(Sheets, 'Item', 2); invoke(sheet2, 'Activate'); % Get a handle to the active sheet.
Additional ActiveX Client Information % Workbook.Saved = 1; % invoke(Workbook, 'Close'); % Quit Excel.
7 ActiveX and DDE Support MATLAB ActiveX Automation Server Support MATLAB on Microsoft Windows supports ActiveX Automation server capabilities. Automation is an ActiveX protocol that allows one application or component (the controller) to control another application or component (the server). Thus, MATLAB can be launched and controlled by any Windows program that can be an Automation Controller.
MATLAB ActiveX Automation Server Support Note The first statement above should be declared in the general declarations section in order to keep the scope throughout the application. MATLAB ActiveX Automation Methods This section lists the methods that are supported by the MATLAB Automation Server. The data types for the arguments and return values are expressed as ActiveX Automation data types, which are language-independent types defined by the ActiveX Automation protocol.
7 ActiveX and DDE Support This method retrieves a full, one- or two-dimensional real or imaginary mxArray from the named workspace. The real and (optional) imaginary parts are retrieved into separate arrays of doubles. Name. Identifies the name of the mxArray to be retrieved. Workspace. Identifies the workspace that contains the mxArray. Use the workspace name “base” to retrieve an mxArray from the default MATLAB workspace.
MATLAB ActiveX Automation Server Support void PutFullMatrix( [in] BSTR Name, [in] BSTR Workspace, [in] SAFEARRAY(double) pr, [in] SAFEARRAY(double) pi); Note The first statement above should be declared in the general declarations section in order to keep the scope throughout the application. This method puts a full, one- or two-dimensional real or imaginary mxArray into the named workspace. The real and (optional) imaginary parts are passed in through separate arrays of doubles. Name.
7 ActiveX and DDE Support Note The first statement above should be declared in the general declarations section in order to keep the scope throughout the application. MATLAB ActiveX Automation Properties You have the option of making your server application visible or not by setting the Visible property. When visible, the server window appears on the desktop, enabling the user to interact with the server application. This may be useful for such purposes as debugging.
Additional ActiveX Server Information Additional ActiveX Server Information Launching the MATLAB ActiveX Server For MATLAB to act as an automation server, it must be started with the / Automation command line argument. Microsoft Windows does this automatically when an ActiveX connection is established by a controller.
7 ActiveX and DDE Support of a dedicated server running simultaneously, since the dedicated server is not shared by multiple clients. Using MATLAB As a DCOM Server DCOM is a protocol that allows ActiveX connections to be established over a network. If you are using a version of Windows that supports DCOM (Windows NT 4.0 at the time of this writing) and a controller that supports DCOM, you can use the controller to launch MATLAB on a remote machine.
Dynamic Data Exchange (DDE) Dynamic Data Exchange (DDE) MATLAB provides functions that enable MATLAB to access other Windows applications and for other Windows applications to access MATLAB in a wide range of contexts. These functions use dynamic data exchange (DDE), software that allows Microsoft Windows applications to communicate with each other by exchanging data.
7 ActiveX and DDE Support The Service Name Every application that can be a DDE server has a unique service name. The service name is usually the application’s executable filename without any extension. Service names are not case sensitive. Here are some commonly used service names: • The service name for MATLAB is Matlab. • The service name for Microsoft Word for Windows is WinWord. • The service name for Microsoft Excel is Excel.
Dynamic Data Exchange (DDE) • Metafilepict – Metafilepict format is a description of graphical data containing the drawing commands for graphics. As a result, data stored in this format is scalable and device independent. MATLAB supports Metafilepict format for obtaining the result of a remote command that causes some graphic action to occur. • XLTable – XLTable format is the clipboard format used by Microsoft Excel and is supported for ease and efficiency in exchanging data with Excel.
7 ActiveX and DDE Support The DDE Name Hierarchy When you access MATLAB as a server, you must specify its service name, topic, and item. The figure below illustrates the MATLAB DDE name hierarchy. Topics and items are described in more detail below. items SysItems topics System Format Topics service MATLAB EngEvalString EngStringResult Engine EngFigureResult The two MATLAB topics are System and Engine.
Dynamic Data Exchange (DDE) • Format Provides a tab-delimited list of string names of all the formats supported by the server. MATLAB supports Text, Metafilepict, and XLTable. These formats are described in “Clipboard Formats” on page 7-24. • Topics Provides a tab-delimited list of the names of the topics supported by MATLAB. MATLAB Engine Topic The Engine topic allows users to use MATLAB as a server by passing it a command to execute, requesting data, or sending data.
7 ActiveX and DDE Support require only the command. Where an item name is required, use EngEvalString. In both forms, the format of the command must be Text. Most clients default to Text for DDE execute. If the format cannot be specified, it is probably Text. The table summarizes the DDE execute parameters. Item Format Command EngEvalString Text String null Text String Requesting Data from MATLAB Clients request data from MATLAB using the DDE request operation.
Dynamic Data Exchange (DDE) The table summarizes the DDE request parameters. Item Format Result EngStringResult Text String EngFigureResult Text Yes/No EngFigureResult Metafilepict Metafile of the current figure Text Character buffer, tab-delimited columns, CR/LF-delimited rows XLTable Binary data in a format compatible with Microsoft Excel Sending Data to MATLAB Clients send data to MATLAB using the DDE poke operation.
7 ActiveX and DDE Support Sub TextInput_KeyPress(KeyAscii As Integer) rem If the user presses the return key rem in the TextInput control. If KeyAscii = vbKeyReturn then rem Initiate the conversation between the TextInput rem control and MATLAB under the Engine topic. rem Set the item to EngEvalString. TextInput.LinkMode = vbLinkNone TextInput.LinkTopic = "MATLAB|Engine" TextInput.LinkItem = "EngEvalString" TextInput.LinkMode = vbLinkManual rem Get the current string in the TextInput control.
Dynamic Data Exchange (DDE) Using MATLAB As a Client For MATLAB to act as a client application, you can use the MATLAB DDE client functions to establish and maintain conversations. This figure illustrates how MATLAB communicates as a client to a server application. Server Application MATLAB DDE Client Module Conversation DDE Server Module MATLAB’s DDE client module includes a set of functions. This table describes the functions that enable you to use MATLAB as a client.
7 ActiveX and DDE Support .XLC and includes the full path if necessary. A Microsoft Excel item is a cell reference, which can be an individual cell or a range of cells. Microsoft Word for Windows topics are System and document names that are stored in files whose names end in .DOC or .DOT. A Word for Windows item is any bookmark in the document specified by the topic.
Dynamic Data Exchange (DDE) You set up and release advisory links with the ddeadv and ddeunadv functions. MATLAB only supports links when MATLAB is a client. This example establishes a DDE conversation between MATLAB, acting as a client, and Microsoft Excel. The example extends the example in the previous section by creating a hot link with Excel. The link updates matrix z and evaluates a callback when the range of cells changes.
7 ActiveX and DDE Support 7-34
8 Serial Port I/O Introduction . . . . . . . . . . . . . . . . . . . . 8-2 Overview of the Serial Port . . . . . . . . . . . . . 8-4 Getting Started with Serial I/O Creating a Serial Port Object . . . . . . . . . . . 8-18 . . . . . . . . . . . . 8-24 Connecting to the Device . . . . . . . . . . . . . . 8-27 Configuring Communication Settings . . . . . . . . 8-28 Writing and Reading Data . . . . . . . . . . . . . . 8-29 Events and Callbacks . . . . . . . . . . . . . . . . 8-48 Using Control Pins . . . .
8 Serial Port I/O Introduction What Is MATLAB’s Serial Port Interface? MATLAB’s serial port interface provides direct access to peripheral devices such as modems, printers, and scientific instruments that you connect to your computer’s serial port. This interface is established through a serial port object.
Using the Examples with Your Device Many of the examples in this section reflect specific peripheral devices connected to a PC serial port – in particular a Tektronix TDS 210 two-channel oscilloscope connected to the COM1 port. Therefore, many of the string commands are specific to this instrument. If your peripheral device is connected to a different serial port, or if it accepts different commands, you should modify the examples accordingly.
8 Serial Port I/O Overview of the Serial Port This section provides an overview of the serial port. Topics include: • What is Serial Communication? • The Serial Port Interface Standard • Connecting Two Devices with a Serial Cable • Serial Port Signals and Pin Assignments • Serial Data Format • Finding Serial Port Information for Your Platform For many serial port applications, you can communicate with your device without detailed knowledge of how the serial port works.
Overview of the Serial Port • The names, electrical characteristics, and functions of signals • The mechanical connections and pin assignments Primary communication is accomplished using three pins: the Transmit Data pin, the Receive Data pin, and the Ground pin. Other pins are available for data flow control, but are not required. Other standards such as RS-485 define additional functionality such as higher bit transfer rates, longer cable lengths, and connections to as many as 256 devices.
8 Serial Port I/O If 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, and the RD pin on each device are connected to each other. Therefore, to connect two like devices, you must use a null modem cable. As shown below, null modem cables cross the transmit and receive lines in the cable. Computer Computer TD TD Pin 3 Pin 3 Pin 2 Pin 2 DTE DTE RD RD Note You can connect multiple RS-422 or RS-485 devices to a serial port.
Overview of the Serial Port The pin assignment scheme for a 9-pin male connector on a DTE is given below. 1 2 6 3 7 4 8 5 9 The pins and signals associated with the 9-pin connector are described below. Refer to the RS-232 standard for a description of the signals and pin assignments used for a 25-pin connector.
8 Serial Port I/O Note The serial port pin and signal assignments are with respect to the DTE. For example, data is transmitted from the TD pin of the DTE to the RD pin of the DCE. Signal States Signals can be in either an active state or an inactive state. An active state corresponds to the binary value 1, while an inactive state corresponds to the binary value 0. An active signal state is often described as logic 1, on, true, or a mark.
Overview of the Serial Port The “on” and “off” states for a data signal and for a control signal are shown below. Data Signal Control Signal Signal value (Volts) 6 off on 3 0 -3 on off -6 The Data Pins Most serial port devices support full-duplex communication meaning that they can send and receive data at the same time. Therefore, separate pins are used for transmitting and receiving data. For these devices, the TD, RD, and GND pins are used.
8 Serial Port I/O The 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 data flow control – called hardware handshaking – is used to prevent data loss during transmission. When enabled for both the DTE and DCE, hardware handshaking using RTS and CTS follows these steps: 1 The DTE asserts the RTS pin to instruct the DCE that it is ready to receive data.
Overview of the Serial Port receiving a signal of a suitable frequency. CD is unasserted if the DCE is not receiving a suitable signal. RI is used to indicate the presence of an audible ringing signal. RI is asserted when the DCE is receiving a ringing signal. RI is unasserted when the DCE is not receiving a ringing signal (for example, it’s between rings). Serial Data Format The serial data format includes one start bit, between five and eight data bits, and one stop bit.
8 Serial Port I/O When reading or writing data, you may need to specify a value, which can consist of one or more bytes. For example, if you read one value from a device using the int32 format, then that value consists of four bytes. For more information about reading and writing values, refer to “Writing and Reading Data” on page 8-29. Synchronous and Asynchronous Communication The RS-232 standard supports two types of communication protocols: synchronous and asynchronous.
Overview of the Serial Port 1 The start bit is transmitted with a value of 0. 2 The data bits are transmitted. The first data bit corresponds to the least significant bit (LSB), while the last data bit corresponds to the most significant bit (MSB). 3 The parity bit (if defined) is transmitted. 4 One or two stop bits are transmitted, each with a value of 1. The number of bits transferred per second is given by the baud rate.
8 Serial Port I/O eighth 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 used since there are 28 or 256 distinct characters. The Parity Bit The parity bit provides simple error (parity) checking for the transmitted data. The types of parity checking are given below. Table 8-2: Parity Types Parity Type Description Even The data bits plus the parity bit result in an even number of 1’s. Mark The parity bit is always 1.
Overview of the Serial Port transmitting device to produce an even number of 1’s. If odd parity is selected, then the parity bit is set to 1 by the transmitting device to produce an odd number of 1’s. Finding Serial Port Information for Your Platform The ways to find serial port information for Windows and UNIX platforms are described below. Note Your operating system provides default values for all serial port settings.
8 Serial Port I/O To obtain information on the possible settings for COM1, select this port under the Ports list box and then select Settings. You can access serial port information for the Windows 95, Windows 98, and Windows 2000 operating systems with the System Properties dialog box, which is available through the Control Panel. UNIX Platform To find serial port information for UNIX platforms, you need to know the serial port names. These names may vary between different operating systems.
Overview of the Serial Port Note If the setserial -ag command does not work, make sure that you have read and write permission for the port. For all supported UNIX platforms, you can use the stty command to display or configure serial port information.
8 Serial Port I/O Getting Started with Serial I/O To get you started with MATLAB’s serial port interface, this section provides the following information: • “Example: Getting Started” illustrates some basic serial port commands. • “The Serial Port Session” describes the steps you use to perform any serial port task from beginning to end. • “Configuring and Returning Properties” describes how you display serial port property names and property values, and how you assign values to properties.
Getting Started with Serial I/O The Serial Port Session The serial port session comprises all the steps you are likely to take when communicating with a device connected to a serial port. These steps are: 1 Create a serial port object – You create a serial port object for a specific serial port using the serial creation function. You can also configure properties during object creation.
8 Serial Port I/O Configuring and Returning Properties You establish the desired serial port object behavior by configuring property values. You can display or configure property values using the set function, the get function, or dot notation. Displaying Property Names and Property Values Once the serial port object is created, you can use the set function to display all the configurable properties to the command line.
Getting Started with Serial I/O RequestToSend: [ {on} | off ] StopBits Terminator You can use the get function to display one or more properties and their current values to the command line.
8 Serial Port I/O Parity = none PinStatus = [1x1 struct] PinStatusFcn = Port = COM1 ReadAsyncMode = continuous RequestToSend = on StopBits = 1 Terminator = LF To display the current value for one property, you supply the property name to get. get(s,'OutputBufferSize') ans = 512 To display the current values for multiple properties, you must include the property names as elements of a cell array.
Getting Started with Serial I/O Note that you can configure only one property value at a time using the dot notation. In practice, you can configure many of the properties at any time while the serial port object exists – including during object creation. However, some properties are not configurable while the object is connected to the device or when recording information to disk. Refer to “Property Reference” on page 8-70 for information about when a property is configurable.
8 Serial Port I/O Creating a Serial Port Object You create a serial port object with the serial function. serial requires the name of the serial port connected to your device as an input argument. Additionally, you can configure property values during object creation. For example, to create a serial port object associated with the serial port COM1 s = serial('COM1'); The serial port object s now exists in the MATLAB workspace. You can display the class of s with the whos command.
Creating a Serial Port Object Configuring Properties During Object Creation You can configure serial port properties during object creation. serial accepts property names and property values in the same format as the set function. For example, you can specify property name/property value pairs. s = serial('COM1','BaudRate',4800,'Parity','even'); If you specify an invalid property name, the object is not created.
8 Serial Port I/O Creating an Array of Serial Port Objects In MATLAB, you can create an array from existing variables by concatenating those variables together. The same is true for serial port objects. For example, suppose you create the serial port objects s1 and s2 s1 = serial('COM1'); s2 = serial('COM2'); You can now create a serial port object array consisting of s1 and s2 using the usual MATLAB syntax.
Connecting to the Device Connecting to the Device Before you can use the serial port object to write or read data, you must connect it to your device via the serial port specified in the serial function. You connect a serial port object to the device with the fopen function. fopen(s) Some properties are read-only while the serial port object is connected and must be configured before using fopen. Examples include the InputBufferSize and the OutputBufferSize properties.
8 Serial Port I/O Configuring Communication Settings Before you can write or read data, both the serial port object and the device must have identical communication settings. Configuring serial port communications involves specifying values for properties that control the baud rate and the serial data format. These properties are given below.
Writing and Reading Data Writing and Reading Data For many serial port applications, there are three important questions that you should consider when writing or reading data: • Will the read or write function block access to the MATLAB command line? • Is the data to be transferred binary (numerical) or text? • Under what conditions will the read or write operation complete? For write operations, these questions are answered in “Writing Data” on page 8-31.
8 Serial Port I/O access to the command line, and you can issue additional commands while the read or write function executes in the background. The terms “synchronous” and “asynchronous” are often used to describe how the serial port operates at the hardware level. The RS-232 standard supports an asynchronous communication protocol. Using this protocol, each device uses its own internal clock.
Writing and Reading Data For example, since serial ports have separate read and write pins, you can simultaneously read and write data. This is illustrated below. MATLAB Serial Port I/O Hardware Write s=serial('COM1'); fopen(s) Instrument Write COM1 Read Read Writing Data This section describes writing data to your serial port device in three parts: • “The Output Buffer and Data Flow” describes the flow of data from MATLAB to the device.
8 Serial Port I/O The properties associated with writing data are given below.
Writing and Reading Data For example, suppose you write the string command *IDN? to the TDS 210 oscilloscope using the fprintf function. As shown below, the string is first written to the output buffer as six values. MATLAB s=serial('COM1'); fopen(s) fprintf(s,'*IDN?') Output Buffer *IDN? ... 6 values 6 bytes Bytes used during write Bytes unused during write The *IDN? command consists of six values since the terminator is automatically written.
8 Serial Port I/O As shown below, after the string is written to the output buffer, it is then written to the device via the serial port. Output Buffer Serial Port I/O Hardware Instrument *IDN? ... COM1 6 values 6 bytes Bytes used during write Bytes unused during write Writing Text Data You use the fprintf function to write text data to the device.
Writing and Reading Data Note that the ValuesSent property value includes the terminator since each occurrence of \n in the command sent to the device is replaced with the Terminator property value. s.Terminator ans = LF The default value of Terminator is the line feed character. The terminator required by your device will be described in its documentation. Synchronous Versus Asynchronous Write Operations.
8 Serial Port I/O Writing Binary Data You use the fwrite function to write binary data to the device. Writing binary data means writing numerical values. A typical application for writing binary data involves writing calibration data to an instrument such as an arbitrary waveform generator. Note Some serial port devices accept only text-based commands. These commands may use the SCPI language or some other vendor-specific language.
Writing and Reading Data The functions associated with reading data are given below.
8 Serial Port I/O The Input Buffer and Data Flow The input buffer is computer memory allocated by the serial port object to store data that is to be read from the device. When reading data from your device, the data flow follows these two steps: 1 The data read from the device is stored in the input buffer. 2 The data in the input buffer is returned to the MATLAB variable specified by the read function.
Writing and Reading Data Note that for a given read operation, you may not know the number of bytes returned by the device. Therefore, you may need to preset the InputBufferSize property to a sufficiently large value before connecting the serial port object. As shown below, after the data is stored in the input buffer, it is then transferred to the output variable specified by fscanf. Input Buffer MATLAB data ...
8 Serial Port I/O You can verify the number of values read from the device – including the terminator – with the ValuesReceived property. s.ValuesReceived ans = 56 Synchronous Versus Asynchronous Read Operations. You specify whether read operations are synchronous or asynchronous with the ReadAsyncMode property. You can configure ReadAsyncMode to continuous or manual.
Writing and Reading Data Asynchronous operations do not block access to the MATLAB command line. Additionally, while an asynchronous read operation is in progress, you can: • Execute an asynchronous write operation since serial ports have separate pins for reading and writing • Make use of all supported callback properties You can determine which asynchronous operations are in progress with the TransferStatus property. If no asynchronous operations are in progress, then TransferStatus is idle. s.
8 Serial Port I/O s.BytesAvailable ans = 69 You can return the data to MATLAB using any of the synchronous read functions. However, if you use fgetl, fgets, or fscanf, then you must issue the function twice since there are two terminators stored in the input buffer. If you use fread, then you can return all the data to MATLAB in one function call. out = fread(s,69); By default, fread returns numerical values in double precision arrays.
Writing and Reading Data fopen(s) 3. Write and read data – Write the *IDN? command to the instrument using fprintf, and then read back the result of the command using fscanf. fprintf(s,'*IDN?') idn = fscanf(s) idn = TEKTRONIX,TDS 210,0,CF:91.1CT FV:v1.16 TDS2CM:CMV:v1.04 You need to determine the measurement source. Possible measurement sources include channel 1 and channel 2 of the oscilloscope.
8 Serial Port I/O delete(s) clear s Example: Parsing Input Data Using strread This example illustrates how to use the strread function to parse and format data that you read from a device. strread is particularly useful when you want to parse a string into one or more variables, where each variable has its own specified format. The instrument is a Tektronix TDS 210 two-channel oscilloscope connected to the serial port COM1. 1.
Writing and Reading Data hfc = 0 par = 'NONE' tm = 'LF' 4. Disconnect and clean up – When you no longer need s, you should disconnect it from the instrument, and remove it from memory and from the MATLAB workspace. fclose(s) delete(s) clear s Example: Reading Binary Data This example illustrates how you can download the TDS 210 oscilloscope screen display to MATLAB. The screen display data is transferred and saved to disk using the Windows bitmap format.
8 Serial Port I/O fopen(s) 4. Write and read data – Configure the scope to transfer the screen display as a bitmap. fprintf(s,'HARDCOPY:PORT RS232') fprintf(s,'HARDCOPY:FORMAT BMP') fprintf(s,'HARDCOPY START') Wait until all the data is sent to the input buffer, and then transfer the data to the MATLAB workspace as unsigned 8-bit integers. out = fread(s,s.BytesAvailable,'uint8'); 5.
Writing and Reading Data Since the scope returns the screen display data using only two colors, an appropriate colormap is selected. mymap = [0 0 0; 1 1 1]; colormap(mymap) The resulting bitmap image is shown below.
8 Serial Port I/O Events and Callbacks You can enhance the power and flexibility of your serial port application by using events. An event occurs after a condition is met and may result in one or more callbacks. While the serial port object is connected to the device, you can use events to display a message, display data, analyze data, and so on. Callbacks are controlled through callback properties and callback functions. All event types have an associated callback property.
Events and Callbacks Event Types and Callback Properties The serial port event types and associated callback properties are described below. Table 8-9: Event Types and Callback Properties Event Type Associated Properties Break interrupt BreakInterruptFcn Bytes available BytesAvailableFcn BytesAvailableFcnCount BytesAvailableFcnMode Error ErrorFcn Output empty OutputEmptyFcn Pin status PinStatusFcn Timer TimerFcn TimerPeriod Break-Interrupt Event.
8 Serial Port I/O buffer. If BytesAvailableFcnMode is terminator, then the callback function executes every time the character specified by the Terminator property is read. This event can be generated only during an asynchronous read operation. Error Event. An error event is generated immediately after an error occurs. This event executes the callback function specified for the ErrorFcn property. It can be generated only during an asynchronous read or write operation.
Events and Callbacks Functions” on page 8-52, these two fields are associated with a structure that you define in the callback function header. Refer to “Debugging: Recording Information to Disk” on page 8-62 to learn about recording data and event information to a record file. The event types and the values for the Type and Data fields are given below. Table 8-10: Event Information Event Type Field Field Value Break interrupt Type BreakInterrupt Data.
8 Serial Port I/O The AbsTime Field. AbsTime is defined for all events, and indicates the absolute time the event occurred. The absolute time is returned using the clock format. day-month-year hour:minute:second The Pin Field. Pin is used by the pin status event to indicate if the CD, CTS, DSR, or RI pins changed state. Refer to “Serial Port Signals and Pin Assignments” on page 8-6 for a description of these pins. The PinValue Field.
Events and Callbacks You pass additional parameters to the callback function by including both the callback function and the parameters as elements of a cell array. For example, to pass the MATLAB variable time to mycallback time = datestr(now,0); s.BytesAvailableFcnMode = 'terminator'; s.BytesAvailableFcn = {@mycallback,time}; Alternatively, you can specify the callback function as a string in the cell array. s.
8 Serial Port I/O Example: Using Events and Callbacks This example uses the M-file callback function instrcallback to display event-related information to the command line when a bytes-available event or an output-empty event occurs. 1. Create a serial port object – Create the serial port object s associated with serial port COM1. s = serial('COM1'); 2. Connect to the device – Connect s to the Tektronix TDS 210 oscilloscope.
Events and Callbacks Read the data from the input buffer. out = fscanf(s) out = 9600;0;0;NONE;LF 5. Disconnect and clean up – When you no longer need s, you should disconnect it from the instrument, and remove it from memory and from the MATLAB workspace.
8 Serial Port I/O Using Control Pins As described in “Serial Port Signals and Pin Assignments” on page 8-6, 9-pin serial ports include six control pins. These control pins allow you to: • Signal the presence of connected devices • Control the flow of data The properties associated with the serial port control pins are given below.
Using Control Pins 1. Create the serial port objects – After the modems are powered on, the serial port object s1 is created for the first modem, and the serial port object s2 is created for the second modem. s1 = serial('COM1'); s2 = serial('COM2'); 2. Connect to the devices – s1 and s2 are connected to the modems. Since the default value for the ReadAsyncMode property is continuous, data is asynchronously returned to the input buffers as soon as it is available from the modems.
8 Serial Port I/O Write the ata command to the second modem. This command puts the modem in “answer mode,” which forces it to connect to the first modem. fprintf(s2,'ata') After the two modems negotiate their connection, you can verify the connection status by examining the value of the Carrier Detect pin using the PinStatus property. s1.
Using Control Pins fclose([s1 s2]) delete([s1 s2]) clear s1 s2 Controlling the Flow of Data: Handshaking Data flow control or handshaking is a method used for communicating between a DCE and a DTE to prevent data loss during transmission. For example, suppose your computer can receive only a limited amount of data before it must be processed. As this limit is reached, a handshaking signal is transmitted to the DCE to stop sending data.
8 Serial Port I/O Note Some devices also use the DTR and DSR pins for handshaking. However, these pins are typically used to indicate that the system is ready for communication, and are not used to control data transmission. In MATLAB, hardware handshaking always uses the RTS and CTS pins. If your device does not use hardware handshaking in the standard way, then you may need to manually configure the RequestToSend property. In this case, you should configure FlowControl to none.
Using Control Pins Example: Using Software Handshaking Suppose you want to use software flow control with the example described in “Example: Reading Binary Data” on page 8-45. To do this, you must configure the oscilloscope and serial port object for software flow control. fprintf(s,'RS232:SOFTF ON') s.FlowControl = 'software'; To pause data transfer, you write the numerical value 19 to the device. fwrite(s,19) To resume data transfer, you write the numerical value 17 to the device.
8 Serial Port I/O Debugging: Recording Information to Disk While the serial port object is connected to the device, you can record this information to a disk file: • The number of values written to the device, the number of values read from the device, and the data type of the values • Data written to the device, and data read from the device • Event information Recording information to disk provides a permanent record of your serial port session, and is an easy way to debug your application.
Debugging: Recording Information to Disk fprintf(s,'RS232?') rs232 = fscanf(s); End the serial port session. fclose(s) delete(s) clear s You can use the type command to display myfile.txt at the command line. Creating Multiple Record Files When you initiate recording with the record function, the RecordMode property determines if a new record file is created or if new information is appended to an existing record file. You can configure RecordMode to overwrite, append, or index.
8 Serial Port I/O The Record File Format The record file is an ASCII file that contains a record of one or more serial port sessions. You specify the amount of information saved to a record file with the RecordDetail property. RecordDetail can be compact or verbose. A compact record file contains the number of values written to the device, the number of values read from the device, the data type of the values, and event information.
Debugging: Recording Information to Disk Example: Recording Information to Disk This example illustrates how to record information transferred between a serial port object and a Tektronix TDS 210 oscilloscope. Additionally, the structure of the resulting record file is presented. 1. Create the serial port object – Create the serial port object s associated with the serial port COM1. s = serial('COM1'); 2. Connect to the device – Connect s to the oscilloscope.
8 Serial Port I/O char(ptop)' ans = 2.0199999809E0 The recording state is toggled from on to off. Since the RecordMode value is index, the record filename is automatically updated. record(s) s.RecordStatus ans = off s.RecordName ans = WaveForm2.txt 5. Disconnect and clean up – When you no longer need s, you should disconnect it from the instrument, and remove it from memory and from the MATLAB workspace. fclose(s) delete(s) clear s The Record File Contents The contents of the WaveForm1.
Debugging: Recording Information to Disk 5 6 7 8 9 10 MEASUREMENT:IMMED:SOURCE CH2 > 26 ascii values. MEASUREMENT:IMMED:SOURCE? < 4 ascii values. CH2 > 27 ascii values. MEASUREMENT:MEAS1:TYPE PK2PK > 25 ascii values. MEASUREMENT:MEAS1:VALUE? < 15 uchar values. 32 2e 30 31 39 39 39 39 39 38 30 39 45 30 0a Recording off.
8 Serial Port I/O Saving and Loading You can save serial port objects to a MAT-file just as you would any workspace variable – using the save command. For example, suppose you create the serial port object s associated with the serial port COM1, configure several property values, and perform a write and read operation. s = serial('COM1'); s.BaudRate = 19200; s.
Disconnecting and Cleaning Up Disconnecting and Cleaning Up When you no longer need your serial port object, you should disconnect it from the device, and clean up your MATLAB environment by removing the object from memory and from the workspace. These are the steps you take to end a serial port session. Disconnecting a Serial Port Object When you no longer need to communicate with the device, you should disconnect it from the serial port object with the fclose function.
8 Serial Port I/O Property Reference This section includes information to help you learn about serial port properties. The information is organized using these topics: • “The Property Reference Page Format” describes the organization of the property reference pages. • “Serial Port Object Properties” summarizes the properties using several categories based on how they are used. Following this section, the properties are listed alphabetically and described in detail.
Property Reference Serial Port Object Properties The serial port object properties are briefly described below, and organized into categories based on how they are used. Following this section, the properties are listed alphabetically and described in detail.
8 Serial Port I/O Read Properties BytesAvailable Indicate the number of bytes available in the input buffer InputBufferSize Specify the size of the input buffer in bytes ReadAsyncMode Specify whether an asynchronous read operation is continuous or manual Timeout Specify the waiting time to complete a read or write operation TransferStatus Indicate if an asynchronous read or write operation is in progress ValuesReceived Indicate the total number of values read from the device Callback Propertie
Property Reference Callback Properties (Continued) OutputEmptyFcn Specify the M-file callback function to execute when the output buffer is empty PinStatusFcn Specify the M-file callback function to execute when the CD, CTS, DSR, or RI pins change state TimerFcn Specify the M-file callback function to execute when a predefined period of time passes TimerPeriod Specify the period of time between timer events Control Pin Properties DataTerminal Ready Specify the state of the DTR pin FlowControl Sp
8 Serial Port I/O General Purpose Properties 8-74 ByteOrder Specify the order in which the device stores bytes Name Specify a descriptive name for the serial port object Port Indicate the platform-specific serial port name Status Indicate if the serial port object is connected to the device Tag Specify a label to associate with a serial port object Type Indicate the object type UserData Specify data that you want to associate with a serial port object
Index Symbols %val 3-5, 3-8 allocating memory 3-25 DIGITAL Visual Fortran 3-8 A ActiveX automation client 7-4 automation server 7-4, 7-16 callback 7-8 client support 7-6 collections 7-10 concepts 7-3 control containment 7-4 controller 7-16 Count property 7-10 event handler function 7-8 events 7-3 Execute method 7-16 integration 7-3 interface 7-3 custom 7-4 standard 7-4 invoking event 7-8 Item method 7-10 launching server 7-21 limitations of MATLAB support 7-13 MATLAB as automation client 7-13 methods 7-3
Index accessing elements of 5-36 assigning the empty matrix 5-41 values to 5-39 with single subscripts 5-40 comparison with MATLAB arrays 5-30 concatenation of 5-43 creating a copy 5-45 creating a reference 5-44 creating in MATLAB 5-34 creating with javaArray 5-34 dimensionality of 5-30 dimensions 5-33 indexing 5-32 with colon operator 5-37 with single subscripts 5-36, 5-38 linear arrays 5-41 passed by reference 5-49 representing in MATLAB 5-30 sizing 5-32 subscripted deletion 5-42 using the end subscript
Index calling user-defined functions 2-33 handling 8-, 16-, 32-bit data 2-23 handling arrays 2-25 handling complex data 2-21 handling sparse arrays 2-29 passing multiple values 2-13 persistent array 2-39 strings 2-11 callback 7-8 serial port object 8-48 functions 8-52 properties 8-49 caller workspace 2-37 cat using with Java arrays 5-43 using with Java objects 5-12 cell 1-9 using with Java objects 5-60 cell arrays 1-8, 2-16 converting from Java object 5-60 char 1-9 overloading toChar in Java 5-58 class u
Index UNIX 1-12 Windows 1-14, 1-16 control pins serial port object, using 8-56 convec.c 2-21 convec.f 3-22 conversation (DDE) 7-23 conversion, data in Java method arguments 5-46 copying a Java array 5-45 Count property 7-10 cxxopts.
Index ddeunadv 7-31 debugging C language MEX-files 2-47 UNIX 2-47 Windows 2-48 debugging Fortran language MEX-files UNIX 3-38 Windows 3-39 DEC Alpha declaring pointers 3-5 df50engmatopts.bat 1-19 df50opts.bat 1-18 df60engmatopts.bat 1-19 df60opts.
Index from Fortran program 4-11 engine functions 4-3–4-4 engine library 4-2 communicating with MATLAB UNIX 4-4 Windows 4-4 engOpen 4-3, 4-4 engOpenSingleUse 4-4 engopts.sh 1-19 engOutputBuffer 4-4 engPutArray 4-3 engPutMatrix 4-4 engSetVisible 4-4 engwindemo.
Index passing matrices 3-17 passing multiple values 3-19 passing scalar 2-7, 3-10 passing strings 3-12 Fortran language MEX-files 3-3 components 3-3 fread 6-4 fulltosparse.c 2-29 fulltosparse.
Index L LAPACK and BLAS functions 2-40 building MEX files for 2-44 example of 2-46 handling complex numbers 2-42 passing arguments 2-41 specifying the function name 2-41 lccengmatopts.bat 1-18 lccopts.bat 1-17 library path setting on UNIX 4-18, 6-29 linking DLLs to MEX-files 1-28 linking multiple files 2-37, 3-36 load 6-4, 6-6 using with Java objects 5-14 loading serial port objects 8-68 locating DLLs 1-32 logical arrays 1-9 M mat.h 6-9 matClose 6-7 matDeleteArray 6-7 matDeleteMatrix 6-8 matdemo1.
Index MAT-file 6-6 reading arrays from 6-6 saving arrays to 6-6 moving data between platforms 6-5–6-6 stand-alone applications 6-2, 6-3 string 1-7 using as a computation engine 4-2 variables 1-6 MATLAB add-in for Visual Studio configuring on Windows 95 and 98 1-30 configuring on Windows ME 1-30 MATLAB Automation Server supported methods 7-17 MATLAB for Visual Studio add-in 1-29 matOpen 6-7 matopts.
Index -U 1-22 -v 1-22 -V4 1-22 mex directory 1-47 mex.bat 2-9 mex.m 2-9 mex.
Index msvc60engmatopts.bat 1-18 mxSetImagData 1-40, 1-41 msvc60opts.
Index specifying 1-17 when to specify 1-17 overloading Java methods 5-54 P parity bit 8-14 passing data to Java methods 5-46 passstr.f 3-15 persistent arrays exempting from cleanup 2-38 phonebook.
Index recording information to disk 8-62 using control pins 8-56 using events and callbacks 8-48 writing and reading data 8-29 writing binary data 8-36 writing text data 8-34 serializable interface 5-14 service name 7-23, 7-24 session serial port 8-19 shared libraries directory UNIX 6-9 Windows 6-9 sincall.c 2-33 sincall.f 3-32 T temporary arrays 2-38 automatic cleanup 2-38 destroying 1-41 temporary memory cleaning up 1-41 text data reading from a device 8-39 writing to a device 8-34 timestwo.
Index watcopts.bat 1-18 watengmatopts.bat 1-19 which using with Java methods 5-25 Windows ActiveX 7-16 automation 7-16 directory organization 1-44 mex -setup 1-14 selecting compiler 1-14 Windows clipboard format Metafilepict 7-25 text 7-24 XLTable 7-25 workspace caller 2-37, 3-36 MEX-file function 2-37, 3-36 write/read failures, checking for 6-11 writing binary data to a device 8-36 text data to a device 8-34 writing event handlers 7-8 X xtimesy.c 2-14 xtimesy.f 3-19 Y yprime.c 1-12, 1-16 yprimef.