Home

MATLAB C Math Library 2.0 User's Guide

image

Contents

1. Structure Functions Function Purpose ml flsfield True if field is in structure array ml flsstruct True for structures ml f Rmfi eld Remove structure field MATLAB M File M ath Library Sparse Matrix Functions Elementary Sparse Matrices Function Purpose ml fSpdiags Sparse matrix formed from diagonals ml f Speye Sparse identity matrix ml fSprand Sparse uniformly distributed random matrix ml fSprandn Sparse normally distributed random matrix ml fSprandsym Sparse random symmetric matrix Full to Sparse Conversion Function Purpose ml fSpconvert Import from sparse matrix external format Working with NonZero Entries of Sparse Matrices Function Purpose ml f Nnz Number of nonzero matrix elements ml fNonzeros Nonzero matrix elements ml f Nz max Amount of storage allocated for nonzero matrix elements ml fSpalloc Allocate space for sparse matrix ml f Spfun Apply function to nonzero matrix elements ml f Spones Replace nonzero sparse matrix elements with ones 9 43 9 Library Routines 9 44 Reordering Algorithms Function Purpose ml f Col mmd Column minimum degree permutation ml fCol perm Column permutation ml f Dmperm Dulmage M endelsohn permutation ml fRandperm Random permutation ml f Sy mmmd Symmetric minimum degree permutation ml f Symrcm Symmetric reverse Cuthill M cK ee permutation Linear Algebra Function Pu
2. if isError fprintf stream ERROR s n msg else fprintf stream WARNING s n msg static double data 1 2 3 4 5 6 mai n mxArray matQ NULL mxArray matl NULL mxArray volatile mat2 NULL ml fSetErrorHandler MyErrorHandl er stream fopen myerrlog out w mi fEnterNewContext 0 0 ml fAssign amp matO ml fDoubleMatrix 2 3 data ml fAssign amp matl ml fDoubleMatrix 3 2 data ml fTry NULL NULL ml fAssign amp mat2 mlfRdivide matl ml fScalar 0 printf Return to try block after warning mifPrintMatrix mlfPlus mat0 mat1 eve 38 11 8 Handling Errors and W riting a Print Handler 8 12 Notes mxDestroyArray mat 2 ml f Catch mifPrintf In catch block Caught an error mif PrintMatrix mlfLasterr NULL if mat 2 mxDestroyArray mat 2 ml fEndCatch m fPrintf Now in application after catch block mxDestroyArray mat 0 mxDestroyArray mat 1 mi fRestorePreviousContext 0 0 fclose stream return EX T_SUCCESS 1 The example program declares a variable st ream that is a pointer to the output log file 2 Theerror handling routine MyError Hand er determines the type of error message and writes warnings and errors to a log file 3 The main program opens the log file named myerrl og out The program callsfclose toclose the log file before exiting
3. A colon index frequently appears in the subscript of the destination because it allows you to modify an entire row or column For example this code mi flndexAssign amp A ml fScalar 2 mlfCreateColonindex m fColon mlfScalar 1 mlfScalar 3 NULL replaces the second row of an M by 3 matrix with the vector 1 2 3 If we use the example matrix A A iS modified to contain w me e ann O wn You can also use a logical index to select multiple elements F or example the assignment statement ml flndexAssign amp A m fGt A mfScalar 5 ml fHorzcat mifScalar 17 m fScalar 17 ml fScalar 17 m fScalar 17 NULL 5 37 5 Indexing into Arrays 5 38 changes all the elements in A that are greater than 5 to17 1 4 17 2 5 17 3 17 17 Assigning to a Subarray Use two vector indices to generate a matrix destination For example let the vector indexB 1 2 and the vector indexc 2 3 Then m fAssign amp source mlfVertcat mlfHorzcat mf Scalar 1 mf Scalar 4 NULL ml fHorzcat ml fScalar 3 mf Scalar 2 NULL NULL ml flndexAssign amp A B C source copies a 2 by 2 matrix into the second and third columns of rows 1 and 2 the upper right corner of A The example matrix A becomes wn Pe Dwr won e You can also use a logical matrix as an index For example let 8 be the logical matrix SSS Orre 1 1 0 Then ml flndexAssign amp A B sour
4. mi f Print Matrix D mxDestroyArray A mxDestroyArray B mxDestroyArray C mxDestroyArray D 3 33 3 W orking with MATLAB Arrays To see the output from this code fragment see Displaying the Contents of a Cell Array on page 3 34 Using Assignment to Create Cell Arrays You can alsocreatea cell array by assigning a valuetoa location in a cell array using theml fl ndexAssi gn routine The MATLAB C Math Library creates a cell array large enough to accommodate the specified location or expands an existing array For moreinformation about using indexing with cell arrays see Chapter 5 The following example is equivalent tothe MATLAB statement A 2 2 17 Note the use of curly braces in the index subscript format string This syntax indicates you want tocreatea cell array Also note that theindex subscript format string may be passed as a standard C character string it does not need to be a MATLAB character array mxArray A NULL ml fl ndexAssi gn amp A ie We rer ee index subscript format string ml fScalar 2 index value ml fScalar 2 index value mfScalar 17 value to be assigned ml fPrintMatrix A mxDestroyArray A The following output shows the cell array created by this code fragment 17 Displaying the Contents of a Cell Array When you useml f PrintMatrix ormi fDisp to display a cell array the MATLAB C Math Library display
5. y 0 y 1 RHO y 1 y 2 ml fRestorePreviousContext 0 2 tm ym return milf Ret urnVal ue ypm 6 23 6 Calling Library Routines 6 24 Notes 1 Include mat ab h This file contains the declaration of the mxArray data structure and the prototypes for all the functions in the library st dl ib h contains the definition of EXIT SUCCESS 2 Declares GMA RHO and BETA which are the parameters for the Lorenz equations The main program sets their values and the or enz function uses them 3 Declare a static global variable MFuncTab of typeml f FuncTabEnt This variable stores a function table entry that identifies the function that ml f 0de23 calls A tableentry contains three parts a string that names the function or enz a pointer tothe function itself ml f Funcp orenz and a pointer to the thunk function that actually calls orenz lorenz_thunk_fcn_ Thetableis terminated with a 0 0 0 entry Before you call mi f 0de23 in the main program pass MFuncTab tothe function ml f Feval Tabl eSet up which adds your entry to the built in function table maintained by the MATLAB C Math Library Note that a table can contain more than one entry 4 DefinetheLorenz equations The input is a 1 by 1 array t m containing the value of t and a 3 by 1 array ym containing the values of y The result isa new 3 by 1 array ypm containing the values of the three derivatives of the equation at time
6. Purpose of mlfEnterN ew Context ml fEnterNewContext ensures that the memory allocated for temporary arrays will not be destroyed until you signal the end of the array context by calling mi f Rest orePrevi ousContext 1t ensures that bound arrays will not be destroyed by your function or any function that it calls Restoring Function Arguments to their Previous Context Each function that you write must close with a call to ml fRestorePrevi ousContext Placethe call just before ther et urn statement for your function The call operates on the output and input array arguments passed to your function It ensures that the memory allocated for those arrays is restored to its state at the time of the function call Important You can t return from your function before calling ml fRestorePrevi ousContext and you can call ml fRestorePrevi ousContext only oncein your function Prototype void ml fRestorePreviousContext int nout int nin W riting Functions Under Automated Memory Management Sample Call from Template mi f RestorePreviousContext 1 2 output_argl input_argl input _arg2 Arguments to mifRestorePreviousContext ml fRestorePreviousContext takes the number of output arguments the number of input arguments and a variable length list of the actual output and input arguments to the function You do not need to terminate the list of arguments with aNULL argument Pass the same arguments to
7. Specify 0 if there are no array input arguments declared in the same way the mai n template function does The template function on page 4 15 declares two input arguments 3 Thearray output arguments mx Array themselves in the order declared for the function In the template out put_arg1 is passed 4 Thearray input arguments mxArray themselves in the order declared for the function In the template i nput_argl andi nput_arg2 are passed Note You only list mArray andmxArray arguments For example if a function takes an argument of typechar ori nt donot includeit in the count of output and input arguments or in the list of the arguments themselves W hat Happens to the Array Arguments ml f Ent er NewContext changes the state of temporary input arrays from temporary to bound enabling them to persist for the duration of the function 4 17 4 Managing Array Memory 4 18 If they are passed as input arguments to other functions they are passed as bound arrays and not deleted Backward Compatibility Note mi fEnterNewContext recognizes when the current function is called from a function that does not use automated memory management In that context it ensures that the input arguments which are all temporary arrays are handled correctly and not subsequently deleted by ml f Rest orePrevi ousContext Output arguments that do not point toNULL or toa valid array are also handled correctly
8. The MATLAB Builtln Library General Purpose Commands Managing Variables Function Purpose ml f For mat Set output format ml fLoad Retrieve variables from disk ml f Save Save variables to disk Operators and Special Functions Arithmetic Operator Functions Function Purpose ml fLdivide Array left division ml f Minus Array subtraction ml f MI divide Matrix left division ml f Mpower Matrix power ml f Mrdi vide Matrix right division ml f Mt i mes Matrix multiplication ml f Plus Array addition ml f Power Array power ml f Rdi vide Array right division ml f Ti mes Array multiplication ml f Unarymi nus Unary minus ml f Umi nus 9 5 9 Library Routines Relational Operator Functions Function Purpose ml f Eq Equality ml f Ge Greater than or equal to gt ml f Gt Greater than gt ml f Le Less than or equal to lt ml f Lt Less than lt ml f Neq Inequality ml f Ne Logical Operator Functions Function Purpose m m f Al fAnd f Any f Not fOr True if all elements of vector are nonzero Logical AND amp True if any element of vector is nonzero Logical NOT Logical OR 9 6 The MATLAB Builtln Library Set Operators Function Purpose ml f smember True for set member ml f Set diff Set difference ml f Set xor Set exclus
9. and ml fI ndexDelete is straightforward once you understand how each forms and applies the subscript The three functions work in a similar way and support indexing into arrays of any dimension including cell arrays and structure arrays The prototypes for the three functions are mxArray mlflndexRef mxArray target_array const char index_string mxArray mlflndexAssign mxArray target_array const char index_string mxArray mlflndexDelete mxArray target_array const char index_string Usemi f ndexRef toread one or more values from an array ml fI ndexAssi gn to change one or more values in an array and ml fI ndexDel et e toremove one or more elements from an array Overview Each indexing function requires at least three arguments ml f ndexAssi gn requires at least four The first argument is the array to which the indexing operation is being applied Since both mi f I ndexAssign and ml fI ndexDel et e modify the array the first argument to these functions must be an mxArray asml fl ndexRef does not modify the array its first argument is an mxArray The second argument is a string describing the indexing operation This string uses a simplification of the MATLAB indexing syntax and field depending on what type of indexing you re doing are required but the actual values that would appear ina MATLAB index operation are replaced by s in the MATLAB C Mat
10. indicates a three dimensional subscript e Type of indexing For example the parenthesesin indicate array indexing The braces in indicate that you are accessing the contents of a cell in a cell array e Which field in a structure you re accessing field indicates you re accessing a field within a structure How to Call the Indexing Functions W hat an Indexing String Doesn t Specify Your indexing string does not specify e The values of the indices themselves The is a placeholder for actual values The values are specified as subsequent mx Ar ray arguments passed to the indexing functions e Nested subscripts Each is a placeholder for a single array index Complex Indexing Expressions In MATLAB you can write complicated indexing expressions For example this MATLAB expression B 3 7 bfield 2 1 combines cell array standard and structure indexing The expression first selects the third element of cell array B this third element must be an array Fromthis array it selects the seventh element which must bea structure with at least one field named bf i el d Fromthat structure it selects the array stored inthebfield field and then the element at position 2 1 within that array Inthe MATLAB C Math Library you can specify this entireindexing operation as a single string bfield Passing this string to any of the MATLAB C Math Library indexing functions selects that location for
11. ml f Cel Create cell array ml fCell2struct Convert cell array into structure array ml fCellhcat Horizontally concatenate cell arrays mi fl scel True for cell array 9 19 9 Library Routines Structure Functions Function Purpose ml fFieldnames Get structure field names ml fGetfield Get structure field contents ml fSetfield Set structure field contents ml f Struct Create or convert to structure array ml fStruct2cel Convert structure array into cell array Sparse Matrix Functions Full to Sparse Conversion Function Purpose ml f Find Find indices of nonzero elements ml f Ful Convert sparse matrix to full matrix ml f Sparse Create sparse matrix Working with NonZero Entries of Sparse Matrices Function Purpose ml flssparse True for sparse matrix Linear Algebra Function Purpose ml f Choline Incomplete Cholesky factorization ml f Lui ne Incomplete LU factorization 9 20 The MATLAB Builtln Library Utility Routines The MATLAB C Math Library utility routines help you perform indexing create scalar arrays and initialize and control the library environment Error Handling Function Purpose void Specify pointer to external ml fSetErrorHandler void EH const char application s error handler function bool mlfFeval Support Function Purpose void mlfFevalTabl eSetup mlfFuncTab m f UfuncTable Regist
12. 2 000 eee 5 13 Nesting Indexing Operations 0 0 0005 5 13 Specifying the Values for Indices cc eee eee 5 14 Specifying a Source Array for Assignments 5 15 Assumptions for the Code Examples 5 16 Using mifi ndexRef for One Dimensional Indexing 5 18 OVERVIEW it Hos ogden edi Meee eee wee ele td ached PAURA 5 18 Selecting a Single Element 0 00 c eee eee 5 19 Selectinga VectOr 2 kkk tee 5 19 Specifying a Vector Index with mIfEnd 5 20 Selectinga Matrix 00 cece eee 5 21 Selecting the Entire Matrix Asa Column Vector 5 21 Using mlfilndexRef for N Dimensional Indexing 5 23 OVErVIGW na ti eed odie baal ot eas e a a ee Pe eae 5 23 Selecting a Single Element 0 00 c eee eee 5 24 Selecting a Vector of Elements 0 00 e een eens 5 24 Specifying a Vector Index with mIfEnd 5 26 Selecting a Row or Column 0 0 cece eee ees 5 26 vi Contents Selecting a Matrix 0 cc eee 5 27 Selecting Entire Rows or Columns 2 000eee 5 28 Selecting an Entire Matrix 0 0 00 c cee eee ee 5 29 Extending Two Dimensional Indexing to N Dimensions 5 29 Using mifi ndexRef for Logical Indexing 5 31 OVV EW we ieee ore bee EA EE EEA ee ee 5 31 Using a Logical Matrix as a One Dimensional Index 5 32 Using Two Logical Vectors asInd
13. 9 24 arithmetic routines creating arrays 3 9 array input arguments and ml fEnterNewContext 4 17 and ml fRestorePreviousContext 4 18 array output arguments and ml fEnterNewContext 4 17 and ml fRestorePreviousContext 4 18 array return values and ml f Ret urnValue 420 arrays access routines 9 46 accessing data in 3 12 allocating 3 41 assigning values to 4 9 assignment by value 4 11 basic information functions 9 10 9 25 bound 4 27 bound vs temporary 4 14 4 21 4 27 4 30 column major storage 3 14 common programming tasks 3 41 concatenating 3 9 converting numeric to character 3 27 converting sparse to full format 3 23 converting to sparse matrix 3 19 creating cell arrays 3 30 creating multidimensional arrays 3 10 creating structures 3 37 deleting 4 11 deleting elements from 5 42 determining dimensions 3 46 determining number of nonzero elements 3 23 determining size 3 44 determining type 3 43 displaying 3 41 freeing 3 41 Index full creation 3 17 indices 5 4 initialization 7 6 initializing with C array 3 14 initializing with data 3 12 input arguments 4 17 4 19 input via ml f Load 7 3 7 6 manipulation functions 9 11 9 26 memory allocation 4 2 multidimensional 3 6 multidimensional character arrays 3 27 numeric arrays 3 4 of characters 3 25 output arguments 4 17 4 19 output via ml fSave 7 2 7 6 pointer to data 3 12 preparing function arguments for a new con text 4 16 resto
14. E xtending Two Dimensional Assignment to N Dimensions on page 5 39 to learn how to work with arrays of dimension greater than two Assumptions for the Code Examples on page 5 16 explains the conventions used in the examples Overview Use the function ml f ndexAssign to make assignments that involve indexing The arguments to ml f ndex Assi gn consist of a destination array an index string the index arrays themselves and the source array The subscript specifies the elements that are to be modified in the destination array The source array specifies the new values for those elements You can use five different kinds of indices e Scalar e Vector e Matrix e Colon e Logical 5 36 Using mlflndexAssign for Assignments The examples below do not present all possible combinations of these index types Note Thesize of the destination mxArray after the subscript has been applied and the size of the source mx Array must be the same Assigning to a Single Element Use one or two scalar indices to assign a value toa single element in a matrix For example ml flndexAssign amp A mlfScalar 2 mlfScalar 1 ml fScalar 17 changes the element at row 2 and column 1 to the integer 17 Here both the source and destination after the subscript has been applied are scalars and thus the same size Assigning to Multiple Elements Use a vector index to modify multiple elements in a matrix
15. If you want to change where or how the library s output appears you must provide an alternate print handler Providing Your Own Print Handler Instead of callingprintf directly the MATLAB C Math Library calls a print handler when it needs to display an error message or warning The default print handler used by the library takes a singleargument aconst char the message to be displayed and returns voi d The default print handler is static void DefaultPrintHandler const char s printf s s The routine sends its output to C s stdout using the pri nt f function If you want to perform a different style of output you can write your own print handler and register it with the MATLAB C Math Library Any print handler that you write must match the prototype of the default print handler a single const char argument and a voi d return Defining a Print Handler Toregister your function and change which print handler the library uses you must call the routine ml f Set PrintHandler ml f Set PrintHandler takes a single argument a pointer to a function that displays the character string and returns voi d void mfSetPrintHandler void PH const char Output to a GUI When you write a program that runs in a graphical windowed environment you may want to display printed messages in an informational dialog box The next two sections illustrate how to provide an alternate print handler under the X Windo
16. Note Any changes that you make to the local options filecompopts bat will be overwritten the next time you run mbuil d setup If you want to make your edits persist through repeated uses of mbui d setup you must edit the master file itself The master options files are located in lt mat l ab gt bin Table 1 4 Compiler Options Files on the PC Compiler Master Options File Borland C C Version 5 0 bcccompp bat Borland C C Version 5 2 bcc52compp bat Borland C C Version 5 3 bcc53compp bat Microsoft Visual C C H Version 4 2 msvccompp bat Microsoft Visual C C 4 Version 5 0 msvc50compp bat Microsoft Visual C C Version 6 0 msvc60compp bat Watcom C C Version 10 6 wat ccompp bat Watcom C C Version 11 wat 11ccompp bat Combining Customized C and C Options Files The options files for mb ui d have changed as of MATLAB 5 3 Release 11 so that the same options file can be used to create both C and C stand alone applications If you have modified your own separate options files to create C and C applications you can combine them into one options file Tocombine your existing options files into one universal C and C options file 1 Copy from the C options file to the C options file all lines that set the variables COMPFLAGS OPTI MFLAGS DEBUGFLAGS andLINKFLAGS 2 IntheC options file within just those copied lines from step 1 replace all occurrences of COMPFLAGS with CPPCOMPFLAGS OPT
17. Passing Any Number of Inputs 0 000 c eee n eens 6 7 How Pure Varargin Functions Differ 055 68 Passing Any Number of Outputs 0 00 c eae enee 6 9 Constructing an mlfVarargoutList 05 6 10 How Pure Varargout Functions Differ 0 6 12 Summary of Library Calling Conventions 6 13 Exceptions to the Calling Conventions 6 14 Example Program Calling Library Routines ex3 c 6 14 How to Call Operators 0 00 c eee eee 6 19 Passing Functions As Arguments to Library Routines 6 20 How Function Functions Use mlfFeval 6 20 How mlfFeval Works 1 0 0 0 00 cece ee eee eee eee 6 21 Extending the mifFeval Table 00 eee ees 6 21 Writing a Thunk Function 00000 e ee eee 6 22 Example Program Passing Functions As Arguments ex4 c 6 22 Output si f eatin Seva dee Doe ee Gee ete AP ee 631 Replacing Argument Lists with a Cell Array 6 32 Positioning the Indexed Cell Array 2 4 6 33 Exception for Built In Library Functions 6 33 Importing and Exporting Array Data 7 OVER VOW ioc cic berate ek NE Ser BR E ER a ie 7 2 Using mlfSave to Write Data toa File 0 7 2 Using mifLoad to Read Data froma File 7 3 Example Program Saving and Loading Data ex5 c 7 4 Handling Errors and Wri
18. lt stdlib h gt 1 include matlab h main 2 mxArray x NULL y NULL z NULL mxArray a NULL b NULL c NULL mfEnterNewContext 0 0 fAssign amp x ml fRand ml fScalar 4 mfScalar 4 NULL fAssign amp y ml fMagic mlfScalar 7 fAssign amp z mlfEig NULL x NULL 33 Save and name the variables Q mi fSave mxCreateString ex5 mat w ERT X y y teh Zi NULL Load the named variables G ml fLoad mxCreateString ex5 mat PTs amp a myn amp b FA amp c NULL 7 4 Overview Check to be sure that the variables are equal if ml fTobool mlflsequal a x NULL amp amp m fTobool mlflsequal b y NULL amp amp m fTobool miflsequal c z NULL m fPrintf Success all variables equal n else mfPrintf Failure loaded values not equal to saved values n mxDestroyArray mxDestroyArray mxDestroyArray mxDestroyArray mxDestroyArray mxDestroyArray OOD DWN e XX mi fRestorePreviousContext 0 0 return EXIT_ SUCCESS N otes 1 Include mat ab h This file contains the declaration of the mx Array data structure and the prototypes for all the functions in the library st dl ib h contains the definition of EXI T_ SUCCESS 2 Declare and initialize variables x y andz will be written to the MAT file using ml f Save a b andc will store the data read from the MAT file by ml fLoad 3 Ass
19. mifHorzcat mfScalar 2 mlfScalar 5 mlfScalar 8 NULL performs the same operation asA 2 5 8 in MATLAB and selects the second fifth and eighth elements of the matrix A 25 8 Because the index is a 1 by 3 row vector the result is also a 1 by 3 row vector The code ml fAssign amp B miflndexRef A mfVertcat mlfScalar 2 mfScalar 5 mfScalar 8 NULL selects the same elements of A but returns the result as a column vector because the call to ml f Vert cat produced a column vector 2 5 8 A 2 5 8 in MATLAB performs the same operation Note the semicolons 5 19 5 Indexing into Arrays 5 20 Specifying a Vector Index with mlfEnd Sometimes you don t know how large an array isin a particular dimension but you want to perform an indexing operation that requires you to specify the last element in that dimension In MATLAB you can use the end function to refer to the last element in a given dimension For example A 6 end selects the elements from A 6 totheend of the array The MATLAB C Math Library s ml f End function corresponds to MATLAB s end function Given an array a dimension 1 row 2 column 3 page and so on and the number of indices in the subscript ml f End returns asa 1 by 1 array the index of the last element in the specified dimension You can then use that scalar array to generate a vector index Given the row dimension for a vector or scalar array ml f End
20. returns the number of columns Given the column dimension for a vector or scalar array it returns the number of rows For a matrix ml fEnd treats the matrix like a vector and returns the number of elements in the matrix Note that the number of indices in the subscript corresponds to the number of index arguments that you pass toml f ndexRef This C code selects all but the first five elements in matrix A just as A 6 end does in MATLAB mxArray end_index NULL B NULL ml fAssign amp end_index ml f Colon ml fScalar 6 mfEnd A mfScalar 1 mfScalar 1 NULL ml fAssign amp B miflndexRef A end_index The second argument ml f Scalar 1 toml f End identifies the dimension where ml f End is used here the row dimension The third argument ml fScalar 1 indicates the number of indices in the subscript for one dimensional indexing it is always one This code selects these elements from matrix A 67 8 9 Using mlflndexRef for O ne Dimensional Indexing Selecting a Matrix Use a matrix index to select a matrix A matrix index works just like a vector index except the result is a matrix rather than a vector For example let B be the index matrix 12 32 Then ml fAssign amp X miflndexRef A B 12 3032 Note that the example matrix A was chosen so that ml flndexRef A X equals x for all types of one dimensional indexing This is not generally the case For example if A
21. which copies a master options file to your local MATLAB directory typically HOME mat ab mbuildopts sh 1 15 1 G etting Ready 1 16 If you need to see which options mbui d passes to your compiler and linker use the verbose option v asin mbuild v filenamel filename2 to generate a list of all the current compiler settings Tochange the options use an editor to make changes to your options file which isin your local MATLAB directory Your local MATLAB directory isa user specific MATLAB directory in your individual home directory that is used specifically for your individual options files You can also embed the settings obtained from the verbose option of mb ui d into an integrated development environment I DE or makefile that you need tomaintain outside of MATLAB Often however it is easier tocall mb ui d from your makefile See your system documentation for information on writing makefiles Note Any changes made tothe local options file will be overwritten if you execute mbuild setup again To make the changes persist through repeated uses of mbui d setup you must edit the master file itself lt matlab gt bin mbuildopts sh Temporarily Changing the Compiler To temporarily change your C or C compiler use the f option asin mbuild f lt options file gt filename c filename The f option tells the mbui d script to use the options file lt file gt If lt file gt is not in t
22. 1 13 1 13 1 16 1 18 1 21 1 22 1 22 1 28 1 29 1 32 1 33 1 34 1 36 1 G etting Ready Introduction The MATLAB C Math Library makes the mathematical core of MATLAB available to application programmers The library is a collection of more than 400 mathematical routines written in C Programs written in any language capable of calling C functions can call these routines to perform mathematical computations The MATLAB C Math Library is based on the MATLAB language The mathematical routines in the MATLAB C Math Library areC callable versions of features of the MATLAB language However you do not need to know MATLAB or own a copy of MATLAB to usethe MATLAB C Math Library If you have purchased the MATLAB C Math Library then the only additional software you need is an ANSI C compiler Who Should Read This Book This book assumes that you are familiar with general programming concepts such as function calls variable declarations and flow of control statements You also need to be familiar with the general concepts of C and linear algebra The audience for this book is C programmers who need a matrix math library or MATLAB programmers who want the performance of C This book will not teach you how to program in either MATLAB or C New MATLAB C Math Library Features Version 2 0 supports these new features e Over 60 new functions Data types Multidimensional arrays Cell arrays MAT
23. 2 1 ml fl ndexAssign 45 amp X 9 7 api et aa ml fScalar 2 ml fScalar l ml fScalar 9 is Replace elements 1 and 4 X 1 4 ml fl ndexAssi gn 8 5 with 8 one dimensional amp X 6 8 indexing 2 ml f Horzcat NULL ml f Horzcat NULL he ml fScalar 1 ml fScalar 4 ml fScalar 8 ml fScalar 8 5 60 Calling Library Routines Overview How to Call MATLAB Functions Returning One Output Argument and Passing Only Required Input Arguments Passing Optional Input Arguments Passing Optional Output Arguments Passing Optional Input and Output Arguments Passing Any Number of Inputs re Passing Any Number of Outputs Summary of Library Calling Conventions i Example Program Calling Library Routines ex3 9 How to Call Operators Passing Functions As Arguments to Library Routines How Function Functions Use mlfFeval his How mlfFeval Works Extending the mIfF eval Table Example Program Passing Functions As Arguments ex4 9 Replacing Argument Lists with a Cell Array 6 2 6 3 6 4 6 5 6 7 6 9 6 13 6 14 6 19 6 20 6 20 6 21 6 21 6 22 6 32 6 Calling Library Routines Overview The MATLAB C Math Library includes over 400 functions Every routinein the library works the same way as its corresponding routinein MATLAB This chapter describes the calling conventions that apply to the library functions including how t
24. 4 Register the error handler with the MATLAB C Math Library with this call toml fSetErrorHandler Handling Errors Output The program produces this output In MyErrorHandler WARNING Divide by zero Logging the warning to a file Returning to try block after warning ln MyErrorHandler Logging the error to a file In catch block Caught an error Matrix dimensions must agree Now in application after catch block 8 13 8 Handling Errors and W riting a Print Handler 8 14 Defining a Print Handler In the past when there were only character based terminals input and output were very simple programs used scanf for input and printf for output Graphical user interfaces GUIs and windowed desktops make input and output routines more complex The MATLAB C Math Library is designed to run on both character based terminals and in graphical windowed environments Simply using printf or a similar routine is fine for character terminal output but insufficient for output in a graphical environment The MATLAB C Math Library performs some output in particular it displays error messages and warnings but performs no input To support programming in a graphical environment the library allows you to determine how thelibrary displays output The MATLAB C Math Library s output requirements are very simple The library formats its output into a character string internally and then calls a function that prints the single string
25. 42 ml flndexRef 5 18 5 23 5 31 nesting indexing operations 5 13 specifying source array 5 15 specifying target array 5 11 specifying values for indices 5 14 use of index string 5 11 indices how MATLAB calculates 5 9 logical 5 31 initializing array output arguments 4 22 4 29 local array variables 4 22 4 29 Microsoft Windows 8 18 X Window system 8 17 initializing arrays 3 12 input arguments optional 6 4 6 5 ml f Load 7 3 7 6 input arguments and ml f EnterNewContext 4 17 and ml f RestorePreviousContext 4 19 Index installing the library PC details 1 10 UNIX details 1 10 with MATLAB 1 9 without MATLAB 1 10 i bmat dll A 7 i bmat ext A 4 ibmatlb dll A 7 i bmatl b ext A 4 i bmatl b h A 5 A 8 i bmi dll A 7 i bmi ext A 4 ibmmfile dll A 8 i bmmfile ext A 4 i bmmfile h A 5 A 8 i bmx dll A 8 i bmx ext A 4 libraries i bmat location Microsoft Windows A 7 UNIX A 4 i bmat b location Microsoft Windows A 7 UNIX A 4 i bmi location Microsoft Windows A 7 UNIX A 4 i bmmf ile location Microsoft Windows A 8 UNIX A 4 i bmx location Microsoft Windows A 8 UNIX A 4 i but location Microsoft Windows A 8 UNIX A 4 Microsoft Windows A 7 UNIX A 4 library path 1 17 libut dll A 8 libut ext A 4 linear algebra 9 20 9 44 linear equations 9 13 9 31 9 44 link library order 1 36 local array variables paradigm for using 4 8 logical flag 5 31 logical functions 9 8 9 24 logical
26. 5 6 7 8 9 This C array when used to initialize a MATLAB array produces the desired result Example Program Creating Numeric Arrays ex 1 c As an illustration this program creates two arrays and then prints them The primary purpose of this example is to present a simple yet complete program The code therefore demonstrates only one of the ways to create an array Each of the numbered sections of codeis explained in more detail below Y ou can find the code for this examplein the lt mat ab gt extern examples cmath directory on UNIX systems and in the lt mat ab gt extern exampl es cmath directory on PCs where lt mat ab gt represents the top level directory of your installation 3 15 3 W orking with MATLAB Arrays exl c include lt stdio h gt include lt stdlib h gt include lt string h gt D include matlab h static double real_data 1 2 3 4 5 6 static double cplx_data 7 8 9 10 11 12 int main Declare two matrices and initialize to NULL mxArray matQ NULL mxArray matl NULL Enable automated memory management mfEnterNewContext 0 0 Create the matrices and assign data to them ml fAssign amp mat0 milf DoubleMatrix 2 3 real_data NULL ml fAssign amp matl ml fDoubleMatrix 3 2 real_ data cplx_data Print the matrices O ml fPrintMatrix mat0 ml fPrintMatrix mat1 Free the matrices G mxDestr
27. B C equals 4 This is tricky B the row index selects row 1 but does not select row 2 C the column index does not select column 1 but does select column 2 Thereis only one element in array A in both row 1 and column 2 the element 4 Using One Colon Index and One Logical Vector as Indices This type of indexing is very similar to the two vector case Here however the colon index selects all of the elements in a row or column acting like a vector of ones the same size as the dimension to which it is applied The logical index works just like a nonlogical index in terms of size For example let the index vector B ogical 1 0 1 Then miflndexRef A mlfCreateCol onl ndex B 5 33 5 Indexing into Arrays 5 34 equals wn e wo on The colon index selects all rows and 8 selects the first and third columns in each row The result is the intersection of these two sets that is the first and third columns of the matrix For comparison ml fAssign amp X m flndexRef A B ml fCreateCol oni ndex equals 147 3 6 9 B selects the first and third rows and the colon index selects all the columns in each row The result is the intersection of the sets selected by each index that is the first and third rows of the matrix Using a Scalar and a Logical Vector Let matrix X bea 4 by 4 magic square X magic 4 16 2 3 7 13 5 11 10 8 9 7 6 12 4 14 15 1 Let 8 bea logical matr
28. Compile only do not link D lt name gt Define C preprocessor macro lt name gt f lt file gt Use lt file gt as the options file lt file gt is a full pathname if it is not in the current directory 9 Build an executable with debugging symbols included hfel p Help prints a description of mbui d and lt pat hname gt lang lt language gt the list of options Include lt pat hname gt in thelist of directories to search for header files Override language choice implied by file extension lt l anguage gt c for C cpp for C This option is necessary when you use an unsupported file extension or when you pass all o files and libraries Building a Stand Alone Application on Microsoft W indows Table 1 5 mbuild Options on Microsoft Windows Continued Option Description link lt target gt Specify output type lt target gt exe for an executable outdir lt dirname gt output lt name gt setup U lt name gt V shared for DLL exe is the default See Building Shared Libraries on page 1 33 for an example Place any generated object resource or executable files in the directory lt di rname gt Do not combine this option with output if the out put option gives a full pathname Create an executable named lt name gt An appropriate executable extension is automatically appended Build an optimized executable Set up the default compiler and l
29. Data from a File 7 3 Example Program Saving and Loading Data ex5 c 7 4 7 Importing and Exporting Array Data Overview The MATLAB C Math Library provides two routines ml f Load and ml f Save which let you import and export array data in MAT files Thearray data is stored in a special binary file format that ensures efficient storage and cross platform portability Since MATLAB also reads and writes MAT files you can use ml fLoad and ml fSave tosharedata with MATLAB applications or with other applications developed with the MATLAB C or C Math Library A MAT fileis a binary machinedependent file However it can be transported between machines because of a machine signature in its file header The MATLAB C Math Library checks the signature when it loads variables from a MAT file and if a signature indicates that a file is foreign performs the necessary conversion TheMATLAB C Math Library functions ml f Save andml f Load implement the MATLAB oad andsave functions Note however that not all the variations of the MATLAB oad andsave syntax are implemented for the MATLAB C Math Library Using mlfSave to Write Data to a File Using ml f Save you can save the data within mx Array variables to disk The prototype for ml f Save is void mlfSave mxArray file const char mode wheref i e points toan mx Array containingthenameof the MAT file and mode points to a string that indi
30. Enter a number 333 Enter a second number 444 333 and 444 share common factor s 3 37 A second run illustrates the alternate output Enter a number 11 Enter a second number 4 11 and 4 are relatively prime 2 W riting Programs Working with MATLAB Arrays Overview Supported MATLAB Array Types MATLAB Array C Data Type Working with MATLAB Numeric ae Creating Numeric Arrays Initializing a Numeric Array with Data Example Program Creating Numeric Arrays ex1 Working with MATLAB Sparse Matrices Creating a Sparse Matrix Converting a Sparse Matrix to F ull M atrix Format Evaluating Arrays for Sparse Storage Working with MATLAB Character Arrays Creating MATLAB Character Arrays x Accessing Individual Strings in an Array of Strings Working with MATLAB Cell Arrays Creating Cell Arrays ee Displaying the Contents of a Cell Array Working with MATLAB Structures Creating Structures ts aad Ss Performing Common Array Programming Tasks Allocating and Freeing MATLAB Arrays Displaying MATLAB Arrays Determining Array Type or Determining the Size of an Array Determining the Shape of an Array 3 2 3 2 3 4 3 5 WEE 3 15 3 18 3 19 3 23 3 23 3 25 3 26 3 29 3 30 3 30 3 34 3 37 3 38 3 41 3 41 3 41 3 43 3 44 3 46 3 W orking with MATLAB Arrays 3 2 Overview Tousethe routines in the MATLAB C Math Library you mus
31. Field The simplest operation on a structure is retrieving data from one of the structure fields To extract thei mage field from the second structurein a structure array use m fAssign amp str miflndexRef images image mlfScalar 2 Indexing into MATLAB Structure Arrays image imagelist 2 image performs the same operation in MATLAB Accessing the Contents of a Structure Field A structure field may contain another array By performing additional indexing operations you can access the data stored in that array You must specify the field name and the type of indexing to perform on the array stored in that field e Use array subscripting if the field contains an array e Use cell array subscripting if the field contains a cell array For example this code retrieves the first row of the image in the third structure ml fAssign amp n miflndexRef images image ml fScalar 3 m fScalar l ml fCreateCol onl ndex n x 3 image 1 performs the same operation in MATLAB Assigning Values to a Structure Field Toassign an initial value to a field creating the field if it doesn t exist or modify the value of an existing field use ml f ndexAssi gn For example to change the description field of the seventeenth image you d write this code ml fl ndexAssi gn amp i mages description m fScalar 17 mxCreateString Cloned sheep embryo 1 Note that you must pass the arr
32. Functions Use mlfFeval A function function uses ml f Feval to execute the function passed to it For instance ml f Ode23 in Example Program Passing Functions As Arguments ex4 c on page 6 22 calls ml f Feval to execute the function or enz The function function passes the name of the function to be executed toml f Feval along with the arguments required by the function In this example the string array containing orenz is passed toml f Feval along with the other arguments that were passed to ml f 0de23 Because the functions passed toml f Feval take different numbers of input and output arguments ml f Feval uses a non standard calling convention Instead of listing each argument explicitly ml f Feval works with arrays of input and output arguments allowing it to handle every possible combination of input and output arguments on its own The prototype for mi f Feval is mxArray mlfFeval mlfVarargoutList varargout void mxfn int nihs mxArray plhs int nrhs mxArray prhs gaye Each function function therefore constructs an array of input arguments pr hs and an array of output arguments pl hs and then passes those two arrays along with the number of arguments in each array nr hs andn hs and the name of the function name toml f Feval which executes the function 6 20 Passing Functions As Arguments to Library Routines How mlfFeval Works ml f Feval
33. MATLAB C Math Library code is mlflndexAssign amp A mlfScalar 1 mlfScalar 2 mfCellhcat vector NULL Because this assignment uses parentheses instead of braces it is an assignment between cells which means the source array on the right hand side of the assignment operator must bea cell array as well The first line of C code creates a cell array from our initial vector of primes Deleting Elements from a Cell Array Cell arrays follow the same rules as numeric arrays and structure arrays as you ll see in the next section for element deletion You can delete a single 5 49 5 Indexing into Arrays 5 50 element from a cell array or an entire dimension element for example a row or column of a two dimensional cell array or a row column or page of a three dimensional cell array In MATLAB you delete elements by assigning to them In the MATLAB C Math Library you use ml f ndexDel et e which takes exactly the same type of arguments as ml f I ndexRef Deleting a Single Element In order to delete a single element from an array of any type you must use one dimensional indexing Deleting a single element from a two dimensional cell array collapses it into a vector cell array For example deleting the 2 1 element of N the complex number 2 4i produces a three element cell array N 2 refers to element 2 1 of N using one dimensional indexing Therefore you d write N 2 in MATLAB a
34. MATLAB function you can pass any number of input arguments to the function starting at that position in the argument list MATLAB takes the arguments you pass and stores themin a cell array which can hold any size or kind of data Thevar ar gi n function then treats the elements of that cell array exactly as if they were arguments passed to the function Whenever you see an ellipsis at the end of the input argument list in a MATLAB syntax description the function is avarargin function For example the syntax for the MATLAB function cat includes the following specification in the online MATLAB Function Reference B cat dim Al A2 A3 A4 6 7 6 Calling Library Routines 6 8 cat accepts any number of arguments Thedi m and A1 arguments tocat are required You then concatenate any number of additional arrays along the dimension di m For example this call concatenates six arrays along the second dimension B cat 2 Al A2 A3 A4 A5 A6 TheC language supports functions that accept variable length argument lists MATLAB var ar gi n functions translate easily into these functions The variable number of arguments are always specified at the end of the argument list and are indicated in the function prototype as an ellipsis For example the prototype for the ml f Cat function in the MATLAB C Math Library is mxArray mlfCat mxArray dim mxArray Al Though C uses its own mechanism different from
35. PP SOAHDWFPWNYNPFYP RYH DOO Y NY WwW AON CO Wo Rr Pe w w Ne y2 984 318 995 678 404 117 852 632 411 402 415 116 576 014 478 948 429 960 618 2545 000 762 147 611 902 943 430 439 2 0 0 2 TA 3h 3 23 4 3h 3 3 3 38 3 23 4 4 p 1 Qi 12 13 15 16 215 14 12 y3 951 498 946 043 836 409 778 972 029 989 899 845 807 796 833 964 245 761 642 097 461 143 971 464 150 721 014 993 6 31 6 Calling Library Routines Replacing Argument Lists with a Cell Array In MATLAB you can substitute a cell array for a comma separated list of MATLAB variables when you pass input arguments to a function MATLAB treats the contents of each cell as a separate input argument To trigger this functionality you specify multiple values by indexing into the cell array with for example the colon index or a vector index For example the MATLAB expression T 1 5 when passed as an input argument is equivalent to a comma separated list of the contents of the first five cells of T Simply passing the cell arrayT produces an error The MATLAB C Math Library also supports the expansion of the contents of a cell array into separate input arguments for library functions For functions that implement MATLAB varargi n functions you use the indexing function ml fI ndexRef and
36. Spconvert format Create a sparse identity matrix ml f Speye Extract a band or diagonal group of milf Spdi ags elements from a matrix and create a sparse matrix Determine the number of nonzero ml f Nnz elements in a numeric matrix W orking with MATLAB Sparse M atrices Table 3 2 Sparse Matrix Routines Continued To Use Determine if a matrix has any ml fAny or nonzero elements or if all elements ml f All are nonzero Determine the amount of storage ml f Nzmax allocated for the nonzero elements of a sparse matrix Apply a function to all the nonzero ml f Spfun elements of a sparse matrix Creating a Sparse Matrix To create a sparse matrix call the MATLAB C Math Library ml f Spars e routine Using this routine you can create sparse arrays in two ways e By converting an existing array to sparse format e By specifying the data and the location of the data in the sparse array Converting an Existing Matrix into Sparse Format Tocreate a sparse matrix from a standard numeric array usetheml f Spars e routine ml f Sparse converts the numeric array into sparse storage format Toillustrate the following code fragment creates a 12 by 12 identity matrix Of the 144 elements in this matrix only 12 elements have nonzero values In full format all 144 are allocated storage When this identity matrix is converted to sparse matrix format only the 12 nonzero elements have storage
37. a mbui d treats these lines as comments and ignores them mbui Id merges multiple exports files into one master exports list F or example givenfile2 exports as times2 times 3 andfilel c as int times2 int x return 2 x int times3 int x return 3 x The command mbuild link shared filel c file2 exports creates a shared library named f i e1 ext whereext isthe platform dependent shared library extension F or example on the PC it would becalledfilel dll 1 33 1 G etting Ready Troubleshooting mbuild This section identifies some of the more common problems that may occur when configuring mbui d to create applications Options File Not Writable When you run mbuil d setup mbuil d makes a copy of the appropriate options file and writes some information to it If the options file is not writable you are asked if you want to overwrite the existing options file If you choose to do so the existing options file is copied to a new location and a new options file is created Directory or File Not Writable If a destination directory or fileis not writable ensure that the permissions are properly set In certain cases make sure that the file is not in use mbuild Generates Errors On UNIX if you run mbuild filename and get errors it may be because you are not using the proper options file Run mbui ld setup to ensure proper compiler and linker settings Compiler and or Lin
38. a C style string True for a character array True if mxArray iS amember of the specified class True if data is complex True if mxArray represents its data as double precision floating point numbers True if mxArray is empty True if value is finite True if value is infinite True if mxArray represents its data as signed 8 bit integers True if mxArray represents its data as signed 16 bit integers Array Access and Creation Library Array Access Routines Continued Function Purpose mxi sl nt 32 True if mxArray represents its data as signed 32 bit integers mx sLogical True if mxArray is Boolean mxi s NaN True if value is Not a N umber mx sNumeric mxl sSingle mxi sSparse mxi sStruct mx Mal loc mxReall oc mxSet Cel mxSet Data mxSet Di mensi ons mxSet Field mxSet Fiel dByNumber mxSet l magData mxSetlr mxSet c mxSet Logical True if mxArray iSnumeric or a string True if mxArray represents its data as single precision floating point numbers Inquire if an mx Array is sparse Always false for the MATLAB C Math Library True if a structure mxArray Allocate dynamic memory using MATLAB s memory manager Reallocate memory Set the value of one cell Set pointer to data Modify the number of dimensions and or the size of each dimension Set a field value of a structure array given a field name and an index Set a field valuein a structure array given
39. are in the lt matlab gt extern include directory mbui d dynamically generates import libraries fromthe def files Before running a stand alone application you must ensure that the directory containing the DLLs is on your path The directory must be on your operating system PATH environment variable On Windows 95 set the value in your autoexec bat file on Windows NT usethe Control Panel to set it Building a Stand Alone Application on Microsoft W indows Running Your Application You can now run your stand alone application by launching it from the command line For example exl 1 3 5 2 4 6 1 0000 7 0000i 4 0000 10 0000i 2 0000 8 00001 5 0000 11 00001 3 0000 9 00001 6 0000 12 00001 mbuild Options The mbui ld script supports various options that allow you to customize the building and linking of your code Many users do not need to know any additional details of the mbui d script they use it in its simplest form The following information is provided for those users who require more flexibility with the tool 1 29 1 G etting Ready Thembui I d syntax and options are mbuild options fil enamel filename2 Table 1 5 mbuild Options on Microsoft Windows Option Description f il ename Replace f i ename on the mbui d command line with the contents of filename fil ename is a response file i e a text file that contains additional command line options to be processed
40. assigns the array returned by ml f Cos toY a pointer toan mArray ml f Assi gn marks the assigned array as a bound array You are responsible for deleting the bound arrays that result from a call tomi fAssign Note Always call mi f Assi gn when you want an array to persist Do not use the assignment operator Becoming accustomed to programming with ml f Assi gn rather than the assignment operator is the biggest adjustment you ll need to make when programming with automated memory management Assigning a Value to an Array Destroys Its Previous Value If you assign a value to an array variable that already has a value ml f Assi gn destroys the variable s previous value before assigning the new value You do not need to call mxDestroyArray before calling ml f Assi gn For example in these two statements m fAssign amp c mfScalar 5 ml fAssign amp c mfScalar 6 ml f Assi gn destroys the contents ofc the scalar array 5 before assigning the scalar array containing 6 toc Exception J ust as the MATLAB language preserves the value of an array passed as an input argument across a function call ml f Assi gn leaves an array value unchanged does not make a copy if the array is a bound not temporary input array argument on entry to the function For example given this function mxArray func mxArray a mxArray b and this call within the function m fAssign amp b mlfScalar 5 ml f Ass
41. bbcew td tne nde ing late dine A ee els 1 22 Configuring for C or CH oo teens 1 22 Locating Options Files 0 cee eee eee 1 22 Systems with Exactly One C C Compiler 1 23 Systems with More than One Compiler 1 23 Changing the Default Compiler 000e eee 1 24 Modifying the Options File 0 00 e een eens 1 26 Combining Customized C and C Options Files 1 27 Temporarily Changing the Compiler 1 28 Verifying mbuild 2 0 0 0 02s 1 28 Shared Libraries DLLS 0 000 c eee eee 1 28 Running Your Application 000 eee ee eee 1 29 mbuild Options 0 000 c eee ee 1 29 Distributing Stand Alone Microsoft Windows Applications 1 32 Building Shared Libraries 1 33 Troubleshooting mbuild 0055 1 34 Options File Not Writable 000000000 eae 1 34 Directory or File Not Writable 1 34 mbuild Generates Errors 0 0 0 0 cece eee 1 34 Compiler and or Linker Not Found 055 1 34 mbuild Not a Recognized Command 00000 1 34 Cannot Locate Your Compiler PC 2 0 005 1 34 Internal Error When Using mbuild setup PC 1 35 Verification of mbuild Fails 00000 1 35 Building on Your Own 00 0c cece ees 1 36 ii Contents Writing Programs 2 Overview irse r
42. component to center of spectrum Inverse discrete F ourier transform Two dimensional inverse discrete F ourier transform Inverse multidimensional fast Fourier transform Sound and Audio Function Purpose ml fFreqspace ml f Lin2mu ml f Mu2l in Frequency spacing for frequency response Convert linear signal to mu law encoding Convert mu law encoding to linear signal 9 34 MATLAB M File M ath Library Polynomial and Interpolation Functions Data Interpolation Function Purpose ml f Gri ddata Data gridding ml fl cubic Cubic interpolation of 1 D function ml fl nterpl One dimensional interpolation 1 D table lookup ml flnterplg Quick one dimensional linear interpolation ml fl nterp2 Two dimensional interpolation 2 D table lookup ml fl nterpft One dimensional interpolation using FFT method Spline Interpolation Function Purpose ml f Ppval Evaluate piecewise polynomial ml f Spline Piecewise polynomial cubic spline interpolant Geometric Analysis Function Purpose ml fl npolygon ml f Pol yarea mi f Recti nt Detect points inside a polygonal region Area of polygon Rectangle intersection area 9 35 9 Library Routines Polynomials Function Purpose ml f Conv Multiply polynomials ml f Decony Divide polynomials ml f Mk pp Make piecewise polynomial ml f Pol y Construct polynomial with specified roots ml f Pol yder Differen
43. for this example named i ntro c isin the lt matlab gt extern examples cmath directory on UNIX systems and in the lt matlab gt extern exampl es cmath directory on PCs where lt mat ab gt represents the top level directory of your installation See Building C Applications on page 1 11 for information on building the examples Overview x intro c include lt stdio h gt include lt stdlib h gt include lt string h gt include matlab h int mai n double numl num2 mxArray volatile factorsl NULL mxArray volatile factors2 NULL mxArray volatile common_factors NULL mi fEnterNewContext 0 0 Get user input and convert from string to integer printf Enter a number scanf f amp numl printf Enter a second number scanf f amp num2 ml fTry Call MATLAB C Math Library functions Get factors of input numbers m fAssign amp factorsl mlfFactor mfScalar numl ml fAssign amp factors2 mifFactor ml fScalar num2 Determine if there are factors in common ml fAssign amp common_factors mflntersect NULL NULL factorsl factors2 NULL 2 W riting Programs If common_factors is an empty array the numbers are relatively prime if ml fTobool mflsempty common_factors printf 0 01f and 0 0I1f are relatively prime n numl num2 else printf 0 0lf and 0 0If share common factor s numl num2 ml fP
44. for writing functions so that they can be nested Deleting Your Arrays You must explicitly delete e Any array that you ve bound to a variable by calling ml f Assi gn e Any array that you ve passed as an output argument to a function 4 11 4 Managing Array Memory 4 12 mxDestroyArray destroys the array mx Arr ay passed to it For example mxDestroyArray A destroys array A mxDestroyArray doeshandleaNULL argument However mx DestroyArray does not reinitialize the mx Arr ay pointer passed toit toNULL If you assign an array toan mxArray variable and subsequently delete that array by calling mx DestroyArray then you must reinitialize the mx Array variable toNULL before reassigning another array to that variable If you follow the Paradigm for Working with Local Array Variables on page 4 8 then you avoid this awkward coding ml fAssign amp c mifScalar 5 mxDestroyArray c c NULL ml fAssign amp c mifScalar 6 Avoiding Memory Leaks in Your Functions Structuring your code as recommended in Paradigm for Working with Local Array Variables on page 4 8 helps you avoid the following memory leaks 1 Never call a library function without assigning the array it returns to an array variable by calling ml f Assi gn or without embedding the call as an argument to a library function Memory leak mi f Si n X The array returned by ml f Si n is not bound toa variable and never
45. function if too many input or output arguments have been provided Note that the thunk function relies on the called function to do more precise checking of arguments Call orenz casting pFunc which points tothe orenz function tothe type PFCN 1 2 Verify that the two expected arguments are provided If at least oneargument is passed pass the first element from the array of input values rhs 0 asthe first input argument otherwise pass NULL If at least two arguments are provided pass the second element from the array of input values rhs 1 as the second argument otherwise pass NULL as the second Passing Functions As Arguments to Library Routines argument Thereturn from or enz is stored temporarily in the local variable Out This general calling sequence handles optional arguments It is technically unnecessary in this example because or enz has no optional arguments However it is an essential part of a general purpose thunk function Note that you must cast the pointer to or enz tothe function pointer type that you defined within the thunk function 5 Assign the value returned by or enz tothe appropriate position in the array of output values The return value is always stored at the first position hs 0 If there were additional output arguments values would be returned in hs 1 hs 2 and soon 6 Return success 6 27 6 Calling Library Routines 6 28 Thenext section of this example cont
46. hel p mathlib ht ml with your Web browser where lt mat ab gt is the top level directory where you installed the C Math Library 2 Select C Math Library Reference Additional Sources of Information Also available from the Help Desk e Release notes for the MATLAB C Math Library lt matl ab gt extern exampl es cmath release txt e Online MATLAB Application Program Interface Reference e Online MATLAB Application Program Interface Guide e Online MATLAB Function Reference e Installation Guide for UNIX e Installation Guide for PC MATLAB C Math Library 1 2 Users Though the library maintains as much backwards compatibility as possible some functions have changed between Version 1 2 and Version 2 0 See Migrating Your Code to Version 2 0 on page 1 6 for a list of these functions 1 G etting Ready Tousethe signatures of the functions from Version 1 2 define the preprocessor symbol MLF_V1_2 when you build your application For example if you use the tool mbui d to build your application mbuild DMLF_V1_2 appfile c Note You must recompile existing code to use Version 2 0 of the MATLAB C Math Library MATLAB C Math Library Version 1 2 Documentation The documentation that supports Version 1 2 of the library includes e MATLAB C Math Library User s Guide This manual provides tutorial information about the library This manual is availablein PDF format accessible through the Help Desk e MATLAB C Math L
47. in the array The calls toml f Tobool are necessary because C requires that the condition for ani f statement be a scalar Boolean not a scalar mx Array 7 Free each of the matrices used in the examples Output When run the program produces this output Success all variables equal 7 Importing and Exporting Array Data Handling Errors and Writing a Print Handler Overview 2 2 0022 ee 8 2 Handling Errors 8 3 Customizing Error Handling aoa a a a a aa 8 5 Example Program Defining Try Catch Blocks ex6 c 8 6 Replacing the Default Library Error Handler 8 9 Defining a Print Handler 8 14 Providing Your Own Print Handler 8 14 OutputtoaGUI 2 044 8 15 8 Handling Errors and W riting a Print Handler 8 2 Overview This chapter includes information about two common programming tasks error handling and print handling This chapter describes how you can e Customize the default MATLAB C Math Library error handling by using the ml f Try and ml f Catch macros and by defining your own print handler e Customize printing by defining your own print handler This sectionincludes information about displaying output toa GUI Handling Errors Handling Errors The MATLAB C Math library routines handle error conditions in two ways depending on the severity of the error e For less severe error conditions called warnings the
48. input arguments 2 Initializelocal array variables to NULL or to valid arrays Library functions including ml f Assi gn require that output arguments are initialized toNULL or toa valid array 3 Call mi fEnterNewContext toturnon automated memory management for your function and to change the status of temporary input arrays to bound arrays Pair this call with a call toml f Rest orePreviousContext attheend of your function 4 Perform the work of your function Becoming accustomed to programming with ml f Assi gn rather than the assignment operator is the biggest adjustment you ll need to make in your programming style 5 Free any bound array variables by calling mxDestroyArray However do not destroy the return value from your function W riting Functions Under Automated Memory Management 6 Call ml fRestorePrevi ousContext toreset the state for each input array the value it had on entering the function and then to delete any temporary arrays Pass the same arguments that you passed to ml f Ent erNewContext 7 Call mi f Ret urnValue tomakethearray you are returning temporary and then return the temporary array You can nest the call toml f ReturnValue within ther et urn statement 4 23 4 Managing Array Memory Example Program Managing Array Memory ex 2 c This example program demonstrates how to write functions that use the same automated memory management technique as the MATLAB C M
49. library routines output a message to the user and then return control to the application The application can continue processing e For more severe error conditions the library routines output a message to the user and then exits terminating the application Control never returns to the application The following example program illustrates this default library error handling The program deliberately causes a warning level error condition division by zero and a more severe error condition attempting to add two matrices of unequal size that causes termination 8 3 8 Handling Errors and W riting a Print Handler 8 4 i nc i nc i nc i nc ude lt stdio h gt ude lt stdlib h gt used for EXIT SUCCESS ude lt string h gt ude matlab h Matrix data Column major element order stat main ic double data 1 2 3 4 5 6 Declare matrix variables mxArray matQ NULL mxArray matl NULL mxArray mat2 NULL mi fEnterNewContext 0 0 Create two matrices of different sizes m fAssign amp mat0 mlfDoubleMatrix 2 3 data NULL ml fAssign amp matl mlfDoubleMatrix 3 2 data NULL Division by zero will produce a warning ml fAssign amp mat2 mifRdivide mat1 mifScalar 0 mfPrintf Return to application after warning n Adding mismatched matrices produces error fPrintMatrix ml fPlus mat0 mat1 mifPrintf Should not be r
50. ml f RestorePrevi ousContext as you passed to mi f EnterNewContext 1 Thenumber i nt nout of array output arguments declared by your function Specify 0 if there are no array output arguments declared in the same way the mai n template function does The template function declares one output argument 2 Thenumber i nt nin of array input arguments declared by your function Specify 0 if there are no array output arguments declared in the same way the mai n template function does The template function declares two input arguments 3 Thearray output arguments mx Array themselves in the order declared for the function In the template out put_arg1 iS passed 4 Thearray input arguments mx Array themselves in the order declared for the function In the template i nput_argl andi nput_arg2 are passed 4 19 4 Managing Array Memory 4 20 Note You only list mArray andmxArray arguments For example if a function takes an argument of typechar ori nt donot include it in the count of output and input arguments or in the list of the arguments themselves W hat Happens to the Array Arguments ml fRestorePrevi ousContext restores the state of the input arrays to their state at the time of the function call e Any array input argument that was temporary at the time of the function call becomes temporary again e Any array input argument that was bound at the time of the function call rem
51. multidimensional arrays of characters represented in 16 bit ASCII Unicode format For more information about working with character arrays see Working with MATLAB Character Arrays on page 3 25 Overview e Cell arrays The library supports multidimensional arrays of MATLAB s primary container type called cals Each cell can contain any type of MATLAB array including other cell arrays For more information about working with cell arrays see Working with MATLAB Cell Arrays on page 3 30 Structures The library supports multidimensional arrays of MATLAB s other container type called structures A structure can be thought of as a one dimensional cell array where each cell is assigned a name These named cells called fidds define the organization of the structure Do not confuse MATLAB structures with standard C structures For more information about working with MATLAB structures see Working with MATLAB Structures on page 3 37 Choose the MATLAB array type that best fits your data F or more detailed information about these array types see Using MATLAB MATLAB Array C Data Type The MATLAB C Math Library uses one data type mx Array torepresent all types of MATLAB arrays ThemxArray data type is defined by the MATLAB Application Program Interface API Each instance of this data type contains information that identifies the type of array and the size and shape of the array The mx Array data typeis an opaqu
52. on a structure In the MATLAB C Math Library The indexing functions in the MATLAB C Math Library support N dimensional standard cell array and structure indexing An array subscript consists of one or more indices passed as mxArray arguments to one of the indexing functions F or example the two dimensional indexing expression miflndexRef A mlfScalar 3 mlfScalar 1 applies the subscript 3 1 toA and returns the element at row three column one miflndexRef A ml fScalar 9 aonedimensional indexing expression returns the ninth element of array A Note The indexing functions follow the MATLAB convention for array indices indices begin at one rather than zero Overview An index mx Arr ay argument can contain a scalar vector matrix or the result from a call to the special function ml f CreateColonlndex e A scalar subscript selects a scalar value e A subscript with vector or matrix indices selects a vector or matrix of values e Theml f Creat eCol onl ndex index which loosely interpreted means all selects for example all the columns in a row or all the rows in a column You can also use the ml f Col on function which is patterned after the MATLAB colon operator to specify a vector subscript For example ml f Colon mlfSclar 1 mlfScalar 10 NULL specifies the vector 12345678910 Note You cannot index into an array with more dimensions than the array has altho
53. owever because the MessageDi alog isa child of the application and not the root window other applications continue to operate normally X Windows Motif Example List other X include files here include lt Xm Xm h gt include lt Xm X11 h gt include lt Xm MessageB h gt static Widget message dialog 0 The alternate print handler void PopupMessageBox const char message Arg args 1 XtSetArg args 0 XmNmessageString message XtSetValues message dialog args 1 Xt Popup message dialog XtGrabExclusive mai n Start X application Insert your own code here main_window XtApplnitialize your code Create the message box widget as a child of the main application window message dialog XmCreateMessageDi alog main_window MATLAB Message 0 0 Set the print handler ml fSetPrintHandl er PopupMessageBox The rest of your program 8 16 Defining a Print Handler This example declares two functions PopupMessageBox andmai n PopupMessageBox is theprint handler and is called every timethelibrary needs to display a text message It places the message text into the MessageDi al og widget and makes the dialog box visible The second routine main first creates and initializes the X Window System application This code is not shown since it is common to most applications and can be found in your X Windows reference guide mai n then c
54. passed as input arguments to other functions they are passed as bound arrays The first calculation passes the input argument x_i n tothe MATLAB C Math Library functions ml f Si n and ml f Cos These two calls return temporary arrays which are passed to another library function ml f Pl us The temporary array returned from the call to ml f PI us is then passed to the library function ml fSqrt In this series of nested calls only the return from ml f Sqrt is assigned toa variable via the ml f Assi gn function That array result _ ocal becomes a bound array Thetemporary arrays returned fromm f Si n andml f Cos and passed to ml f PI us are automatically deleted by mi f Pl us ml f Sqrt deletes the temporary array returned fromm f Plus Calls tomi f Assi gn now appear as frequently as the assignment operator did in code prior to MATLAB C Math Library Version 2 0 The array on the left hand side of the assignment the first argument to ml f Assi gn becomes a bound array and persists You must explicitly delete it the library does not These calculations again illustrate the automated memory management provided by the library If you do not want to keep the array returned from alibrary function just nest the call as an argument toa function Thereturn from the call a temporary array will be deleted by the other function In these calculations g_ ocal andz_out are each the targets of an assignment s
55. prefix 1 3 ml fAssign 4 8 4 9 4 14 4 22 4 25 4 27 3 3 3 33 3 3 3 3 3 3 3 53 fCat example 3 11 fCell disp using 3 34 fCell hcat using 3 33 fColon 9 21 fComplexScalar 9 23 fCreateColonindex 5 5 5 18 5 23 5 27 fEnd 5 20 5 26 fEnterNewContext 414 4 16 4 25 4 26 arguments to 4 17 4 30 called from mai n 4 16 4 29 fFeval 6 20 6 30 fFeval function table built in table extending 6 21 ml fFevalTableSetup 6 24 6 29 ml fFuncTabEnt type 6 24 setting up 6 24 6 29 fFeval function table 621 fFevalTableSetup 624 6 29 9 21 fFprintf 3 42 f Funcp function pointer type 6 24 6 25 6 26 fHorzcat 5 16 creating arrays 5 16 number of arguments 5 25 fl ndexAssi gn for assignments 5 36 how to call 5 10 fl ndexDel et e for deletion 5 42 how to call 5 10 fl ndexRef for logical indexing 5 31 for N dimensional indexing 5 23 for one dimensional indexing 5 18 how to call 5 10 Index 1 10 3 fl ndexVarargout function constructing 6 11 fload 7 3 7 6 9 18 flogical 5 31 fNnz 3 23 f0de23 6 22 6 29 fPrintf 3 42 fPrintf 9 22 fPrintMatrix 9 23 fRestorePreviousContext 4 14 4 18 4 25 4 28 arguments to 4 19 4 28 4 30 called from mai n 4 16 4 29 ml fReturnValue 4 14 4 20 4 28 argument to 4 21 making an array temporary 4 21 e eee ml fSave 7 2 7 6 9 18 m fScalar 7 6 9 23 ml fSetErro
56. reading writing or deletion In the MATLAB C Math Library the expression becomes miflndexRef B bfield mfScalar 3 mfScalar 7 mfScalar 2 mfScalar 1l Nesting Indexing Operations In MATLAB you can nest indexing operations when you do the results of the inner indexing operation supply the index values for the outer index operation Because the MATLAB C Math Library represents MATLAB indexing operations with calls toml f ndexRef you can recreate the MATLAB behavior in the library by nesting calls to ml f ndexRef inside one another 5 13 5 Indexing into Arrays 5 14 For example the MATLAB expression x y 4 3 becomes m flndexAssign amp x mlflndexRef y ml fScalar 4 mi fScalar 3 The MATLAB expression D A foo 1 B 2 3 bar 4 C becomes ml fAssign amp D ml flndexRef A foo mlfScalar 1 miflndexRef B mlfScalar 2 mlfScalar 3 bar mlfScalar 4 ml fl ndexRef C ml fCreateCol onlndex Specifying the Values for Indices Because the second argument the index string only describes the types of operations to be performed and does not contain the actual subscript values you must pass these values seperately to the indexing functions F ollowing the indexing string argument you pass a list of pointers tomxArrays Each array contains the value of an index in your subscript s For example thetwocallstoml f Scal ar i
57. result _local ml fSqrt mlfPlus mlfSin x_in mlfCos x_in In MATLAB q Saqrt cos y sin y ml fAssign amp q_loca ml fSqrt mlfMinus mlfCos y_in mlfSin y_in In MATLAB z q result q 3 ml fAssign z_out ml fMinus mlfTimes q_local result_local ml fPower q_local mlfScalar 3 mxDestroyArray q_local ml fRestorePreviousContext 1 2 z_out x_in y_in return mlfReturnValue result_local 4 25 4 Managing Array Memory 4 26 Notes The numbers in the list below correspond to the numbered sections of code above 1 Includeheader files mat ab h declaresthemxArray data structure and the prototypes for all the functions in the MATLAB C Math Library stdlib h contains the definition of EXIT SUCCESS 2 Define the interface for your function This function Automated _Mem_Exampl e takes two inputs and returns two outputs It has one return value one output array argument mxArray z_out and two input array arguments mxArray x_in andmxArray y_in The definition of the function follows the MATLAB C Math Library calling conventions where output arguments precede input arguments You can write functions that follow these calling conventions or implement your own The body of Automat ed_ Mem Exampl e performs three calculations that illustrate how the library manages the memory allocated for the arrays The first two calculations operate on the two input arguments the third on
58. routine must not return a value return void e An error handling routine accepts two arguments a const string and a Boolean value The string is the text of the error message When the value of this Boolean value is TRUE it indicates an error message If this value is FALSE it indicates a warning message Registering Your Error Handler After writing an error handler you must register it with the MATLAB C Math Library so that the library routines can call it when they encounter an error condition at runtime You register an error handler using the ml fSetErrorHandler routine ml fSetErrorHandler MyErrorHandl er Example Program The following example program adds an error handler to the sample program introduced on page 8 4 This error handler writes error messages to a log file identifying each message as an error or warning An error handler like this allows a program torun unattended since any errors produced are recorded in a file for future examination More complex error handling schemes are also possible For example you can use two files one for the messages sent to the print handler and one for errors or you can pipe the error messageto an e mail program that sends a notification of the error to the user who started the program Handling Errors include lt stdio h gt include lt stdlib h gt include lt string h gt include matlab h FILE stream void MyErrorHandler const char msg bool isError
59. single structure 5 54 referencing nested structures 5 54 within cells 5 55 structures converting cell arrays 3 39 converting to cell arrays 3 31 creating 3 37 creating by assignment 3 40 indexing 5 51 using ml f Struct 3 38 subscripting how MATLAB calculates indices 5 9 subscripts 5 4 logical 5 31 syntax index string 5 12 indexing 5 57 library functions documented online 1 5 subscripts 5 57 T temporary arrays 4 6 4 14 4 21 4 27 4 28 behavior of 4 7 thunk functions defining 6 25 how to write 6 22 relationship toml f Feval 621 when to write 6 22 time current 9 19 9 40 timing functions 9 41 transpose 1 13 Index use instead of 9 7 trigonometric functions list of 9 12 9 27 two libraries justification for 9 3 two dimensional indexing table of examples 5 57 with logical indices 5 31 U UNIX building stand alone applications 1 13 directory organization A 3 libraries A 4 location build script A 3 example source code A 5 A 9 header files A 5 libraries A 4 utility functions error handling 9 21 indexing 9 21 memory allocation 9 22 ml fFeval support 9 21 print handling 9 22 scalar array creation 9 23 V varargi n functions 6 7 pure 6 8 varargout functions 6 9 pure 6 10 W warnings list of B 8 working with nonzero entries of sparse matrices 9 20 9 43 writing functions 4 14 X X Window system initializing 8 17 PopupMessageBox C code 8 16 print handler 8 15 XtPopup
60. the maximum legal value for an integer NaN and Inf not allowed IEEE NaN Not A Number or nf Infinity was passed to a function that cannot handle those values or resulted unexpectedly from computations internal to a function Not enough input arguments A function expected more input arguments than it was passed F or example most functions will issue this error if they receive zero arguments The MATLAB C Math Library should never issue this error Please notify The MathWorks if you see this error message Not enough output arguments A function expected more output arguments than were passed to it Functions in the MATLAB C Math Library will issue this error if any required output arguments are NULL If you see this error under any other conditions please notify The MathWorks Singularity in ATAN A singularity indicates an input for which the output is undefined ATAN arc tangent has singularities on the complex plane particularly at z 1 Singularity in TAN A singularity indicates an input for which the output is undefined TAN tangent function has singularities at odd multiples of 7 2 B 5 B Errors and W arnings B 6 Solution will not converge This error occurs when the input to a function is poorly conditioned or otherwise beyond the capabilities of our iterative algorithms to solve String argument is an unknown option A function received a string matrix i e a matrix with the string property se
61. their output For example the sample application in Chapter 2 creates arrays by calling the library arithmetic routines ml fFactor andmifintersect Creating Numeric Arrays by Concatenation You can create arrays by grouping together existing MATLAB arrays using concatenation In MATLAB you usethe brackets operator to concatenate arrays vertically or horizontally For example you can use the following syntax in MATLAB to concatenate arrays In this MATLAB example the numeric values being concatenated are scalar arrays The semicolon indicates that you want to create rows for vertical as well as horizontal concatenation AR Shi D2 Ba ABa The MATLAB C Math Library uses theml f Horzcat andmlfVertcat routines to perform horizontal and vertical concatenation You nest calls to ml f Horzcat insideml f Vertcat tocreatethe same two dimensional array inaC program 3 9 3 W orking with MATLAB Arrays Note This code fragment duplicates the preceding MATLAB syntax however it is more efficient to create a two dimensional array of constants using ml f Doubl eMatrix rather than with ml f Horzcat andmifVertcat mxArray A NULL m fAssign amp A mfVertcat mlfHorzcat mlfScalar 1 ml f Scalar 2 ml f Scalar 3 NULL ml fHorzcat ml fScalar 4 ml f Scalar 5 mi f Scal ar 6 NULL NULL ml f Print Matrix A mxDestroyArray A Creating Multidimensional Numeric Arrays by Concatenatio
62. this example does not register a print handling routine all output goes through the default print handler The default print handler uses pri nt f See the section Defining a Print Handler in Chapter 8 for details on registering print handlers Free each local bound array by calling mx Dest royArray Note that mxDestroyArray can handlea NULL argument if you inadvertently pass a pointer to an array that has already been destroyed and set toNULL End the function by calling ml f Rest orePrevi ousContext Pass0 asthe first and second argument to indicate that mai n has no input and output arguments Example Program M anaging Array Memory ex2 c Output When run the program produces this output mat 0 1 3 5 2 4 6 Output array 0 0714 0 0331 0 2959i 0 9461 1 5260i 0 6023 1 2631 1 2030i 0 0 6181i result_array 1 1755 0 0 9213i 0 0 82171 0 7022 0 1 1876i 0 8251 Example Without Automated Memory Management The function Explicit _Mem_Exampl e performs the same calculations as Automated Mem Exampl e in the previous example Compare the use of temporary variables nonnested calls tothe MATLAB C Math Library functions and calls to mx DestroyArray 1t contains twenty six lines of code compared toAut omated_ Mem Exampl e s nine lines Important You can still code to this interface The MATLAB C Math Library continues to support it However you cannot call Explicit Mem Exampl e fr
63. three outputs n n ml f Print Matrix U n ml fPrintMatrix S n ml fPrintMatrix V ut and output arguments lf Svd amp amp V X mfScalar 0 0 inputs three out puts n n ml fPrintMatrix U n ml fPrintMatrix S n ml f Print Matrix V 6 15 6 Calling Library Routines 6 16 mxDestroyArray X mxDestroyArray U mxDestroyArray S mxDestroyArray V ml fRestorePreviousContext 0 0 return EXIT SUCCESS Notes 1 Include mat ab h This file contains the declaration of the mx Array data structure and the prototypes for all the functions in the library st dl ib h contains the definition of EXIT SUCCESS 2 Declare the eight element static array that subsequently initializes the ml f Svd input matrix The elements in this array appear in column major order The MATLAB C Math Library stores its array data in column major order unlike C which stores array data in row major order 3 Declare and initialize the ml f Svd input array X Declare and initialize mx Array variables U S andV to be used as output arguments in later calls toml fSvd 4 mi fSvd can be called in three different ways Call it the first way with one input matrix and one output matrix Note that the optional inputs and outputs in the parameter list are set toNULL Optional in this case does not mean that the arguments can be omitted from the parameter list instead it means that the ar
64. user usinginput and output functions but you can use ANSI standard C input output routines Note Thelibrary includes two routines ml flLoad and mi f Save that allow you to import and export data in MAT file format F or more information about using these routines see Chapter 7 5 Definea try block using the MATLAB C Math library macro ml f Try When a library function included in a try block encounters a run time error it outputs an error message and then passes control to a catch block in the program In a catch block an application can free arrays that have been assigned to variables or perform other processing before exiting For more information about defining try and catch blocks see Handling Errors on page 8 3 6 Call the MATLAB C Math Library routine ml f Fact or tofind the prime factors of each number input by the user The call to ml f Scal ar which converts the number input by the user from an integer toa MATLAB array is an example of nesting this is only safe if automated memory management Because the application only uses the array returned by ml fScalar aSinput toml fFactor thereis no need to assign the array toa variable With automated memory management enabled the library frees the array after ml fFactor is finished using it In contrast because the example uses the array returned by ml f Fact or several times it assigns this array to a variable f act ors1 using the ml f Assi gn ro
65. were changed to ml fAssign amp A mf Magic ml fScalar 3 Ww oo Wo Wm FE NuU DD and B remains the same then ml f I ndexRef A B would equal 3 3 oo Note In both cases si ze A B iS equal tosi ze B This is a fundamental property of one dimensional indexing Selecting the Entire Matrix As a Column Vector Use the colon index toselect all the elements in an array Theresult is a column vector For example mi fAssign amp B miflndexRef A ml fCreateColonindex 5 21 5 Indexing into Arrays 5 22 WoO OAD Oo amp WP PE The colon index means all It is a context sensitive function It expands toa vector array containing all the indices of the dimension in which it is used its context In the context of an M by N array 4 A in MATLAB notation is equivalent toA 1 M N When you use colon you don t have to specify M and N explicitly which is convenient when you don t know M and N Using mlflndexRef for N Dimensional Indexing Using mlifindex Ref for N Dimensional Indexing This section describes how to e Extract a scalar from a matrix e Extract a vector from a matrix e Extract a subarray from a matrix e Extend two dimensional indexing to N dimensions All two dimensional examples work with example matrix A wn e ow pA wo oom There is no functional difference between two dimensional indexing and N dimensional indexing where N gt 2 Be
66. 1 second date c 1 2 date performs the same operation in MATLAB In this case the result is a single date structure Deleting Elements from a Structure Array There are three kinds of deletion operations you can perform on a structure array You can delete e An entire structure from the array e A field from all the structures in the array e Elements from an array contained by a field 5 55 5 Indexing into Arrays 5 56 Deleting a Structure from the Array To delete an entire structure from a structure array use ml f ndexDelete For example if you have a three element array of image structures you can delete the second image structure like this ml flndexDelete amp i mages mlfScalar 2 images 2 performs the same operation in MATLAB Theresult is a two element array of image structures Deleting a Field from All the Structures in an Array To delete a field from all the structures in the array use ml f Rmfi el d For example you can remove the description field from an array of image structures with this code ml fAssign amp i mages mi fRmfield images mxCreateString description images rmfield images description performs the same operation in MATLAB Note that r mf i el d does not allow you to remove a field of a nested structure from a structure array For example you cannot remove the day field of the nested date structure with this MATLAB code rmfield ima
67. 4 2 description Greater Bird of Paradise images 3 4 2 date year 1993 images 3 4 2 date month 7 images 3 4 2 day 15 For simplicity the examples in the book focus on two dimensional structure arrays but they d work just as well with structure arrays of any dimension Tips for Working with Structure Arrays All the structures in a structure array have the same form every structure has the same fields Adding a field to one structure in a structure array adds it to all the structures in the structure array Similarly deleting a field from one structure in the array deletes it from all the structures in the array You can access and modify data stored in the fields of a structure just as you would data stored in an ordinary variable Structure fields are analogous to cell array indices only they are names rather than numbers Therefore structure field access and creation use the same indexing routines as cell array and numeric array element access and creation do ml fl ndexRef mlfilndexAssign mlflndexDelete Each field in a structure array is an array itself For example in the 3 by 4 by 2 example above the array contains 24 structures There are 24 images 24 descriptions etc and you can treat each field of the structure as an array of 24 elements If you typed x description for example you d get a 24 by 1 array of strings containing all the image descriptions in the structure array Accessing a
68. 8 temporarily changing on UNIX 1 16 options files PC 1 27 options mbui d on Microsoft Windows 1 30 on UNIX 1 19 order link 1 36 of arguments 6 13 of call toml f Set PrintHandler 8 15 ordinary differential equations option handling 9 38 1 11 Index 1 12 solvers 9 37 output and graphical user interface 8 14 arguments multiple 6 4 optional 6 4 6 5 formatted arrays 3 42 ml fSave 7 2 7 6 of arrays 3 41 of error messages 8 14 of matrix 8 14 to GUI 8 15 output arguments and ml fEnterNewContext 4 17 andml fRestorePreviousContext 4 19 initializing before function call 4 8 P performance 5 39 polynomial and interpolation functions data interpolation 9 35 geometric analysis 9 35 polynomials 9 36 spline interpolation 9 35 polynomials 9 36 PopupMessageBox Microsoft Windows C code 8 18 X Window system C code 8 16 print handler default C code 8 14 Microsoft Windows example 8 17 ml fSetPrintHandler 8 15 providing your own 8 14 X Window system example 8 15 print handling functions 9 22 printing arrays 3 41 purevarargin functions 6 8 purevarargout functions 6 10 quadrature 9 37 R registering functions with ml f Feval 6 22 relational operator functions 9 6 release notes A 6 A 9 remainder functions 9 13 9 28 reordering algorithms 9 44 response file 1 30 restrictions on calling functions 4 31 4 33 return values and ml f ReturnVal ue 4 20 4 28 return values multiple 6 14 return
69. 8 16 XtSetArg 8 16 XtSetValues 8 16 XmCreateMessageDi al og 816
70. 9 37 functions compatibility between memory management styles 4 33 documented in online reference 1 5 embedding calls to 4 8 4 11 4 27 nesting calls to 4 8 4 11 4 27 order of arguments 6 2 preparing function arguments for a new context 4 16 restoring function arguments to a previous con text 4 18 returning an array fromi 4 20 steps for coding 4 22 template for managing array memory 4 14 4 15 4 16 using a single return statement 4 21 Index writing your own under automated memory management 4 14 writing your own under explicit memory man agement 4 31 G geometric analysis 9 35 graphical user interface output to 8 15 GUI output to 8 15 H Handle Graphics 1 3 header files i bmat b h location Microsoft Windows A 8 UNIX A 5 i bmmf i e h location Microsoft Windows A 8 UNIX A 5 matlab h location Microsoft Windows A 8 UNIX A 5 matrix h location Microsoft Windows A 8 UNIX A 5 l indexing and assignment 5 36 5 49 and deletion 5 42 5 49 5 55 array storage 5 5 assumptions for examples 5 16 base 5 4 C vs MATLAB 5 57 dimensions and subscripts 5 3 logical 5 31 N dimensional 5 23 5 29 5 35 5 45 one dimensional 5 18 similar tof or loop 5 5 5 27 structure array 5 51 table of examples 5 57 terminology 5 3 types of 5 3 5 45 with ml f CreateCol onl ndex 5 5 5 18 5 23 5 27 with ml f End 5 20 5 26 indexing functions 5 2 5 10 9 21 ml flndexAssign 5 36 ml flndexDelete 5
71. Application executable e i bmmfile ext e i bmatlb ext e i bmat ext e i bmx ext e i but ext e i bmi amp t where the file extension ext is a on IBM RS 6000 so on Solaris Alpha Linux and SGI and s on HP 700 For example to distribute theex1 example for Solaris you need toincludeex1 libmmfile so libmatlb so libmat so libmx so libut so andlibmi so Remember that the path variable must reference the location of the shared libraries 1 21 1 G etting Ready Building a Stand Alone Application on Microsoft Windows This section explains how to compile and link C code into stand alone Windows applications Configuring for C or C mbui d determines whether to compile in C or C by examining the type of files you are compiling Table 1 1 shows the file extensions that mbui d interprets as indicating C or C files If you include both C and C files mbui d uses the C compiler and the MATLAB C Math Library If mbui ld cannot deduce from the file extensions whether to compile in C or C mbui d invokes the C compiler Table 1 3 Windows File Extensions for mbuild Language Ex tension s C s CH Epp LEXY CC Note You can override the language choice that is determined from the extension by using the ang option of mbui d For more information about this option as well as all of the other mbui d options see Table 1 5 Locating Options Files To locate your op
72. B M file math functions MATLAB Array Access and Creation Library Contains array creation and access routines MATLAB Utilities Library Contains the utility routines used by various components Batch file that helps you build and link stand alone executables Default options file for use with mbui d bat Created by mbuild setup Switches and settings for C compiler to create stand alone applications e g msvccomp bat for use with Microsoft Visual C lt matiab gt extern include The lt mat ab gt extern incl ude directory contains the header files for developing MATLAB C Math Library applications and the def files used by the Microsoft Visual C and Borland compilers The i b def files are used by MSVC andthe _1i b def files are used by Borland li bmatlb h i bmmfile h matlab h matrix h li bmat def _libmat def Header file containing the prototypes for the MATLAB Built In Math Library functions Header file containing the prototypes for the MATLAB M File Math Library functions Header file for the MATLAB C Math Library Header file containing the definition of the mxArray type and function prototypes for array access routines Contains names of functions exported from the MAT file DLL Directory O rganization on Microsoft W indows i bmat b def _libmatlb def i bmmfile def _libmmfile def i bmx def _libmx def Contains names of functions exported f
73. B C Math Library Each type of message is treated in its own section Within each section the messages are listed in alphabetical order Following each message is a short interpretation of the message and where applicable suggested ways to work around the error Errors Errors This section lists a subset of the error messages issued by the library By default programs written using the library always exit after an error has occurred For information about handling errors so that you can continue processing after an error occurred see Handling Errors in Chapter 8 Argument must be a vector An input argument that must be either 1 by N or M by 1 i e either a row or column vector was an M by N matrix where neither M nor N is equal to 1 To correct this check the documentation for the function that produced the error and fix the incorrect argument Division by zero is not allowed The MATLAB C Math Library detected an attempt to divide by zero This error only occurs on non I EEE machines notably DEC VAX machines which cannot represent infinity Division by zero on IEEE machines results in a warning rather than an error Empty matrix is not a valid argument Some functions such as ml f Si ze accept empty matrices as input arguments Others such as ml f Ei g do not You will see this error message if you call a function that does not accept NULL matrices with aNULL matrix Floating point overflow A computation
74. Cell Array mxCreateCell Matrix mxCreateCharArray mxCreateCharMatrixFromStrings mxCreateDoubl eMat ri x mxCreateNumericArray mxCreateSparse mxCreateString mxCreateStructArray Allocate and free dynamic memory using MATLAB s memory manager Clear the logical flag Create an unpopulated N dimensional cell mx Array Create an unpopulated 2 D cell mxArray Create an unpopulated N dimensional string mx Array Create a populated 2 D string mxArray Create an unpopulated 2 D double precision floating point mx Array Create an unpopulated N dimensional numeric mx Array Create a 2 D unpopulated sparse mx Array Create a 1 by n string mx Array initialized to the specified string Create an unpopulated N dimensional structure mx Array Array Access and Creation Library Array Access Routines Continued Function Purpose mxCreateStruct Matrix mxDestroyArray mxDuplicateArray mx Get Cel mxGet Cl assiD mxGet Cl assName mxGet Data mxGet Di mensi ons mxGet El ement Size mxGet Eps mxGet Field mxGet Fi el dBy Number mxGet Fi el dNameBy Number mxGet Fi el dNumber mxGet magData mx Get nf mxGetlr mxGet c mxGet M mxGetN Create an unpopulated 2 D structure mxArray F ree dynamic memory allocated by an mxCr eate routine Make a deep copy of an array Get a cell s contents Get as an enumerated constant an mxArray s dass Get as a string an mxArray s class Ge
75. I MFLAGS with CPPOPTI MFLAGS DEBUGFLAGS with CPPDEBUGFLAGS and LI NKFLAGS with CPPLINKFLAGS 1 27 1 G etting Ready 1 28 This process modifies your C options file to be a universal C C options file Temporarily Changing the Compiler To temporarily change your C compiler use the f option as in mbuild f lt file gt The f option tells the mbui d script to use the options file lt fi l e gt If lt fi l e gt is not in the current directory then lt f i e gt must be the full pathname to the desired options file Using the f option tells thembui I d script to use the specified options file for the current execution of mbui d only it does not reset the default compiler Verifying mbuild C source code for the exampleex1 c is included in the lt matlab gt extern exampl es cmath directory where lt mat ab gt represents the top level directory where MATLAB is installed on your system To verify that mbui ld is properly configured on your system to create stand alone applications enter at the DOS prompt mbuild exl c This creates the file called ex1 exe Stand alone applications created on Windows 95 or NT always have the extension exe The created application is a 32 bit Microsoft Windows console application Shared Libraries DLLs All the WIN32 Dynamic Link Libraries DLLs for the MATLAB C Math Library arein the directory lt matlab gt bin The def files for the Microsoft and Borland compilers
76. In catch block Caught an error Matrix dimensions must agree Now in application after catch block A more sophisticated error handling mechanism could do much more than simply print an additional error message If this statement were in a loop for example the code could discover the cause of the error correct it and try the operation again Replacing the Default Library Error Handler The default error handling behavior of the MATLAB C Math Library routines is implemented by the default library error handler routine You can further customize error handling by replacing the default library error handler routine with one of your own design Note Because of the error handling capabilities provided by the library try catch mechanism applications typically do not need to replace the default error handler However in some instances it can be useful For example you can write an error handler that directs error messages to a file Toreplace the default error handler you must e Write an error handler e Register your error handler so that library routines call it when they encounter an error Writing an Error Handler When you writean error handler you must conform to the library prototype for error handling routines void MyErrorHandler const char msg bool isError Your code 8 9 8 Handling Errors and W riting a Print Handler 8 10 In this prototype note the following e An error handling
77. LAB Structures Sparse matrices Variable input and output argument lists vararginWarargout New indexing functions try blocks and catch blocks Introduction e Automated memory management for temporary variables e Improved mbui d script Unsupported MATLAB Features The library does not indude any Handle Graphics or Simulink functions In addition the library does not support the following MATLAB features e Objects e MATLAB integer types int8 int16 int32 uint8 uint16 and uint32 e Functions that require the MATLAB interpreter most notably eval and input Library Routine Naming Convention All routines in the MATLAB C Math Library begin with the prefix ml f The name of every routine in the MATLAB C Math Library is derived from the corresponding MATLAB function For example the MATLAB function sin is represented by the MATLAB C Math Library function ml f Si n The first letter following theml f prefix is always capitalized MATLAB C Math Library Documentation The documentation that supports Version 2 0 of the library includes e MATLAB C Math Library User s Guide This manual provides tutorial information about the library This manual is also available in PDF format accessible through the Help Desk e MATLAB C Math Library Reference The reference pages for all the MATLAB C Math library routines are availablein HTML and PDF versions accessible through the Help Desk How This Book Is Organiz
78. LL mi fEndCatch 8 7 8 Handling Errors and W riting a Print Handler 8 8 mfPrintf Now in application after catch block n mxDestroyArray mat 0 mxDestroyArray mat1l mxDestroyArray mat 2 mi fRestorePreviousContext 0 0 return EXIT SUCCESS Notes 1 Variables that will be set within a try block must be declared as volatile When a variable is declared as vol atile itis not storedin a register You can therefore assign a value to the variable inside the try block and still retrieve the value ml f Tr y macro defines the beginning of the try block The exampe deliberately triggers a warning by attempting to divide by zero and an error by calling mi f PI us with two input matrices of unequal size The ml f Cat ch macro defines the beginning of the catch block The error handling code in this catch block is quite simple It displays a message n my catch block Caught an error and then prints out the message associated with the last error by passing the return value of the ml flLastErr routinetotheml f Print Matrix routine Theml f Endcatch macro marks the end of the catch block After the catch block completes executing the application continues freeing the matrices mat 0 mat 1 and mat 2 which were used as input arguments to ml fPlus andmlfRdivide Handling Errors The program produces this output WARNING Divide by zero Return to try block after warning
79. MATLAB API routines accept integer arguments int ndim 3 int dims 3 3 3 2 int bytes_to_copy 3 3 2 sizeof double double data 1 4 7 2 5 8 3 6 9 10 13 16 11 14 17 12 15 18 double pr NULL mxArray A NULL create the array ml f Assign amp A mxCreateNumericArray ndim di ms mx DOUBLE CLASS mx REAL get pointer to data in array pr mxGet Pr A copy data to pointer memcpy pr data bytes to copy mi f Print Matrix A mxDestroyArray A This program displays the following output 1 Te we 3 4 5 6 E 8 ages 10 11 12 13 14 15 16 17 18 3 13 3 W orking with MATLAB Arrays 3 14 Column Major Storage versus Row Major Storage It is important to note in the previous example that the MATLAB C Math Library stores its arrays in column major order unlike C which stores arrays in row major order Static arrays of data that are declared in C and that initialize MATLAB C Math Library arrays must store their data in column major order For this reason we recommend not using two dimensional C language arrays to initialize a MATLAB array because the mapping of array elements from C to MATLAB can become confusing As an example of the difference between C s row major array storage and MATLAB s column major array storage consider a 3 by 3 matrix filled with the numbers from one to nine Notice how the numbers follow one another down the c
80. MATLAB Arrays When you create a MATLAB array using any of the array creation mechanisms the MATLAB C Math Library allocates the storage for the array The responsibility for freeing the allocated storage is shared between you and the library automated memory management facility When automated memory management is enabled all the arrays returned by library routines are temporary That is when these arrays are passed to another library routine that routine destroys the array before returning This capability allows you to nest or compose calls to MATLAB C Math Library routines without causing memory leaks The calls totheml f Scal ar routine which are nested in the examples in this chapter illustrate routine nesting If your application needs to use an array several times you must assign the array toan mxArray pointer variable to make it persist This is called binding thearray toa variable You usethenl f Assi gn routineto bind an array toan array pointer variable Arrays returned as output arguments are bound to variables automatically by the library Any array you bind to a variable you must explicitly free Use the mx DestroyArray routine to free bound arrays All the code examples in this chapter assume that the MATLAB C Math Library automated memory management is enabled For information about enabling memory management see Chapter 4 Displaying MATLAB Arrays To output an array to the display use the MATLAB C Math Library
81. MATLAB C Math Library The Language of Technical Computing Computation m Visualization Programming I MATH WORKS User s Guide as Version 2 X OD d How to Contact The MathW orks 508 647 7000 Phone 508 647 7001 Fax The MathWorks Inc Mail 24 Prime Park Way Natick MA 01760 1500 http www mathworks com Web ftp mathworks com Anonymous FTP server comp soft sys matlab Newsgroup support mathworks com Technical support suggest mathworks com Product enhancement suggestions bugs mat hworks com Bug reports doc mathworks com Documentation error reports subscribe mathworks com Subscribing user registration service mathworks com Order status license renewals passcodes inf o mathworks com Sales pricing and general information MATLAB C Math Library User s Guide COPYRIGHT 1984 1999 by The MathWorks Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or repro duced in any form without prior written consent from The MathWorks Inc U S GOVERNMENT If Licensee is acquiring the Programs on behalf of any unit or agency of the U S Government the following shall apply a For units of the Department of Defense the Government shall have only the rights specified in the license under which the commercial computer software or commerci
82. O O amp O ooo WoO UO DO CO a e a D D O eS ea a a a em ooo WoO UO DOD CO Converting a Sparse Matrix to Full Matrix Format You can convert a sparse matrix toa full format matrix by usingtheml f Ful routine The previous example nested a call to this routinein ml f Pri nt Matrix toshow the pattern created by the values in the sparse matrix mf PrintMatrix mlfFull F Evaluating Arrays for Sparse Storage Toseeif a MATLAB array is a good candidate for sparse format storage determine the number of nonzero elements in an array using the ml f Nnz routine The following code fragment creates the same 12 by 12 identity matrix shown in the example in Converting an Existing Matrix into Sparse 3 23 3 W orking with MATLAB Arrays 3 24 Format on page 3 19 and then prints out the number of nonzero elements in the matrix mxArray I NULL Create the array m fAssign amp l mlfEye mlfScalar 12 NULL Determine the number of nonzero elements mf Print Matrix mlfNnz l mxDestroyArray l This code outputs the number of nonzero elements in the 12 by 12 identity matrix 12 W orking with MATLAB Character Arrays Working with MATLAB Character Arrays The MATLAB C Math Library alsoincludes routines to create and manipulate character arrays One dimensional character arrays are also called strings Multidimensional character arrays arealsocalled arrays of strings In an array of str
83. Restrictions on Function Calling Function Uses Automated Memory Management If you write a new function that uses the MATLAB C Math Library s automated memory management functions that start with ml f EnterNewContext and end with ml f RestorePreviousContext you can e Call other new functions that you ve written with automated memory management e Call MATLAB C Math Library Version 2 0 functions Y ou cannot e Call a function that you wrote with the MATLAB C Math Library prior to Version 2 0 e Call a new function that you ve written without using automated memory management unless the function does not manipulate arrays Note Functions written with or without automated memory management can call your function Function Does Not Use Automated Memory Management If you write a new function that does not use the library s automated memory management declares temporary variables does not nest calls to the library functions you can e Call a function that you wrote with the MATLAB C Math Library prior to Version 2 0 e Call a new function that you ve written with or without automated memory management e Call MATLAB C Math Library Version 2 0 functions 4 33 4 Managing Array Memory 4 34 Note Functions written without automated memory management can call your function functions written with automated memory management cannot Recommendation Though the explicit approach seems to offer fle
84. S argument specifies that the array should contain double precision values F or a complete list of these class specifiers use the MATLAB Help Desk to view the mx Cl ass_ D online reference page W orking with MATLAB N umeric Arrays Notein the example that the arguments specifying the number of dimensions ndi m and the size of these dimensions di ms do not need to be converted into a MATLAB array The MATLAB API routines accept integer arguments int ndim 37 Number of dimensions int dims 3 3 3 2 Size of dimensions mxArray A NULL declare pointer to mxArray ml f Assign amp A mxCreateNumericArray ndim di ms mx DOUBLE CLASS mx REAL mi f Print Matrix A mxDestroyArray A This code creates the following 3 by 3 by 2 array eee ae 0 0 0 0 0 0 0 0 0 cael 0 0 0 0 0 0 0 0 0 For information about initializing this array with data see Initializing a Numeric Array with Data on page 3 12 Creating Commonly Used Numeric Arrays The MATLAB C Math Library includes several routines that create commonly used multidimensional arrays e Array of ones ml f Ones e Array of zeros ml f Zeros e Identity matrices ml f Ey e e Random numbers ml f Rand 3 7 3 W orking with MATLAB Arrays e Normally distributed random numbers ml f Randn e Magic squares limited to two dimensions ml f Magi c With all these routines the number of dimensions in the
85. You specify these arrays as output arguments passed to the ml f Varargout routine For more information about calling library routines that take variable number of input and output arguments see Chapter 6 The following code returns the dimensions in three output arguments di m1 di m2 and di m3 When used with output arguments you donot need to bind the 3 45 3 W orking with MATLAB Arrays 3 46 return value from ml f Si ze toa variable The routine binds the return values to the output arguments specified As with all bound arrays you must explicitly free them ml fSize mlfVarargout amp di ml amp di m2 amp di m3 NULL C NULL mxDestroyArray di ml mxDestroyArray di m2 mxDestroyArray di m3 If the array has more dimensions than the number of output arguments specified the last output argument contains the product of the remaining dimensions Determining the Shape of an Array To determine the number of dimensions of an array use the ml f Ndi ms routine This code uses ml f Ndi ms to get the number of dimensions of a 2 by 3 by 2 array mxArray A NULL mxArray ndims NULL Create three dimensional array ml fAssign amp A milf Ones milf Scalar 2 ml fScalar 3 ml fScalar 2 NULL Determine dimensions ml fAssign amp ndims mifNdims A ml fForintf ml fScalar 1 mxCreateString The array has d dimensions ndi ms NULL mxDestroyArray A mxDes
86. a cell array index to obtain an array reference that returns multiple values For example given thevarar gin function void mfVarargin_Func mxArray A mxArray B you can make the following call ml fVarargin_Func A B m flndexRef C mfColon mlfScalar 1 mlfScalar 5 NULL NULL A andB pointers to existing mx Ar rays are passed as explicit arguments C isa pointer to a cell array that contains at least five cells The embedded call to ml fl ndexRef uses the index 1 5 to return multiple values the first five cells of c The MATLAB C Math Library passes these as individual arguments tomi fVarargin_Func 6 32 Replacing Argument Lists with a Cell Array Positioning the Indexed Cell Array e Pass the return from the cell array indexing operation as one of the variable length arguments in the input argument list That reference identifies multiple arrays e Do not pass the return from a cell array indexing operation as an explicit argument For example you cannot make this call tothe examplevar ar gi n function mlfVarargin_Func mlflndexRef C mfColon mlfScalar 1 mfScalar 5 NULL A B NULL Given the definition of ml f Varargin_Func the first argument position is reserved for an explicit single argument The MATLAB C Math Library does not handle multiple values in an explicit position e You can pass other array arguments or other cell array indexing expressions before or afte
87. a field number and an index Set imaginary data pointer for an mx Array Set their array of asparsemxArray Set thej c array of a sparse mxArray Set the logical flag 9 49 9 Library Routines 9 50 Array Access Routines Continued Function Purpose mxSetM mxSetN mx Set Nz max mxSet Pi mxSet Pr Set the number of rows M and columns N of an array Set the storage space for nonzero elements Set the real and imaginary parts of an mxArray Fortran Interface Function Purpose mxCopyCharacterToPtr mxCopyPtrToCharacter mxCopyCompl exl6toPtr mxCopyPtrToCompl ex16 mxCopyl nteger4ToPtr mxCopyPtrTolnteger4 mxCopyReal 8toPtr mxCopyPtrToReal 8 Copy CHARACTER values from Fortran toC pointer array Copy CHARACTER values from C pointer array to Fortran Copy COMPLEX 16 values from Fortran to C pointer array Copy COMPLEX 16 values to Fortran from C pointer array Copy NTEGER 4 values from Fortran to C pointer array Copy NTEGER 4 values to Fortran from C pointer array Copy REAL 8 values from Fortran toC pointer array Copy REAL 8 values to Fortran from C pointer array Directory Organization Directory Organization on UNIX lt matlab gt bin lt matlab gt extern lib ARCH Stove fe A lt matlab gt extern indude 2 4 2 y lt matlab gt extern examples cmath aa Directory Organization on Microsoft Windows lt matlab gt bin aaa a lt ma
88. ains bound ml fRestorePrevi ousContext then performs an important action it deletes any input array arguments that are temporary Backward Compatibility Note mi fRestorePrevi ousContext recognizes when the current function is called from a function that does not use automated memory management In that call context where all arrays are temporary it does not delete any arrays Purpose of mlfRestorePreviousContext This is the key step that allows a call to another function to be embedded as an input argument to your function Your function deletes the temporary arrays passed to it ensuring proper deletion of the memory for temporary arrays Returning an Array from Your Function Before you pass an array tother et urn statement in your function you must pass that array toml f ReturnValue mi f ReturnVal ue makes the array a temporary array Your function can therefore return a temporary array just like each function in the MATLAB C Math Library does W riting Functions Under Automated Memory Management Prototype mxArray mlfReturnValue mxArray a Sample Call from Template return ml fReturnValue local_return value Note You cannot have multipler et urn statements in your function You must code in a style that ends your function with a call to ml fRestorePreviousContext followed by asinglereturn statement return mlfReturnValue result Argument and Return for mifReturnValue Pass the arr
89. ains the main program Keepin mind that in aworking program all parts appear in the same file int main mxArray tm NULL ym NULL tsm NULL ysm NULL double tspan 0 0 10 0 double yO 10 0 10 0 10 0 double t yl y2 y3 int k n ml fEnterNewContext 0 0 mi fFevalTableSetup MFuncTab SI GMA 10 0 RHO 28 0 BETA 8 0 3 0 m fAssign amp tsm mifDoubleMatrix 2 1 tspan NULL ml fAssign amp ysm mifDoubleMatrix 1 3 y0 NULL ml fAssign amp tm m fOde23 amp ym mfVarargout NULL mxCreateString lorenz tsm ysm NULL NULL n mxGet M tm t mxGet Pr tm yl mxGetPr ym y2 yl n y3 y2 n m fPrintf t yl y2 y3 n for k 0 k lt n k mifPrintf 9 3f 9 3f 9 3f 9 3f n tik ylik y2 k y3 k Passing Functions As Arguments to Library Routines Free the matrices mxDestroyArray tsm mxDestroyArray ysm mxDestroyArray tm mxDestroyArray ym ml fRestorePreviousContext 0 0 return EXIT SUCCESS N otes 1 Declare and initialize variables t span stores the start and end times y0 is theinitial value for the or enz iteration and contains the vector 10 0 10 0 10 0 Add your function table entry to the MATLAB C Math Library built in feval function table by calling mi f Feval Tabl eSetup The argument MFuncTab associates the string orenz with a pointer tothel or enz function and a pointer
90. akethe first output argument the return value from the function 4 Pass any other output arguments as the first arguments to the function If the function accepts any number of output arguments pass those arguments toml f Varargout ormlflndexVarargout in the last output argument position 5 PassaNULL argument wherever an optional output argument does not apply to the particular call you re making 6 Passtheinput arguments totheC function following theoutput arguments If the function accepts any number of input arguments pass those arguments as the last input arguments 6 13 6 Calling Library Routines 6 14 7 Pass aNULL argument wherever an optional input argument does not apply to the particular call Passing the wrong number of arguments to a function causes compiler errors Passing NULL in the place of a required argument causes runtime errors Note Theonline MATLAB C Math Library Reference does the mapping between MATLAB and C functions for you Access the Referencefrom the Help Desk Exceptions to the Calling Conventions Theml fLoad ml fSave andml fFeval functions do not follow the standard calling conventions for the library For information about ml f Load and ml f Save seeChapter 7 For information about ml f Feval see Passing Functions As Arguments to Library Routines on page 6 20 Example Program Calling Library Routines ex3 c This example program illustrates how to call
91. al software documentation was obtained as set forth in subparagraph a of the Rights in Commercial Computer Software or Commercial Software Documentation Clause at DFARS 227 7202 3 therefore the rights set forth herein shall apply and b For any other unit or agency NOTICE Notwithstanding any other lease or license agreement that may pertain to or accompany the delivery of the computer software and accompanying documentation the rights of the Government regarding its use reproduction and disclo sure are as set forth in Clause 52 227 19 c 2 of the FAR MATLAB Simulink Stateflow Handle Graphics and Real Time Workshop are registered trademarks and Target Language Compiler is a trademark of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Printing History October 1995 First printing J anuary 1998 Revised for Version 1 2 J anuary 1999 Revised for Version 2 0 Release 11 Getting Ready 1 Introduction oes rcs SE EE Bic ees ete bone 1 2 Who Should Read This Book 00 00 0c eee eee 1 2 New MATLAB C Math Library Features 1 2 Unsupported MATLAB Features 0 00005 1 3 Library Routine Naming Convention 00 1 3 MATLAB C Math Library Documentation 1 3 How This Book Is Organized 00e eee eee 1 3 Accessing Online Reference Documentation 1 4 Additional Sources of Inf
92. al Operator Functions Function Purpose ml f Xor Logical exclusive or operation Set Operators Function Purpose m flntersect Set intersection of two vectors Logical Functions Function Purpose ml flsieee True for IEEE floating point arithmetic ml fl sspace True for whitespace characters in string matrices 9 24 MATLAB M File M ath Library Logical Functions Continued Function Purpose mi fl sstudent True for student editions of MATLAB ml fl suni x True on UNIX machines ml f 1s vms True on computers running DEC s VMS MATLAB As a Programming Language Function Purpose ml f Nar gchk Validate number of input arguments ml f Xyzchk Check arguments to 3 D data routines Elementary Matrices and Matrix Manipulation Elementary Matrices Function Purpose ml f Aut omesh True if the inputs require automatic meshgriding ml fLinspace Linearly spaced vector ml fLogspace Logarithmically spaced vector ml f Meshgrid X and Y arrays for 3 D plots Basic Array Information Function Purpose ml flsnumeric True for numeric arrays 9 25 9 Library Routines Matrix Manipulation Function Purpose ml f Cat Concatenate arrays mf Fliplr Flip matrix in the left right direction ml f Fl i pud Flip matrix in the up down direction ml fl permute Inverse permute array dimensions ml f Rep mat Replicate and tile an array ml fReshape Chang
93. allocated for them 3 19 3 W orking with MATLAB Arrays In the example the NULL s included in the call toml f Sparse represent optional arguments The following section describes these optional arguments 3 20 mxArray A N mxArray B N Create the ml fAssign amp A mi f Print Matrix Convert the ml fAssign amp B m mi f Print Matrix mxDestroyArray mxDestroyArray ULL ULL identity matrix ml fEye ml fScalar 12 NULL A identity matrix to sparse format fSparse A NULL NULL NULL NULL NULL B A Free bound arrays B W orking with MATLAB Sparse M atrices This code displays the identity matrix in full and sparse formats 0 e e e COCO COO OO Fe ooo A COCO OOO OF Oo ooo e CC CO OF OO GO oooococCcCOFRDO OOO O ooocoCOoOrFrROOWO OOO Go ooorccacCO CWO OO O ooo CcC CCC COC OF ooo CcCC CWC OrF OO O ooocoorRrOCOO OOO O O oor COC COCO COCO OOO O oro CC COCO CWO OOo WO OAD OH amp WP PE H a 10 1 1 11 1 12 1 RRO OH D MH S amp S WwW PP Pe m o Creating a Sparse Matrix from Data You can create a sparse matrix specifying the value and location of all the nonzero elements when you create it Using ml f Sparse you specify as arguments e Two vectors andj that specify the row and column subscripts of the nonzero elements e One vector s containing the real or comple
94. alue0 1 0i ml fI nf Infinity ml f J Return an array with the value0 1 0i ml f Nan Not a N umber ml f Pi 3 1415926535897 ml f Real max Largest floating point number ml f Real min Smallest floating point number Matrix Manipulation Function Purpose ml f Diag Create or extract diagonals ml f Per mute Permute array dimensions ml f Tri Extract lower triangular part ml f Tri u Extract upper triangular part Specialized Matrices Function Purpose ml f Magi c Magic square 9 11 9 Library Routines Elementary Math Functions Trigonemetric Functions Function Purpose ml f Acos Inverse cosine ml f Asin Inverse sine ml fAtan Inverse tangent ml f Atan2 Four quadrant inverse tangent ml f Cos Cosine ml f Sin Sine ml f Tan Tangent Ex ponential Functions Function Purpose ml f Exp Exponential ml flog Natural logarithm ml fLog2 Base 2 logarithm and dissect floating point numbers ml f Pow2 Base 2 power and scale floating point numbers ml fSqrt Square root Complex Functions Function Purpose ml f Abs Absolute value ml f Conj Complex conjugate ml f 1 mag Imaginary part of a complex array 9 12 The MATLAB Builtln Library Complex Functions Continued Function Purpose ml fl sreal True for noncomplex matrices ml f Real Real part of a complex array Rounding and Remainder Functions Fun
95. ample To retrieve data from nested structures you only need a single call to ml f ndexRef Simply specify the nested structure reference operation in the second argument as shown here m fAssign amp y miflndexRef images date year mlfScalar 2 y images 2 date year performs the same operation in MATLAB Indexing into MATLAB Structure Arrays You can also assign to this location by using ml fl ndexAssign instead of ml flndexRef Note You can only reference or assign to single instances of nested structures Though you might expect this MATLAB code y images date year tosety tothe array of years in thedate field of the images structure array this code generates an error because the result of images date is a Structure array rather than a single structure It is also an error in the MATLAB C Math Library Accessing the Contents of Structures Within Cells Cell arrays can contain structure arrays and vice versa Accessing a structure stored in a cell array is very similar to accessing a structure stored in a regular variable you just need to extract it from the cell array first You use ml f ndexRef tocombineall the operations intoa single call Assume the cell array c contains a three element structure array of images You can combine cell array and standard indexing to access a single field of a single structure ml fAssign amp second date miflndexRef c mlfScalar 2 date mf Scalar
96. any function that it calls 9 Return a temporary array ml f Ret urnVal ue marks its argument as temporary You must pass any mx Array that your function returns to ml fReturnValue before passing it tother et urn statement If you forget this step the automated memory management of the library will be disrupted for the variable that you return and memory will leak Example Program M anaging Array Memory ex2 c The second section of code contains the main program int main mxArray matQ NULL mxArray output_array NULL mxArray result_array NULL mfEnterNewContext 0 0 ml fAssign amp matO ml fDoubleMatrix 2 3 real_datal NULL ml fAssign amp result_array Automated Mem Exampl e amp output_array mat 0 ml f Doubl eMatrix 2 3 real_data2 NULL mifPrintf matd n ml f Print Matrix mat0 ml fPrintf output array n ml fPrintMatrix output_array m fPrintf result_array n ml fPrintMatrix result_array mxDestroyArray mat0 mxDestroyArray result_array mxDestroyArray output_array mi fRestorePreviousContext 0 0 return EXIT_ SUCCESS Notes The numbers in the list below correspond to the numbered sections of code above 1 Initialize any local array variables toNULL MATLAB C Math Library functions that use automated memory management require that you initialize any output arguments toNULL or a valid array F or example before you call ml f Assi gn
97. ar 1 5 57 5 Indexing into Arrays Table 5 2 MATLAB C Indexing Expression Equivalence Continued Description MATLAB Expression C Expression Result Extract third element X 3 ml fl ndexRef 5 X a ml fScalar 3 Extract all elements into X mi fl ndexRef 4 column vector X 6 bat he 5 mi f CreateCol onl ndex 7 Extract first row X 1 ml fl ndexRef 4 5 X ae a a ae mfScalar 1 ml f CreateCol onl ndex Extract second row X 2 ml fl ndexRef 6 7 X SET aa mfScalar 2 mi f CreateCol onl ndex Extract first column Xa T mi fl ndexRef 4 X 6 Men ml f CreateColonindex ml fScalar 1 5 58 Comparison of C and MATLAB Indexing Syntax Table 5 2 MATLAB C Indexing Expression Equivalence Continued Description MATLAB Expression C Expression Result Extract second column X 2 ml fl ndexRef 5 X 7 EASI eae mi f CreateColonindex ml fScalar 2 Replace first element X 1 9 ml fl ndexAssign 9 5 with 9 amp X 6 7 pea aes ml fScalar l ml fScalar 9 MM Replace first row with X 1 f 11 12 ml fl ndexAssi gn 11 12 11 12 amp X 6 7 ot Decne ee m fScalar l ml f CreateColonindex ml f Horzcat mf Scalar 11 mf Scalar 12 NULL E 5 59 5 Indexing into Arrays Table 5 2 MATLAB C Indexing Expression Equivalence Continued Description MATLAB Expression C Expression Result Replace element 2 1 with 9 X
98. array mxCreateString Eric NULL ml fCellhcat mlfComplexScalar 2 4 mifScalar 7 NULL NULL Note that you can t just place this single line of code into a function you need to follow the conventions for this coding style using automatic memory management See Assumptions for the Code E xamples on page 5 16 for the conventions used in the examples Overview A cell array is a regularly shaped N dimensional array of cals Each cell is capable of containing any type of MATLAB data including another cell arrays When using cell arrays you must be careful to distinguish between the data values stored in the cells and the cells themselves which are data values in their own right MATLAB supports two types of indexing on cell arrays The first standard indexing uses parentheses and allows you to manipulate the cells in a cell array The second cell array indexing uses braces to manipulate the data values stored in the cells For example given the cell array N above N 2 2 isthescalar7 butN 2 2 is a 1 by 1 cell array a single cell containing the scalar 7 Tips for Working with Cell Arrays e Cell arrays must be regularly shaped All rows must have the same number of columns and all columns the same number of rows This requirement extends into dimensions higher than two as well For example all pages must be the same size in a three dimensional cell array e You can t do arithmetic on a cell Y
99. at directory does not exist on this machine Use directory name anyway y n Using thes et up option sets your default compiler so that the new compiler is used every time you use the mbui d script Modifying the Options File Another use of thes et up option is if you want to change your options file settings For example if you want to makea changethe current linker settings or you want to disable a particular set of warnings use thes et up option Theset up option copies the appropriate options file to your user profile directory and names it compopts bat Make your user specific changes to compopts bat in the user profile directory and save the modified file This sets your default compiler s options file to your specific version Table 1 4 lists the names of the PC master options files included in this release of the MATLAB C Math Library If you need to see which options mbui d passes to your compiler and linker use the verbose option v as in mbuild v filenamel filename2 to generate a list of all the current compiler settings used by mbui d You can also embed the settings obtained from the verbose option into an integrated development environment IDE or makefile that you need to maintain outside of MATLAB Often however it is easier to call mbui d from your makefile See your system documentation for information on writing makefiles Building a Stand Alone Application on Microsoft W indows
100. ated memory management new in Version 2 0 of the library e Explicit memory management In versions of the MATLAB C Math Library prior to Version 2 0 explicit memory management was the only memory management technique It is still available and existing code is compatible with the routines that use automated memory management See Restrictions on F unction Calling on page 4 33 to learn about the compatibility between the two styles of managing memory You must choose either automated memory management or explicit memory management to manage array memory in your application We strongly recommend that you choose the automated memory management technique because of the benefits it offers 4 3 4 Managing Array Memory 4 4 e You can embed calls to library functions as function arguments e You don t need to declare mx Array variables to store temporary values or explicitly delete those temporary arrays e Your code is typically more compact and more readable A formula that contains multiple function calls can be written as a single line of code rather than several For example compare the MATLAB code z sin x cos y to this C code that uses automated memory management m fAssign amp mf Plus mfSin x mlfCos y and then to this C code that uses explicit memory management mxArray temp_x temp_y temp_x ml fSin x temp_y ml fCos y z mfPlus tempx temp_y mxDestroyArray temp_x mxDestroyArr
101. ath Library Apply this technique to every function you write This section presents an annotated example Example Without Automated Memory Management on page 4 31 shows comparable code that does uses explicit memory management Each of the numbered sections of code is explained in more detail below You can find the codefor the examplein lt mat ab gt extern exampl es cmath ex2 c where lt mat ab gt represents the top level directory of your installation See Building C Applications in Chapter 1 for information on building the examples The example is split into two parts In a working program both parts would be placed in the same file The first part includes header files declares twofile static variables and defines a routine that demonstrates how the library manages array memory The second section contains the main program 4 24 Example Program M anaging Array Memory ex2 c Qe ea He Sy e i nc i nc i nc i nc stat stat mx Ar X20 F ude lt stdio h gt ude lt stdlib h gt used for EXIT _SUCCESS ude lt string h gt ude matlab h ic double real _datal ic double real _data2 1 2 3 4 5 6 6 5 4 3 2 1 ray Automated_Mem Example mxArray z_out mxArray x_in mxArray y_in mxArray result_local NULL mxArray q_local NULL ml fEnterNewContext 1 2 z_out x_in y_in Iin MATLAB result sqrt sin x cos x ml fAssign amp
102. ay as their first argument Specifying the Index String Y ou pass an indexing string as the second argument to an indexing function An indexing string is always surrounded by For example the MATLAB indexing expression A 2 1 is written like this in the MATLAB C Math Library mi fIndexRef A mfScalar 2 mlfScalar 1 7 7 is the indexing string that specifies a two dimensional index The question mark iS a placeholder for each index value 5 11 5 Indexing into Arrays 5 12 e f you re indexing into a regular array use parentheses to enclose the subscript e f you re indexing into a cell array use braces to enclose the subscript Some more sample indexing strings standard indexing cell array indexing 7 y combined standard structure and cell array indexing Table 5 1 Elements of Index String Syntax Syntax Definition Example Element e Encloses an array subscript EP Encloses a cell array subscript 7 i Separates dimensions of the subscript Placeholder for a single array index 2 value field Indicates a field in a structure score What an Indexing String Specifies When you specify an indexing string you provide the following information to the indexing functions e Number of dimensions in the subscript For example the single in indicates a one dimensional subscript The three sin
103. ay being modified to ml f I ndexAssign asan mxArray rather than themxArray that ml flndexRef requires images 17 description Cloned sheep embryo 1 performs the same operation in MATLAB 5 53 5 Indexing into Arrays 5 54 Assigning Values to Elements in a Field By using ml fI ndexAssign you can also modify array data contained ina structure field You must specify the field name and the type of indexing to perform on the contained array For example the following call to ml fI ndexAssi gn replaces a 3 by 3 subarray of the image data of the ninth image with the data in the 3 by 3 array x You might do this as part of some image processing operation ml fl ndexAssign amp i mages image ml fScalar 9 mfColon mlfScalar 1 mlfScalar 3 NULL mfColon mlfScalar 2 mlfScalar 4 NULL x images 9 image 1 3 2 4 x performs the same operation in MATLAB Referencing a Single Structure in a Structure Array To access a single structure within the structure array use the standard array indexing function ml f ndexRef For example to reference the forty second image structure in a structure array use this code ml fAssign amp B mflndexRef images mlfScalar 42 B images 42 performs the same operation in MATLAB Referencing into Nested Structures Structures can contain other structures The image structure used in these examples contains a date structure for ex
104. ay temp_y Using automated memory management makes your code more like MATLAB The code is easier to write easier to read and far less likely to leak memory Using Explicit Memory Management Routines in the MATLAB C Math Library return a pointer toa newly allocated mx Array Versions of the MATLAB C Math Library prior to Version 2 0 required you to follow a strict set of rules to prevent memory leaks You were required to assign the returned mx Array to an array variable before passing it to another function You could not nest calls to library functions When you were finished with an array you were required to explicitly delete it Explicit memory management still works this way All arrays are treated alike Overview Under explicit memory management e You assign a valuetoan mxArray variable in two different ways By using the assignment operator to assign the return value from a library function to an mx Array variable BypassinganmxArray variable uninitialized or initialized toNULL as an output argument to a library function The function assigns a value to it Then you must e Delete each array with mx Dest royArray when you re done using it Because explicit memory management requires that you declare array variables for all your arrays and make calls to mxDestroyArray itis error prone resulting in memory leaks See Example Without Automated Memory Management on page 4 31 for an example of
105. ay that your function returns an mxArray toml f Ret urnValue The array is a bound array when it is passed toml f Ret urnValue andis typically the result of an assignment made within the function or the value of an output argument set by a function call ml f Ret urnVal ue makes the array a temporary array and returns the same array You can nest the call toml f Ret urnValue intheret urn statement for your function You do not need to call ml f Ret urnVal ue if you are writing a function that does not return a pointer toan array in the sameway that themai n template doesn t call mi f Ret urnVal ue Note Dono pass an array input argument to ml f Ret urnVal ue Instead useml f Assign to assign the array toa local variable first and then pass that local variable to ml f Ret urnValue W hat Happens to the Array Argument ml f Ret urnVal ue changes the bound state of the array passed to it to temporary You then pass that array tother et urn statement 4 21 4 Managing Array Memory 4 22 Purpose of mlifReturnValue By marking the returned array temporary you ensure that a call to your function can be nested as an argument to another function without leaking memory Summary of Coding Steps The steps you must take are the same for every function you write 1 Declare the interface for your function Does it return an array Does it take any array output arguments Does it take any array
106. b gt extern include The lt matl ab gt extern incl ude directory contains the header files for developing MATLAB C Math Library applications The header files associated with the MATLAB C Math Library are shown below matlab h li bmatlb h i bmmfile h matrix h Header file for the MATLAB C Math Library Header file containing the prototypes for the MATLAB Built In Math Library functions Header file containing the prototypes for the MATLAB M File Math Library functions Header file containing the definition of the mxArray type and function prototypes for array access routines lt matiab gt extern examples cmath The lt matl ab gt extern exampl es cmath directory contains the sample C programs that are described throughout this book intro c exl c ex2 ex3 c ex4 c ex5 The source code for A Simple Example Program on page 2 2 The source code for Example Program Creating Numeric Arrays ex1 c on page 3 15 The source code for Example Program Managing Array Memory ex2 c on page 4 24 The source code for Example Program Calling Library Routines ex3 c on page 6 14 The source code for Example Program Passing Functions As Arguments ex4 c on page 6 22 The source code for Example Program Saving and Loading Data ex5 c on page 7 4 A Directory Organization A 6 ex6 release txt The source code for Examp
107. ble ASCII _codes 109 121 32 115 116 114 105 110 103 ml fAssign amp i mifDoubleMatrix 1 9 ASCII codes NULL mifPrintMatrix mlfChar i NULL mxDestroyArray A This code produces the following output my string To convert this character array back into its underlying numeric representation in double precision format use the ml f Doubl e routine Creating Multidimensional Arrays of Strings You can create a multidimensional array of MATLAB character strings however each string must have the same length The MATLAB C Math Library routines that create arrays of character strings pad the strings with blanks to make them all a uniform length Note Tocreatea multidimensional character array without padding use cell arrays For more information see Working with MATLAB Cell Arrays on page 3 30 3 27 3 W orking with MATLAB Arrays 3 28 Toillustrate the following code fragment creates a two dimensional array character from two strings of different lengths mxArray A NULL mxArray D1 NULL mxArray D2 NULL create array of strings m fAssign amp A mifChar mxCreateString my string mxCreateString my dog NULL mi f Print Matrix A Get the size of each dimension of the array of strings mi fSize mlfVarargout amp D1 amp D2 NULL A NULL Print out the size of each dimension fFprintf ml fScalar 1 mxCreateString Resulting array is d b
108. brary error processing however does change When you define a try block the library routines do not output an error message to the user and then exit Instead the routines transfer control to your catch block which performs the error handling processing For example if you want to output an error message to the user you must do so from your catch block You can usethenl fLasterr routine to obtain the text of the message associated with the most recent error that occurred 8 5 8 Handling Errors and W riting a Print Handler 8 6 Defining a Try Block A try block is a group of one or more statements enclosed in braces introduced by the ml f Tr y macro ml fTry your code Note that theml f Tr y macro does not require parentheses it is not a procedure call Defining a Catch Block A catch block is a group of one or more routines enclosed in braces introduced by the ml f Cat ch macro and terminated by the ml fEndCatch macro ml f Catch Your code mi f EndCatch The catch block contains error processing code F or example you could put clean up code in your catch block to free allocated storage before exiting The ml f Catch and ml f EndCatch macros do not require parentheses Note Whilethis error handling mechanism is modeled on the C exception handling facility there is no connection between the two The MATLAB C Math Library does not throw exceptions as the MATLAB C Math Lib
109. built in table already exist Example Program Passing Functions As Arguments ex 4 c To illustrate function functions this example program uses the ordinary differential equation ODE solver ml f 0de23 to compute the trajectory of the Lorenz equation Given a function F and a set of initial conditions expressing an ODE ml f 0de23 integrates the system of differential equations y F t y over a given time interval mi f 0de23 integrates a system of ordinary differential equations using second and third order Runge Kutta formulas In this example the name of the function being integrated is orenz Passing Functions As Arguments to Library Routines Oro For convenience this example has been divided into three sections in a working program all of the sections would be placed in a single file The first code section specifies header files declares global variables including the local function table and defines the or enz function FE ex4 c include lt stdlib h gt include matlab h double SIGMA RHO BETA static mlfFuncTabEnt MFuncTab lorenz ml fFuncp lorenz _lorenz_thunk_fcn_ 0 0 0 H mxArray lorenz mxArray tm mxArray ym mxArray ypm NULL double y yp m fEnterNewContext 0 2 tm ym m fAssign amp ypm mifDoubl eMatrix 3 1 NULL NULL y mxGetPr ym yp mxGet Pr ypm yp 0 BETA y 0 y 1 y 2 yp 1 SIGMA y 1 SI GMA y 2 yp 2
110. by n array matrix ml fDoubleMatrix or mxCreateDoubl eMatri x Create a magic square matrix ml f Magi c Create a multidimensional mxCreateNumericArray m by n by p by array Create a numeric array by ml f Horzcat concatenating existing arrays mlfVertcat Create commonly useful ml f Ones multidimensional arrays such as ml f Zeros arrays of ones zeros random ml fRand milf Randn numbers identity matrices and ml f Ey e magic squares ml f Magi c W orking with MATLAB N umeric Arrays Creating Numeric Arrays Tocreatea numericarray use any of the following array creation mechanisms e Using an array creation routine e Calling an arithmetic routine e Concatenating existing arrays e Assigning a value to an element in an array Using Numeric Array Creation Routines The MATLAB C Math Library contains many routines that create various types of numeric arrays including scalar arrays vectors matrices multidimensional arrays and some commonly useful arrays Creating Scalar Arrays The simplest way to create an array is to use the ml f Scalar routine When you pass this routine a numeric value it creates an 1 by 1 numeric array containing the value stored in double precision format Whenever you have to pass a numeric value to a library routine you can useml fScalar Creating Two Dimensional Arrays Matrices Because two dimensional arrays of double precision values are used so oft
111. cates whether you want to overwrite or update the data in the file The variable argument list consists of at least one pair of arguments the name you want to assign tothe variable you re saving and the address of the mxArray variable that you want to save The last argument to ml fSave is always a NULL which terminates the argument list e You must name each mxArray variable that you save to disk A name can contain up to 32 characters e You can save as many variables as you want in a single call tomi fSave e Thereis no call that globally saves all the variables in your program or ina particular function Overview e The name of a MAT file must end with the extension mat The library appends the extension mat tothe filename if you do not specify it e You can either overwrite or append to existing data in a file Pass w to overwrite u to update append or w4 to overwrite using V4 format e The file created is a binary MAT file not an ASCII file Using mlifLoad to Read Data from a File Using ml f Load you can read in mxArray data froma binary MAT file The prototype for ml f Load void mlfLoad mxArray file wheref i e points to an mx Array containing the name of the MAT file and the variable argument list consists of at least one pair of arguments the name of the variable that you want to load and a pointer to the address of an mx Array variable that will receive the data The last argument
112. cause it is easier to understand two dimensional arrays most of the examples in this section deal with two dimensional arrays See Extending Two Dimensional ndexing to N Dimensions on page 5 29 to learn how to work with arrays of dimension greater than two To use the code samples in your own code see Assumptions for the Code Examples on page 5 16 which explains the conventions used in the examples Overview An N dimensional subscript contains N indices The first index is the row index the second is the column index the third the page index and so on When you use the MATLAB C Math Library to perform N dimensional indexing you pass ml f ndexRef N index arrays as arguments that together represent the subscript the first index array argument stores the row index the second the column index the third the page index etc Each index array can store a scalar vector matrix or the result from a call to the function ml f Creat eCol onl ndex 5 23 5 Indexing into Arrays 5 24 The size of the indices rather than the size of the subscripted matrix determines the size of the result the size of the result is equal to the product of the sizes of the N indices For example assume matrix A is set to wn e ao uw PA wo oom If you index matrix A with a 1 by 5 vector and a scalar the result is a five element vector five elements in the first index times one element in the second index If you index matrix A wit
113. ccessing Individual Strings in an Array of Strings 3 29 Working with MATLAB Cell Arrays 3 30 Creating Cell ArrayS 0 0 00 cece es 3 30 Using the Cell Array Creation Routine 3 31 Using Cell Array Conversion Routines 05 3 31 Using Concatenation to Create Cell Arrays 3 32 Using Assignment to Create Cell Arrays 3 34 Displaying the Contents of a Cell Array 4 3 34 Working with MATLAB Structures 3 37 Creating Structures 0 0 0 0 c ee ee 3 38 Using a Structure Creation Routine 2 4 3 38 Creating Multidimensional Arrays of Structures 3 38 Using a Structure Conversion Routine 3 39 Using Assignment to Create Structures 3 40 Performing Common Array Programming Tasks 3 41 Allocating and Freeing MATLAB Arrays 3 41 Displaying MATLAB Arrays 000 cece eee eee 3 41 Formatting Output 0 0 cee ee 3 42 Determining Array Type 00 e eee eee 3 43 Determining the Size of an Array 000 0c ee eee 3 44 Obtaining the Length of a Single Dimension 3 45 Returning the Dimensions in Separate Arrays 3 45 Determining the Shape of an Array 2 00000 00 3 46 Managing Array Memory 4 OVOP VI OW rererere e ee a a ki E EA Soe 4 2 Why Choose Automated Memory Mana
114. ce changes A to wn e Dwr won amp Using mlflndexAssign for Assignments Assigning to All Elements You can use the colon index to replace all elements in a matrix with alternate values The colon index however is infrequently used in this context because you can accomplish approximately the same result by using assignment without any indexing For example although you can write ml fl ndexAssign amp A ml fCreateCol onl ndex ml fRand ml fScalar 3 NULL writing ml fAssign amp A milf Rand mlfScalar 3 NULL is simpler The first statement reuses the storage already allocated for A The first statement will be slightly slower because the elements from the source must be copied into the destination Note mifRand mlfScalar 3 NULL is equivalent to mi fRand mfScalar 3 mlfScalar 3 NULL Extending Two Dimensional Assignment to N Dimensions Two dimensional assignment extends naturally to N dimensions simply use more index arguments Let A be a 3 by 3 by 2 three dimensional array two 3 by 3 pages Page 1 wn e au pe wo com Page 2 10 13 16 11 14 17 12 15 18 5 39 5 Indexing into Arrays 5 40 Then theMATLAB expression A 2 eye 3 changes page 2 tothe 3 by 3 identity matrix A 1 ones 1 3 2 changes row 1 on both pages to be all ones A 2 2 2 42 changes the element at the middle of page 2 the number 14 to the number 42 and so on It is very si
115. cell arrays to process variable length argument lists the translation from a call toa MATLAB varargin function toa call tothe MATLAB C Math Library function is straightforward You invoke ml f Cat likethis m fAssign amp B mfCat mf Scalar 2 A1 A2 A3 A4 A5 A6 NULL whereB isan mxArray variable initialized toNULL The six A matrices are alsomx Array variables Note Always terminate the argument list toavarar gi n function with a NULL argument How Pure Varargin Functions Differ Some MATLAB functions take avarargin argument as their only input argument and are therefore called purevarargin functions For example function output_argl Example Pure Varargin varargin declares a purevarargin function in MATLAB How to Call MATLAB Functions Because the C language requires at least one explicit argument in the definition of avarargin function this purevarargin function translates to mxArray Example Pure Varargin mxArray input_argl where input_arg1 isthe first of thevarargin parameters even though it is an explicit argument Passing Any Number of Outputs Some MATLAB functions return any number of outputs In MATLAB these functions are called varar gout functions When the variablevar ar gout appears as the last output argument in the definition of a MATLAB function that function can return any number of outputs starting at that position in the argument list When you call avarargout functi
116. ch of the indicated rows this operation A 1 2 1 3 2 in MATLAB selects the column elements at the specified column positions F or example ml f Assi gn amp B ml flndexRef A mi fHorzcat mlfScalar 1l mlfScalar 2 NULL mi f Horzcat mlfScalar 1 ml fScalar 3 mi fScalar 2 NULL selects the first third and second in that order elements from rows 1 and 2 yielding 174 28 5 Notice that the result has two rows and three columns The size of the result matrix always matches the size of the index vectors the row index had two elements the column index had three elements The result is 2 by 3 5 27 5 Indexing into Arrays 5 28 Theindexing routines treat a matrix index as onelong vector moving down the columns of the matrix The loop for a subscript composed of a matrix in the row position and a vector in the column position works like this for each column in the row index matrix B for each row J in the Ith column of B for each element K in the column index vector select the matrix element A B I J K For example let the matrix B equal 11 2 3 Then the expression mi fI ndexRef A B ml fHorzcat mlfScalar 1 mlfScalar 2 NULL performs the same operation as A B 1 2 in MATLAB and selects the first second first and third elements of columns 1 and 2 wr re ofr UU p Selecting Entire Rows or Columns Use a colon index and a vector or matrix index to select multiple ro
117. charge and available to all customers e E mail at servi ce mat hworks com e Telephone at 508 647 7000 ask for Customer Service e Fax at 508 647 7001 1 9 1 G etting Ready 1 10 Installation Without MATLAB The process for installing the MATLAB C Math Library on its own is identical to the process for installing MATLAB and its toolboxes Although you are not actually installing MATLAB you can still follow the instructions in the MATLAB Installation Guide for your specific platform Verifying a UNIX Workstation Installation Toverify that the MATLAB C Math Library has been installed correctly build one of the example programs distributed with the library You can find the example programs in the lt mat ab gt extern exampl es cmath directory where lt mat ab gt is your root MATLAB installation directory See Building C Applications on page 1 11 to learn how to build the example programs using the mb ui d command To spot check the installation cd to the directory lt matlab gt extern include where lt mat ab gt symbolizes the MATLAB root directory and verify that the file mat ab h exists Verifying a PC Installation When installing a C compiler to use in conjunction with the Math Library install both the DOS and Windows targets and the command line tools TheC Math Library installation adds lt matlab gt bin toyour PATH environment variable where lt mat ab gt symbolizes the MATLAB root d
118. ction Purpose ml f Cei Round toward plus infinity ml f Fi x Round toward zero ml f Floor Round toward minus infinity ml f Rem Remainder after division ml f Round Round to nearest integer ml f Sign Signum function Numerical Linear Algebra Matrix Analysis Function Purpose ml f Det Determinant ml f Norm Matrix or vector norm ml f Rcond LINPACK reciprocal condition estimator Linear Equations Function Purpose ml f Chol ml f Chol update Cholesky factorization Rank 1 update to Cholesky factorization 9 13 9 Library Routines Linear Equations Continued Function Purpose ml flny Matrix inverse ml f Lu Factors from Gaussian elimination ml f Qr Orthogonal triangular decomposition Eigenvalues and Singular Values Function Purpose ml f Eig Eigenvalues and eigenvectors ml f Hess Hessenberg form ml f Qz Generalized eigenvalues ml f Schur Schur decomposition ml f Svd Singular value decomposition Matrix Functions Function Purpose ml f Expm Matrix exponential Factorization Utilities Function Purpose ml f Balance Diagonal scaling to improve eigenvalue accuracy 9 14 The MATLAB Builtln Library Data Analysis and Fourier Transform Functions Basic Operations Function Purpose ml f Cumprod Cumulative product of elements ml f Cums um Cumulative sum of elements ml f Max Largest component m
119. cture created with odeset ml f Odeset Create or alter options structure for input to ODE solvers Character String Functions General Function Purpose ml f Blanks String of blanks ml f Debl ank Remove trailing blanks from a string ml fStr2mat Form text array from individual strings String Operations Function Purpose ml fFindstr Find a substring within a string mf Strcat String concatenation ml fStrjust J ustify a character array ml fStrmatch Find possible matches for a string ml fStrrep Replace substrings within a string ml fStrtok Extract tokens from a string ml fStrvcat Vertical concatenation of strings MATLAB M File M ath Library String to Number Conversion Function Purpose ml fl nt2str Convert integer to string ml f Mat 2str Convert matrix to string ml fNum2str Convert number to string ml fStr2double Convert string to double precision value ml fStr2num Convert string to number Base Number Conversion Function Purpose ml fBase2dec Base to decimal number conversion ml f Bin2dec Binary to decimal number conversion ml fDec2base Decimal number to base conversion ml f Dec2bin Decimal to binary number conversion ml f Dec2hex Decimal to hexadecimal number conversion ml f Hex2dec IEEE hexadecimal to decimal number conversion ml f Hex2num H exadecimal to double number conversion 9 39 9 Library Routines File I O Functions Forma
120. d Writing a Print Handler This chapter describes how to customize error handling and print handling using MATLAB C Math Library routines Chapter 9 Library Routines This chapter lists the functions availablein the MATLAB C Math Library The chapter groups the morethan 400 library functions into functional categories and provides a short description of each function Appendix A Directory Organization This chapter provides a description of the MATLAB directory structure that positions the library s files in relation to other products from The MathWorks Appendix B Errors and Warnings This appendix lists the error messages issued by the library Accessing Online Reference Documentation To access the online reference documentation use the MATLAB Help Desk The Help Desk is a Web page that provides access to all MATLAB documentation in HTML and PDF formats Introduction Tolook up the syntax and behavior for a C Math Library function refer to the online MATLAB C Math Library Reference This reference gives you access to a reference page for each function Each page presents the function s C syntax and links you to the online MATLAB Function Reference page for the corresponding MATLAB function If you area MATLAB user 1 Typehel pdesk at the MATLAB prompt 2 From the MATLAB Help Desk select C Math Library Reference from the Other Products section If you area stand alone Math Library user 1 OpentheHTML file lt mat ab gt
121. e imagine you were building a database of images You might want to create a structure with three fields the image data a description of the image and the date the image was created The following MATLAB code creates this stucture images image i magel images description Trees at Sunset images date year 1998 i mages date month 12 images date day 17 Thestructurei mages contains three fields i mage description anddate The date field is itself a structure and contains three additional fields year mont h and day Notice that structures can contain different types of data i mages contains a matrix the image a string the description and another structure the date Like standard arrays structures are inherently array oriented A single structure is a 1 by 1 structure array just as the value5 is a 1 by 1 numeric array You can build structure arrays with any valid size or shape including multidimensional structure arrays Assume you wanted to arrange the images from the previous example in a series of pages where each page is three images wide three colums and four images tall four rows The images might be arranged this way in a photo album or for publication in a journal The 5 51 5 Indexing into Arrays 5 52 following code demonstrates how you use standard MATLAB indexing to create and access the elements of a 3 by 4 by n structure array images 3 4 2 image i mage24 images 3
122. e ml fFclose Close file ml f Fopen Open file File Positioning Function Purpose ml f Feof Test for end of file ml fFerror Inquire file I O error status ml f Fseek Set file position indicator ml f Ftel Get file position indicator Formatted I O Function Purpose ml fForintf Write formatted data to file ml f Fscanf Read formatted data from file 9 17 9 Library Routines 9 18 Binary File I O Function Purpose ml fFread Read binary data from file ml fFwrite Write binary data to file String Conversion Function Purpose ml fSprintf Write formatted data to a string ml fSscanf Read string under format control File Import Ex port Functions Function Purpose ml fLoad Retrieve variables from disk ml fSave Save variables to disk Data Types Data Types Function Purpose ml f Char Create character array string ml f Doubl e Convert to double precision The MATLAB Builtln Library Object Functions Function Purpose ml fClassName Return a string representing an object s class ml flsa True if object is a given class Time and Dates Current Date and Time Function Purpose ml f Clock Wall clock Multidimensional Array Functions Function Purpose ml f Cat Concatenate arrays ml f Ndi ms Number of array dimensions ml f Per mute Permute array dimensions Cell Array Functions Function Purpose
123. e 2 the number 14 and so on It is very simpleto convert these MATLAB indexing expressions into MATLAB C Math Library indexing expressions A 2 becomes miflndexRef A mfCreateColonindex mi f CreateColonindex mlfScalar 2 The result of this operation is the 3 by 3 array on page 2 of A 10 13 16 11 14 17 12 15 18 A 1 becomes miflndexRef A mlfScalar 1 mlfCreateCol onl ndex mi f CreateCol onl ndex The result of this operation is a three dimensional array 1 by 3 by 2 in which each page consists of the first row of the corresponding page of A Page 1 147 Page 2 10 13 16 Finally A 2 2 2 becomes mflndexRef A ml fScalar 2 mlfScalar 2 ml f Scal ar 2 The result of this operation is the 1 by 1 array 14 If the array A had more than three dimensions the index strings would have more than three s in them and they would be followed by more than three index values All of the other types of indexing discussed in this chapter selecting entire rows and columns etc work equally well on N dimensional arrays Using mlflndexRef for Logical Indexing Using mlifindexRef for Logical Indexing This section describes how to use e A logical index as a one dimensional subscript e Two logical vectors as indices in a two dimensional subscript e A colon index and a logical vector as a two dimensional subscript e A logical index to select e
124. e Describes how to delete multiple elements from an array The examples work with matrix A A wn e ow pA wo como Assumptions for the Code Examples on page 5 16 explains the conventions used in the examples Use the function ml f ndexDel et e todelete elements from an array This function is equivalent tothe MATLAB statement A B Instead of specifying a subscript for the elements you want to replace with other values specify a subscript for the elements you want removed from the matrix The MATLAB C Math Library removes those elements and shrinks the array For example to delete elements from example matrix A you simply pass the target array the index string and the value of the indices that identify the elements to be removed When you delete a single element froma matrix the matrix is converted intoa row vector that contains one fewer element than the original matrix F or example when element 8 is deleted from matrix A mi fl ndexDelete amp A ml fScalar 8 matrix A becomes this row vector with element 8 missing 1234567 9 You can also delete more than one element from a matrix shrinking the matrix by that number of elements To retain the rectangularity of the matrix however you must delete one or more entire rows or columns For example miflndexDelete amp A mfScalar 2 ml f CreateCol onl ndex Using mliflndexDelete for Deletion produces this rectangular
125. e data type The MATLAB API includes routines to create arrays and access them These routines areidentified by the prefix mx For a complete list of these routines see Chapter 9 As a convenience the MATLAB C Math Library includes routines to create certain types of commonly used arrays The sections in this chapter that describe the various types of arrays detail these routines These routines like all the library routines are identified by the prefix ml f You can use a mix of ml f and mx routines to create and manipulate arrays 3 3 3 W orking with MATLAB Arrays 3 4 Working with MATLAB Numeric Arrays The MATLAB C Math Library includes routines to create and manipulate numeric arrays Numeric arrays are the fundamental MATLAB array type The elements of the array are stored as a one dimensional vector of double precision numbers Imaginary data if present is stored in a separate vector Table 3 1 lists the MATLAB C Math Library routines that create numeric arrays and perform some basic tasks with them The sections that follow provide more detail about using these routines F or more detailed information about using numeric arrays see Using MATLAB For more detailed information about any of the library routines see the online MATLAB C Math Library Reference Table 3 1 Numeric Array Routines To Use Create a 1 by 1 array scalar ml f Scalar Create a 1 by n array vector ml f Col on Create an m
126. e pairs ml f Unwrap Remove phase angle jumps across 360 boundaries Rounding and Remainder Functions Function Purpose ml f Mod Modulus signed remainder after division 9 28 MATLAB M File M ath Library Specialized Math Functions Specialized Math Functions Function Purpose ml f Beta Beta function ml f Bet ai nc Incomplete beta function ml f Bet aln Logarithm of beta function ml f Cross Vector cross product ml f Ell i pj J acobi elliptic functions ml fEllipke Complete elliptic integral ml f Erf Error function ml fErfc Complementary error function ml fErfcx Scaled complementary error function ml fErfiny Inverse error function ml fExpi nt Exponential integral function ml f Gamma Gamma function ml f Gammai nc Incomplete gamma function ml f Gammal n Logarithm of gamma function ml fLegendre Legendre functions Number Theoretic Functions Function Purpose ml f Factor Prime factors ml f Gcd Greatest common divisor ml fl spri me True for prime numbers 9 29 9 Library Routines Number Theoretic Functions Continued Function Purpose ml f Lom Least common multiple ml f Nchoosek All combinations of n elements taken k at atime ml f Per ms All possible permutations ml f Primes Generate list of prime numbers ml f Rat Rational approximation ml f Rats Rational output Coordinate System Transforms Function Purpose ml f Car
127. e size ml f Rot 90 Rotate matrix 90 degrees ml fShiftdim Shift dimensions Specialized Matrices Function Purpose m m f Compan f Hadamard f Hankel f Hil b flnvhilb f Pascal fRosser fToeplitz f Vander fWil kinson Companion matrix Hadamard matrix Hankel matrix Hilbert matrix Inverse Hilbert matrix Pascal matrix Classic symmetric eigenvalue test problem Toeplitz matrix Vandermonde matrix Wilkinson s eigenvalue test matrix 9 26 MATLAB M File M ath Library Elementary Math Functions Trignometric Functions Function Purpose ml fAcosh Inverse hyperbolic cosine ml fAcot Inverse cotangent ml fAcoth Inverse hyperbolic cotangent ml fAcsc Inverse cosecant ml fAcsch Inverse hyperbolic cosecant ml fAsec Inverse secant ml fAsech Inverse hyperbolic secant ml fAsinh Inverse hyperbolic sine ml fAtanh Inverse hyperbolic tangent ml f Cosh Hyperbolic cosine ml f Cot Cotangent ml f Coth Hyperbolic cotangent ml f Csc Cosecant ml f Csch Hyperbolic cosecant ml f Sec Secant ml fSech Hyperbolic secant ml f Sinh Hyperbolic sine ml f Tanh Hyperbolic tangent 9 27 9 Library Routines Ex ponential Functions Function Purpose ml fLogl0 Common base 10 logarithm ml f Next pow2 Next higher power of 2 Complex Functions Function Purpose ml fAngle Phase angle ml f Cpl xpair Sort numbers into complex conjugat
128. eached after error n 3 Free any matrices that were assigned to variables mxDestroyArray mat 2 mxDestroyArray mat 0 mxDestroyArray mat 1 mi fRestorePreviousContext 0 0 return EXIT SUCCESS Handling Errors This program produces the following output You can see how this program continues processing after a warning but terminates after an error WARNING Divide by zero Return to application after warning ERROR Matrix dimensions must agree EXITING Customizing Error Handling Two aspects of the default error handling behavior of the MATLAB C Math Library routines may not suit every application e Exiting on error conditions e Displaying error messages to the same display as other application messages You may want control to return to your application when an error occurs allowing it to perform clean up processing before exiting You may also prefer to direct error and warning messages to a different output stream than the normal messages output by your application The following sections describe how to make these customizations Continuing Processing After Errors Toreturn control to your application after a library routine encounters an error condition you must define try and catch blocks in your application When you define a try block the library warning level processing does not change The routines output a warning message and return control back tothe application The default li
129. eat eCol onl ndex function The size and shape of the one dimensional index determine the size and shape of the result the size of the result is exactly equal to the size of the one dimensional subscript For example a one dimensional row vector index produces a one dimensional row vector result Given the matrix A the expression A 1 5 8 produces therow vector 1 5 8 To apply a one dimensional subscript to an N dimensional array you need to know how to go from the one dimensional index value to a location inside the array See Array Storage on page 5 5 for complete details on how MATLAB counts one dimensionally through arrays of N dimensions 5 18 Using mlflndexRef for O ne Dimensional Indexing Note Therangefor a one dimensional index depends on the size of the array For a given array A it ranges from 1 the first element of the array to prod size A thelast element in an N dimensional array Contrast this range with the two ranges for a two dimensional index where the row value varies from 1 to M and the column value from 1 to N Selecting a Single Element Use a scalar index to select a single element from the array For example ml fAssign amp B miflndexRef A ml fScalar 5 performs the same operation as A 5 in MATLAB and selects the fifth element of A the number 5 Selecting a Vector Use a vector index to select multiple elements from an array For example miflndexRef A
130. ed This chapter provides an introduction to the MATLAB C Math Library and tells how to install it In addition it includes information about building applications The remainder of the book is organized as follows e Chapter 2 Writing Programs This chapter introduces all the primary new library features by showing how they are used in a simple example program 1 G etting Ready 1 4 This chapter contains pointers to all the other chapters where you can find more detailed information about each new feature Chapter 3 Working with MATLAB Arrays Arrays are the fundamental MATLAB data type This chapter describes how to create MATLAB arrays in your C program Chapter 4 Managing Array Memory This chapter describes how tousethe MATLAB C Math library automatic memory management facility Chapter 5 Indexing into Arrays This chapter describes how to access individual elements or groups of elements in an array Using indexing you can access modify or delete elements in an array Chapter 6 Calling Library Routines This chapter describes the MATLAB C Math Library interface tothe MATLAB functions This chapter describes how to call MATLAB functions that have variable numbers of input arguments and return values Chapter 7 Importing and Exporting Array Data This chapter describes how tousetheml f Load and ml fSave routines to import data to your application or export data from your application Chapter 8 Handling Errors an
131. en in MATLAB the library includes the routine ml f Doubl eMat ri x that allows you to create a matrix of double precision values and initialize it with data Note that you can use integers to specify the array dimensions you do not need to convert these to arrays static double data 1 4 2 5 3 6 mxArray A NULL ml fAssign amp A mi f Doubl eMatrix 2 Rows 3 Columns data NULL No imaginary part ml f Print Matrix A mxDestroyArray A 3 5 3 W orking with MATLAB Arrays 3 6 This code produces the following output 1 2 3 4 5 6 In this code fragment note that the values in the C array used to initialize the MATLAB array are not specified in numeric order because MATLAB stores arrays in column major order and C arrays are stored in row major order F or more information about this see Initializing a Numeric Array with Data on page 3 12 You can also use the MATLAB API routine mxCreat eDoubl eMatrix to create a matrix of doubles Creating Multidimensional Numeric Arrays To create a multidimensional numeric array use the MATLAB API routine mxCreateNumericArray The arguments to this routine are e The number of dimensions of the array e The size of each dimension e The type of data the array will contain e Whether the data is real or complex For example the following code fragment creates a three dimensional array with dimensions 3 by 3 by 2 ThemxDOUBLE_CLAS
132. er a thunk function table with the MATLAB C Math Library Indexing Function Purpose mxArray Handle assignments that include mi flndexAssign mxArray volatile pa const char index mxArray ml flndexDelete mxArray volatile pa const char index mxArray ml flndexRef mxArray pa const char index_string mxArray ml fColon mxArray start mxArray step mxArray end indexing Handle deletions that include indexing Perform array references such as X 5 Generate a sequence of indices Use this where you d usethe colon operator operator in MATLAB ml fColon NULL NULL NULL is equivalent to ml f CreateColonindex 9 21 9 Library Routines 9 22 Indexing Continued Function Purpose mxArray mi f CreateCol onl ndex void mxArray ml fEnd mxArray array mxArray di m mxArray numindices Create an array that acts likethe colon operator when passed to mi fArrayRef mlfArrayAssign and ml fArrayDelete Generate the last index for an array dimension Acts likeend in the MATLAB expression A 3 6 end dim is the dimension to compute end for Use 1 to indicate the row dimension use 2 to indicate the column dimension numi ndi ces is the number of indices in the subscript Memory Allocation Function Purpose void mlfSetLibraryAllocFcns calloc_proc calloc_fcn free proc free _fcn realloc_proc
133. explicit memory management 4 5 4 Managing Array Memory Using Arrays Under Automated Memory Management This section describes how to work with arrays under automated memory management The section e Defines temporary and bound arrays e Lists the rules for working with arrays e Describes how to assign values to array variables e Describes how to nest calls to library functions e Describes when you need to delete arrays e Describes how to avoid memory leaks See Writing F unctions Under Automated Memory Management on page 4 14 for information about writing your own functions that includethe assignments deletions and nested calls to functions described in this section Definitions Automated memory management distinguishes between two types of arrays e Temporary arrays e Bound arrays Understanding the definition of the temporary and bound states for an array will help you understand e Why you can nest calls to library functions e Why you need to call mi f Assi gn rather than use the assignment operator for assignments e Why you need to follow the rules for writing functions presented in Writing Functions Under Automated Memory Management on page 4 14 This diagram illustrates how library functions return temporary arrays and how arrays become bound if they are assigned toan array variable mxArray 4 6 Using Arrays Under Automated M emory M anagement Temporary Array Temporary Array
134. fAssign amp N mfOnes mfScalar 2 mlfScalar 3 NULL mf Print Matrix N Convert it into a cell array ml fAssign amp C mifNum2cel N NULL ml fPrintMatrix C mxDestroyArray N mxDestroyArray C In this output the brackets indicate that each element in the numeric array has been placed into a cell in the cell array The brackets indicate cell array elements Using Concatenation to Create Cell Arrays You can group existing MATLAB arrays into a cell array by concatenation In MATLAB you usethe braces operator to create cell arrays through W orking with MATLAB Cell Arrays concatenation For example you can use the following syntax in MATLAB to concatenate arrays into a cell array A 1 10 A 1 2 3 4 5 6 7 8 9 10 B my string my string C 12 3 45 6 Gc 1 2 3 4 5 6 D ABC 1x10 double my string 2x3 double Tocreate the same cell array through concatenation in a C program use the MATLAB C Math Library ml f Cel hcat routine This routine performs the same function as the MATLAB cell concatenation operator mxArray A NULL mxArray B NULL mxArray C NULL mxArray D NULL static double data 1 4 2 5 3 6 ml fAssign amp A mifColon mfScalar 1 mfScalar 10 NULL ml f Assign amp B mxCreateString my string mi fAssign amp C mifDoubleMatrix 2 3 data NULL mi fAssign amp D mifCell hcat A B C NULL
135. freed Using Arrays Under Automated Memory M anagement 2 Never assign a valuetoan array variable without subsequently deleting the array Memory leak void func mxArray y mxArray x ml fEnterNewContext 0 1 y ml f Assign amp x milf Sin y ml fRestorePrevi ousContext 0 1 y You must pair each mxArray declaration with a call tomxDestroyArray 3 Never use the assignment operator to assign array values Unexpected termination of your program x isa temporary array If x is Subsequently passed as an input argument to a function that function will delete x Any subsequent reference tox will cause your program to crash x mfSin y x is temporary a mfPlus x ml fScalar 1 x is deleted b mfPlus a x Program crashes 4 13 4 Managing Array Memory Writing Functions Under Automated Memory Management You must follow a set procedure when you writea function that conforms tothe rules of automated memory management It s not hard The pattern is the same for each function By calling the functions emlfEnterNewContext e m fRestorePreviousContext e mi fReturnValue in each funcion that you write that uses arrays e A call to your function can be embedded as an input argument to another function For example ml fAssign amp A mifPlus myFunc A 8B e A call to another function can be embedded as an input argument to your function For example ml fA
136. g conventions 6 2 8 9 functions 9 24 link order 1 36 matlab h 3 17 A 5 A 8 matrices creating 3 5 matrices elementary functions 9 10 9 25 matrices specialized functions 9 11 9 26 matrix analysis functions 9 13 9 31 creation 3 17 functions 9 14 9 32 initialization with C array 3 14 output of 8 14 printing 8 14 singular value decomposition 6 14 sparse 1 3 matrix manipulation functions 9 11 9 26 matrix h A 5 A 8 mbuild 1 11 Microsoft Windows A 8 setup option 1 24 setup option on PC 1 24 setup option on UNIX 1 14 syntax and options on Microsoft Windows 1 29 on UNIX 1 18 troubleshooting 1 34 UNIX A 3 verbose option on PC 1 26 Index verbose option on UNIX 1 16 memory management 1 3 memory allocation writing own routines 4 35 memory allocation functions 9 22 memory leakage avoiding 4 12 memory management 4 2 automated 4 3 automated benefits of 4 3 choosing automated or explicit 4 3 coding to automated memory management in terface 4 14 4 22 coding to explicit memory management inter face 4 31 example 4 24 4 31 explicit 4 4 ml fSetLibraryAllocFcns 4 35 prior to Version 2 0 4 3 setting up your own 4 35 message display 9 9 MessageDi al og Motif widget 8 15 Microsoft Windows building stand alone applications 1 22 directory organization A 7 DLLs A 7 location def files A 8 build script A 8 header files A 8 libraries A 7 A 8 MessageBox 8 17 PopupMessageBox C code 8 18 print handling 8 17 ml f
137. g tomxDestroyArray 412 number theoretic functions 9 29 numeric arrays converting to cell arrays 3 31 converting to character arrays 3 27 creating 3 4 numerical integration 9 37 numerical linear algebra eigenvalues and singular values 9 14 9 31 factorization utilities 9 14 9 32 linear equations 9 13 9 31 matrix analysis 9 13 9 31 matrix functions 9 14 9 32 0 object functions 9 19 ODE option handling 9 38 ODE solvers 9 37 offsets for indexing 5 9 one dimensional indexing 5 18 range for index 5 19 selecting a matrix 5 21 selecting a single element 5 19 selecting a vector 5 19 table of examples 5 57 with a logical index 5 31 online help accessing 1 5 opening files 9 17 operators calling conventions 6 19 operators and special functions arithmetic operator functions 9 5 9 24 logical functions 9 8 9 24 logical operator functions 9 6 9 24 MATLAB as a programming language 9 9 9 25 message display 9 9 relational operator functions 9 6 set operator functions 9 7 9 24 special operator functions 9 7 optimization and root finding 9 37 optional input arguments 6 4 6 5 optional output arguments 6 4 6 5 options file combining customized on PC 1 27 locating on PC 1 22 locating on UNIX 1 13 location on UNIX 1 14 making changes persist on PC 1 27 making changes persist on PC 1 27 making changes persist on UNIX 1 16 modifying on PC 1 26 modifying on UNIX 1 15 purpose 1 12 temporarily changing on PC 1 2
138. gement 4 3 Using Explicit Memory Management 05 4 4 Using Arrays Under Automated Memory Management 4 6 Definitions 2 cngceee Wa wee eke alee aa a ae Baya a EN 4 6 Rules for Array Usage 06 e ete 4 8 Paradigm for Working with Local Array Variables 4 8 iv Contents Assigning Arrays to mxArray Variables 4 9 Assigning a Value to an Array Destroys Its Previous Value 4 10 Assignment by Value 0 0 0 0 aaae 4 11 Nesting Calls to Functions that Return Arrays 4 11 Deleting Your ArrayS 2 0 00 e eee ee 4 11 Avoiding Memory Leaks in Your Functions 4 12 Writing Functions Under Automated Memory Management 0 cece cette teenies 4 14 Using a Function Template As an Example 4 14 Function Template 0 000 eee ee 4 15 Main Routine Template 0 00 cee eee eee 4 16 Preparing Function Arguments for a New Context 4 16 Arguments to mlfEnterNewContext 00 00s 4 17 What Happens tothe Array Arguments 4 17 Purpose of mlfEnterNewContext 000 e eee 4 18 Restoring Function Arguments to their Previous Context 4 18 Arguments to mlfRestorePreviousContext 4 19 What Happens to the Array Arguments 4 20 Purpose of mlfRestorePreviousContext 005 4 20 Returning an Array from Your Function 4 20 Ar
139. generated a floating point number larger than the maximum number representable on the current machine Check your inputs to see if any are near zero if dividing or infinity if adding or multiplying Initial condition vector is not the right length This error is issued only by the ml f Fil ter function The length of the initial condition vector must be equal to the maximum of the products of the dimensions of the input filter arguments Let the input filter arguments be given by matrices B and A with dimensions bM by bN and aM by aN respectively Then the length of the initial condition vector must be equal to the maximum of bM bN and aM aN B 3 B Errors and W arnings Inner matrix dimensions must agree Given two matrices A andB with dimensions aN by aM and bN by bM the inner dimensions referred to by this error message are aM and bN These dimensions must be equal This error occurs for example in matrix multiplication an N by 2 matrix can only be multiplied by a scalar or a 2 by M matrix Any attempt to multiply it by a matrix with other than two rows will cause this error Log of zero Taking the log of zero produces negative infinity On non IEEE floating point machines this is an error because such machines cannot represent infinity Matrix dimensions must agree This error occurs when a function expects two or more matrices to be identical in size and they are not For example the inputs tomi f Pl us whic
140. ges date day Thisis an error in MATLAB and the corresponding call tomi f Rmfi el d isan error in the MATLAB C Math Library Deleting an Element from an Array Contained by a Field To delete an element from an array contained by a field use ml fI ndexDel et e For example toremove the fifth column of theimagein the third image structure call ml f ndexDel ete likethis ml flndexDelete amp i mages image ml fScalar 3 ml f CreateColonindex ml fScalar 5 images 3 image 5 performs the same operation in MATLAB Comparison of C and MATLAB Indexing Syntax Comparison of C and MATLAB Indexing Syntax The table below summarizes the differences between the MATLAB and C indexing syntax Although the MATLAB C Math Library provides the same functionality as the MATLAB interpreter the syntax is very different Refer to Assumptions for the Code Examples on page 5 16 to look up the conventions used for the code within the table Note For the examples in the table matrix X is set to the 2 by 2 matrix 45 6 7 a different value from the 3 by 3 matrix A in the previous sections Example Matrix X 4 5 6 7 Table 5 2 MATLAB C Indexing Expression Equivalence Description MATLAB Expression C Expression Result Extract 1 1 element X 1 1 ml fl ndexRef 4 X u De Fa ml fScalar 1 ml fScalar 1 Extract first element X 1 ml fl ndexRef 4 X ERT ml fScal
141. gml fAssign amp B ml fLogical matrix where mat ri x stores a matrix of 1 s and O s If the logical index is not the same size as the subscripted array the logical index is treated like a vector For example ifB ogical 1 0 0 1 then ml fAssign amp X mlflndexRef A B equals 1 4 sinceB has a zero at positions 2 and 3 and a 1 at positions 1 and 4 Logical indices behave just like regular indices in this regard Using Two Logical Vectors as Indices Two vectors can be logical indices into an M by N matrix 4 Thesize of a logical vector index often matches the size of the dimension it indexes although this is not a requirement Using mlflndexRef for Logical Indexing For example letB ogical 101 andcC ogical 0 1 0 twovectors that do match the sizes of the dimensions where they are used Then ml fAssign amp X miflndexRef A B C equals 4 6 B the row index vector has nonzero entries in the first and third elements This selects the first and third rows C the column index vector has only one nonzero entry in the second element This selects the second column The result is the intersection of the two sets selected by B and C that is all the elements in the second columns of rows 1 and 3 Or letB logical 1 0 andc ogical 0 1 twovectors that donot match the sizes of the dimensions where they are used Then ml fAssign amp X miflndexRef A
142. gument and Return for mlfReturnValue 4 21 What Happens to the Array Argument 4 21 Purpose of mlfReturnValue 0 cece eee 4 22 Summary of Coding Steps 0 0 c cece eee 4 22 Example Program Managing Array Memory ex2 c 4 24 Example Without Automated Memory Management 4 31 Restrictions on Function Calling 4 33 Function Uses Automated Memory Management 4 33 Function Does Not Use Automated Memory Management 4 33 Recommendation essea eee eee ee 4 34 Setting Up Your Own Allocation and Deallocation RROUTINCS aie eee a cere Bel etd dade pera ene 4 35 Indexing into Arrays 5 Overview enanada ne o e A E A alates E EDE E Aa 5 2 Indexing Functions ccc eee 5 2 TeEHMInOlOOYy saciid Aus tit wees Monee E aE wae BY A eae 5 3 Dimensions and Subscripts 00 0 eee eee eee 5 3 MATLAB a s5 cdots eutdnce stars aes a a att a 5 5 3 Inthe MATLAB C Math Library 0 05 5 4 Afray StOrage s cece wea ee dd ene ee eee Y 5 5 How to Call the Indexing Functions 5 10 OVErVIEW woe ek cee eee bbe oe eee eee eee 5 10 Specifying the Target Array ccc cece cee eee eee 5 11 Specifying the Index String 0 cece eee 5 11 What an Indexing String Specifies 00 5 12 What an Indexing String Doesn t Specify 5 13 Complex Indexing Expressions
143. gument is optional tothe workings of the function and that it can be set toNULL Print the result of the call toml fSvd If you want to know more about the function ml f Svd or the calling conventions for the library refer to the online MATLAB C Math Library Reference 5 Call ml f Svd the second way with three output arguments and one input argument The additional output arguments and V appear first in the argument list Becausethe return valuefromml f Svd corresponds tothefirst How to Call MATLAB Functions output argument U only two output arguments S and V appear in the argument list bringing the total number of outputs to three The next argument X is the required input argument Only the final argument the optional input is passed as NULL Print all of the output matrices 6 Call mi f Svd the third way with three output arguments and two input arguments Print all of the output matrices Notice that in this call as in the previous one an ampersand amp precedes the two additional output arguments An ampersand always precedes each output argument because the address of the mxArray iS passed The presence of an amp is a reliable way to distinguish between input and output arguments Input arguments never have an amp in front of them 7 Last of all free all of the matrices that have been bound to variables 6 17 6 Calling Library Routines Output When the program is run it produces this
144. h computes the sums of the elements of two matrices must be of equal size To correct this error make sure the required input matrices are the same size Matrix is singular to working precision A matrix is singular if two or more of its columns are not linearly independent Singular matrices cannot be inverted This error message indicates that two or more columns of the matrix are linearly dependent to within the floating point precision of the machine Matrix must be positive definite A matrix is positive definite if and only if x Ax gt 0 for all nonzero vectors x This error message indicates that the input matrix was not positive definite Matrix must be square A function expected a square matrix For example ml f Qz which computes generalized eigenvalues expects both of its arguments to besquare matrices An M by N matrix is square if and only if M and N are equal Errors Maximum variable size allowed by the programis exceeded This error occurs when an integer variable is larger than the maximum representable integer on the machine This error occurs because all matrices contain double precision values yet some routines require integer values and the maximum representable double precision value is much larger than the maximum representable integer Correct this error by checking the documentation for the function that produced it Make sure that all input arguments that are treated as integers are less than or equal to
145. h Library For example the MATLAB expression x 3 2 4 2 col or a combination of cell array standard and structure indexing results in the following string color Thethird and subsequent arguments are the values to usein place of the sin the string These values must be mx Ar r ay s and are very often the result of a 5 10 How to Call the Indexing Functions call toml f Scal ar which creates an mxArray froma double precision floating point number or a integer When calling mi f I ndexAssign the last argument in the list is the source array that contains the values to write into the target array Note that the source array must be exactly the same size as the subset of the target array specified by the indexing expression in the second argument and subsequent arguments Refer to the online MATLAB C Math Library Reference for more detail on the interface for the three functions Specifying the Target Array Each indexing function takes a target array as its first argument The subscript is applied to this array e Formi fIndexRef thefirst argument is the array that you want to extract elements from e For ml fl ndexAssign the first argument is the array that you want to change elements of be assigned to e For ml fl ndexDel et e the first argument is the array that you want to delete elements from Note mi findexRef takesanmxArray ml flndexAssign and ml flndexDelete takemxArr
146. h a three element row index and a two element column index the result has six elements arranged in three rows and two columns Selecting a Single Element Use two scalar indices to extract a single element from an array For example ml fAssign amp B mflndexRef A mfScalar 2 mfScalar 2 selects the element5 from the center of matrix A the element at row 2 column 2 Selecting a Vector of Elements Use one vector and one scalar index or one matrix and one scalar index to extract a vector of elements from an array You can use the functions ml fHorzcat mlfVertcat or mfCreateCol onl ndex to make the vector or matrix index or use an mxArray variable that contains a vector or matrix returned from other functions Theindexing routines iterate over the vector index or down the columns of the matrix index pairing each element of the vector or matrix with the scalar index Think of this process as applying a Scalar scalar subscript multiple times the result of each selection is collected into a vector Using mlflndexRef for N Dimensional Indexing For example ml f Assi gn amp B miflndexRef A mi f Horzcat mlfScalar 1 mlfScalar 3 NULL mf Scalar 2 selects the first and third element or first and third rows of column 2 4 6 In MATLAB A 1 3 2 performs the same operation If you reverse the positions of the indices A 2 1 3 in MATLAB ml f Assi gn amp B mi fI
147. he C interface to the functions differs from the MATLAB interface Once you understand the calling conventions you can translate any call toa MATLAB function into a call to a C function Chapter 9 contains a listing of all the routines in the MATLAB C Math library For complete reference information about the library functions including the list of arguments and return value for each function see the online MATLAB C Math Library Reference accessible from the Help Desk Each routine s reference page includes a link to the documentation for the MATLAB version of the function This chapter also includes information about passing a function toa MATLAB function or a function of your own creation 6 2 How to Call MATLAB Functions How to Call MATLAB Functions Some MATLAB functions accept optional input arguments and return multiple output values Some MATLAB functions can take a varying number of input and output values these functions are calledvarargin andvarargout functions C does not allow routine with the same name to accept different calling sequences nor does it allow a routine to return more than one value Thus totranslate MATLAB functions into callable C routines the MATLAB C Math Library had to establish certain calling conventions This chapter describes these conventions Returning One Output Argument and Passing Only Required Input Arguments For many functions in the MATLAB C Math Library the translation from
148. he current directory then lt f i e gt must be the full pathname to the desired options file Using the f option tells thembui d script to use the specified options file for the current execution of mbui d only it does not reset the default compiler Verifying mbuild The C source code for the exampleex1 c is included in the lt matlab gt extern examples cmath directory where lt mat ab gt represents the top level directory where MATLAB is installed on your system To verify that mbui Id is properly configured on your system to create stand alone Building a Stand Alone Application on UN IX applications copy ex1 c to your local directory and c d to that directory Then at the UNIX prompt enter mbuild exl c This should create the file called ex1 Stand alone applications created on UNIX systems do not have any extensions Locating Shared Libraries Before you can run your stand alone application you must tell the system wherethe API and C shared libraries reside This table provides the necessary UNIX commands depending on your system s architecture Architecture Command HP 700 setenv SHLIB_ PATH lt matlab gt extern lib hp700 SHLIB_PATH IBM RS 6000 setenv LIBPATH lt matlab gt extern lib ibm_ers LI BPATH All others setenv LD_LIBRARY_PATH lt matlab gt extern ib lt arch gt LD_LIBRARY_PATH where lt mat ab gt isthe MATLAB root directory lt arch gt is your architecture i e al pha 1nx86 sgi sg
149. i gn modifies the value of b locally within the function However because b is an input argument the call toml f Assi gn does not destroy the old value Using Arrays Under Automated Memory M anagement Assignment by Value ml f Assi gn implements assignment by value When the array on the righthand side of the assignment the second argument to ml f Assi gn is already bound to a variable the array on the lefthand side receives a copy of that array For example mxArray A NULL mxArray B NULL ml f Assign amp A milf Rand mlfScalar 4 ml fAssign amp B A A andB point totwo different arrays Note that the copy is actually a shared data copy until the application requires two separate copies of the data The MATLAB C Math Library supports full copy on write semantics Nesting Calls to Functions that Return Arrays You can nest calls to library functions as arguments to other library functions When you nest calls the library deletes the array returned from the call for you For example when you call the library s indexing functions you can embed the calls toml f Scal ar that define the index values ml f Assi gn amp B mflndexRef A mfScalar 2 mlfScalar 2 The two calls toml f Scal ar each return a temporary array that the function ml fl ndexRef deletes just before it returns See Writing Functions Under Automated Memory Management on page 4 14 which explains the rules
150. i64 sol 2 It is convenient to place this command in a startup script such as cshrc Then the system will be able to locate these shared libraries automatically and you will not have to re issue the command at the start of each login session The best choice is to place the libraries in logi n which only gets executed once if that option is available on your system Note On all UNIX platforms the C libraries are shipped as shared object so files or shared libraries s Any stand alone application must be able to locate the C libraries along the library path environment variable SHLIB_PATH LI BPATH Or LD_LIBRARY_PATH in order to be loaded 1 17 1 G etting Ready 1 18 Consequently to share a stand alone application with another user you must provide all of the required shared libraries For more information about the required shared libraries for UNIX see Distributing Stand Alone UNIX Applications on page 1 21 Running Your Application To launch your application enter its name on the command line For example ex1 1 3 5 2 4 6 1 0000 7 0000i 4 0000 10 0000i 2 0000 8 00001 5 0000 11 00001 3 0000 9 00001 6 0000 12 00001 mbuild Options The mbui ld script supports various options that allow you to customize the building and linking of your code Many users do not need to know additional details about the mbui d script they use it in its simplest form The following inf
151. ibraries This option should be the only argument passed Undefine C preprocessor macro lt name gt Verbose print all compiler and linker settings 1 31 1 G etting Ready 1 32 Distributing Stand Alone Microsoft Windows Applications To distribute a stand alone application you must include the application s executable as well as the shared libraries against which the application was linked This package of files includes e Application executable e ibmmfile dil e ibmatib dil e ibmat dil e i bmx dll e ibut dil For example to distribute the Windows version of theex1 example you need toincludeexl exe libmmfile dl libmatlb dll libmat dll libmx dll andlibut dll The DLLs must be on the system path You must either install them in a directory that is already on the path or modify the PATH variable to include the new directory Building Shared Libraries Building Shared Libraries You can use mbui d to build C shared libraries on both UNIX and the PC All of the mbui d options that pertain to creating stand alone applications also pertain to creating C shared libraries To createa C shared library you usethe option link shared and specify one or more files with the exports extension The exports files are text files that contain the names of the functions to export from the shared library one per line You can include comments in your code by beginningaline first column with or
152. ibrary Reference The reference pages for all the MATLAB C Math library routines are available in PDF format accessible through the Help Desk Migrating Your Code to Version 2 0 In most cases you won t need to make any changes to your current code base However you need to modify your code in these two cases Introduction e In existing code update any calls you have made to the following functions f Cov fDatestr f Datevec f Del 2 f Feval f Fmin f Fmi ns fForintf fFzero f Gradient flnterpl flnterp2 fload flu f 0de113 fOdel5s f Ode23 f Ode23s fOde45 f Odeget fOdeset f Ones f Qr f Quad f Quad8 f Rand f Randn f Save fSize fSprintf fStrjust f Zeros 3 3 3 53 3 3 3 3 3 33 3 3 3S E 33S 3B BS 3B 33 3 3 3 33 3 The prototypes for these functions have changed to support new features in the library For example mi f Si ze now takes a variable length output argument var ar gout The MATLAB C Math Library Reference Version 2 0 documents the new prototypes They are also listedinrelease txt in lt matl ab gt extern exampl es cmath 1 G etting Ready e Migrate any existing functions to automated memory management if you want to call them from new functions that use automated memory management See Chapter 4 for information about using automated memory management 1 8 Installing the MATLAB C Math Library Installing the MATLAB C Math Library The MATLAB C Math Lib
153. ices 0000u 5 32 Using One Colon Index and One Logical Vector as Indices 5 33 Using a Scalar anda Logical Vector 0 0 5 34 Extending Logical Indexing toN Dimensions 5 35 Using mlflndexAssign for Assignments 5 36 OVVIE WE 3 dati iowa ti het be Peedi de OG ee oe 5 36 Assigning to a Single Element 0 0 eee eee 5 37 Assigning to Multiple Elements 0 0005 5 37 Assigning to a Subarray 000 c eee eee 5 38 Assigning to All Elements 0000 eee eee eee 5 39 Extending Two Dimensional Assignment to N Dimensions 5 39 Using mifi ndexDelete for Deletion 5 42 Indexing into Cell Arrays 0 00055 5 44 OVErVIOW 20 teens 5 45 Tips for Working with Cell Arrays 2 0 5 5 45 Referencing a Cell ina Cell Array 000055 5 46 Referencing a Subset of a Cell Array 0 0 0005 5 46 Referencing the Contents of a Cell 0 cee ees 5 47 Referencing a Subset of the Contents of a Cal 5 47 Indexing Nested Cell Arrays 000 c eee eee eee 5 47 Indexing the First Level 00 0 cece eee 5 48 Indexing the Second Level 00 0 eee ee 5 48 Indexing the Third Level 2 00000 c eee ee eee 5 48 Assigning Values toa Cell Array 00000 eae 5 49 Deleting Elements froma Cell Array 0 0 005 5 49 DeletingaSingleE
154. ign data to the variables that will be saved to a file x stores a 4 by 4 array that contains randomly generated numbers y stores a 7 by 7 magic 7 Importing and Exporting Array Data square z contains the eigenvalues of x Note that ml f Rand isavarargin function you must terminate the argument list with NULL The MATLAB C Math Library utility function ml f Scal ar creates 1 by 1 arrays that hold an integer or double value Save three variables to the file ex5 mat You can save any number of variables to the file identified by the first argument to ml f Save The second argument specifies the mode for writing to the file Here w indicates that ml f Save should overwrite the data Other values include u to update append and w4 to overwrite using V4 format Subsequent arguments come in pairs the first argument in the pair a string labels the variable in thefile the contents of the second argument is written tothe file A NULL terminates the argument list Note that you must provide a name for each variable you save When you retrieve data froma file you must providethe name of the variable you want to load You can choose any name for the variable it does not have to correspond to the name of the variable within the program Unlike arguments to most MATLAB C Math Library functions the variable names and mode are not mx Array arguments you can pass a C string directly to ml fSave andmlfLoad Load the named va
155. imensional Indexing Using mifi ndexRef for N Dimensional Indexing Using mifi ndexRef for Logical Indexing Using mifi ndexAssign for Assignments Using mifi ndexDelete for Deletion Indexing into Cell Arrays Indexing into MATLAB Structure Arrays Comparison of C and MATLAB Indexing Syntax 5 16 5 18 5 23 5 31 5 36 5 42 5 44 5 51 5 57 5 Indexing into Arrays 5 2 Overview The MATLAB interpreter provides a sophisticated and powerful indexing operator that allows you to access and modify multiple array elements The MATLAB C Math Library also supports an indexing operator The MATLAB C Math Library provides the same indexing functionality as the MATLAB interpreter and the MATLAB C Math Library but through a different mechanism Instead of an indexing operator the MATLAB C Math Library provides indexing functions This chapter describes how to e Call the indexing functions e Use one dimensional n dimensional and logical subscripts e Make assignments using indexing e Make deletions using indexing e Index into cell arrays e Index into structure arrays Indexing Functions Conceptually the indexing functions in C are very similar to the indexing operations in MATLAB In MATLAB you can e Access e Modify e Delete elements of an array For example A 3 1 accesses the first element in row 3 of matrix A In the MATLAB C Math Library the functi
156. indexing 5 31 logical operator functions 9 6 9 24 M main routine template for managing array memory 4 16 makefile 1 16 malloc 4 35 managing array memory 4 2 managing variables 9 5 MAT files 7 3 mat extension 7 6 and named variables 7 6 created by ml fLoad 7 6 created by ml fSave 7 6 import and export functions 9 18 read by ml f Load 7 3 written to with ml f Save 7 2 math functions elementary complex 9 12 9 28 Index exponential 9 12 9 28 rounding and remainder 9 13 9 28 trigonometric 9 12 9 27 math functions specialized 9 29 coordinate system transforms 9 30 number theoretic 9 29 MATLAB as a programming language functions 9 9 9 25 function calling conventions 6 2 Handle Graphics 1 3 indexing 5 57 sparse matrix 1 3 subscripts 5 57 MATLAB Access 1 10 MATLAB Built In Library 9 4 calling conventions 6 2 8 9 functions 9 5 link order 1 36 utility routines 9 21 ml f Col on 9 21 ml f Compl exScalar 9 23 ml f CreateCol onl ndex 9 22 ml fEnd 9 22 ml fFeval TableSetup 9 21 ml fl ndexAssign 9 21 ml fl ndexDel ete 9 21 mi fl ndexRef 9 21 mf Printf 922 ml f Print Matrix 9 23 ml fScalar 9 23 mfSetErrorHandler 9 21 m fSetlLibraryAllocFcns 9 22 ml fSetPrintHandler 9 23 MATLAB C Math Library conventions 1 3 installing PC details 1 10 UNIX details 1 10 with MATLAB 1 9 without MATLAB 1 10 number of routines 1 2 MATLAB M File Math Library 9 24 callin
157. ing D A B C D 3 35 3 W orking with MATLAB Arrays This code produces the following output The mfPrintMatrix output 2x3 double 1x5 double my string The mifCell Disp output D 1 1 2 3 4 5 6 7 8 9 10 D 2 my string D 3 1 2 3 4 5 6 3 36 W orking with MATLAB Structures Working with MATLAB Structures A MATLAB structure can be thought of as a one dimensional cell array in which each cell is assigned a name These named cells are called fields You can create multidimensional arrays of structures all the structures in an array of structures must have the same fields Table 3 5 lists the MATLAB C Math Library routines used to create structures and perform basic tasks with them The sections that follow provide more detail about using these routines For more detailed information about using structures seeUsing MATLAB For moredetailed information about any of the library routines see the online MATLAB C Math Library Reference Table 3 5 MATLAB Structure Routines To Use Create a structure an initialize it ml fStruct with values Convert a cell array into a ml fCell2struct structure Determine the names of the fields ml f Fiel dnames in a structure Determine if a string is the name ml fl sfiel d of a field in a structure Access the contents of a field in a ml f Getfield structure Specify the value of a field in a ml fSetfield structu
158. ing an array from a function 4 20 rounding functions 9 13 9 28 row major C array storage 3 14 Runge Kutta 6 22 S saving and loading data example 7 4 scalar array creation functions 5 16 9 23 scalar arrays creating 3 5 scanf 8 14 set operator functions 9 7 9 24 settings compiler 1 12 Index linker 1 12 shared libraries 1 11 1 21 1 32 singular values 9 14 9 31 sound and audio 9 34 sparse matrix 1 3 converting numeric array 3 19 converting to full matrix format 3 23 creating 3 18 creating from data 3 21 sparse matrix functions elementary sparse matrices 9 43 full to sparse conversion 9 20 9 43 linear algebra 9 20 9 44 linear equations 9 44 miscellaneous 9 45 reordering algorithms 9 44 working with nonzero entries 9 20 9 43 special constants 9 10 special operator functions 9 7 specialized math functions 9 29 specialized matrix functions 9 11 9 26 spline interpolation 9 35 stand alone applications building on Microsoft Windows 1 22 building on UNIX 1 13 distributing on Microsoft Windows 1 32 distributing on UNIX 1 21 overview 2 2 storage layout column major vs row major 3 14 string operations 9 16 9 38 string tests 9 16 string to number conversion 9 17 9 39 strings creating 3 25 extracting from array 3 29 structure functions 9 20 9 42 structure indexing accessing a field 5 52 accessing the contents of a field 5 53 assigning values to a field 5 53 assigning values to field elements 5 54 referencing a
159. ings each string must be the same length The routines that create arrays of strings use blanks to pad the strings to the same length In a cell array of strings individual strings can be different lengths For information about cell arrays see Working with MATLAB Cell Arrays on page 3 30 Table 3 3 lists the MATLAB C Math Library routines used to create character arrays and perform some basic tasks with them The sections that follow provide more detail about using these routines F or more detailed information about using character arrays see Using MATLAB For more detailed information about any of the library routines see the online MATLAB C Math Library Reference Table 3 3 Character Array Routines To Use Create a character array mCreateString Create a character array froma ml f Char numeric array Convert a character array to its ml f Doubl e underlying numeric representation Concatenate character stringsintoa mi fStr2mat multidimensional blank padded ml fStreat character array ml fStrvcat Convert an array of blank padded ml fCellstr character strings into a cell array of strings Concatenate each character string ml f Char in acell array of strings intoa multidimensional array of strings 3 25 3 W orking with MATLAB Arrays 3 26 Table 3 3 Character Array Routines Continued To Use Remove extra blank characters from milf Deb ank individual row
160. interpreted MATLAB toC is very simple For example in interpreted MATLAB you invoke the cosine function cos like this Y cos X where both X andy are arrays Using the MATLAB C Math Library you invoke cosine in much the same way ml f Assign amp Y milf Cos X where both X and Y are pointers tomx Array structures Y must beinitialized to NULL ml fAssign assigns the return value from ml f Cos toy Note The example above and all the remaining examples in this chapter use the automated memory management routine ml f Assi gn to bind the array return value to a variable For information about writing functions that use ml f Assi gn and C Math Library automated memory management see Chapter 4 6 3 6 Calling Library Routines 6 4 Passing Optional Input Arguments Some MATLAB functions take optional input arguments t r i for example which returns the lower triangular part of a matrix takes either one input argument or two The second input argument k if present indicates which diagonal to use as the upper bound k 0 indicates the main diagonal and is the default if nok is specified In interpreted MATLAB you invoket ri either as L tril X or L tril X k whereL X andk are arrays k is a 1 by 1 array Because C does not permit an application to have two functions with the same name the MATLAB C Math Library version of thet ri function always takes two arguments The second argument is o
161. into Cell Arrays Assigning Values to a Cell Array You put a value into a cell array in much the same way that you read a value out of a cell array In MATLAB the only difference between the two operations is the position of the cell array relative to the assignment operator left of the equal sign means assignment right of the operator means reference No matter if you re reading or writing values the indexing operations you use to specify which values to access remain the same This is truein the MATLAB C Math Library as well The only difference between reading values from a cell array and writing values to a cell array is the function you call ml f I ndexRef reads values ml f I ndexAssign writes values For example each of the ml f ndexRef examples presented in the previous sections will also work with ml fl ndexAssign if you provide a source array of the correct size as the last argument to ml f I ndexAssign Likeml flndexRef ml flndexAssi gn distinguishes between cell array indexing and standard indexing For example to assign avector 1 2 5 7 11 to the contents of the cell 1 2 of A youwriteA 1 2 1 2 5 7 11 in MATLAB and miflndexAssign amp A ml fScalar 1 mlfScalar 2 vector in C with the MATLAB C Math Library Assume the array variablevector is set to the vector of primes above You could have written the previous assignment in MATLAB as A 1 2 1 2 5 7 11 Thecorresponding
162. irectory Thebi n directory contains the DLLs required by stand alone applications After installation reboot your machine To verify that the MATLAB C Math Library has been installed correctly build one of the example programs distributed with the library You can find the example programs in the lt mat ab gt extern examples cmath directory where lt mat ab gt is your root MATLAB installation directory See Building C Applications on page 1 11 to learn how to build the example programs using the mb ui d command You can spot check the installation by checking for the file mat ab h in lt matlab gt extern include andli bmmfile dll libmatlb dll and libmec dil in lt matlab gt bin Building C Applications Building C Applications This section explains how to build stand aloneC applications on UNIX systems and PCs running Microsoft Windows The section begins with a summary of the steps involved in building C applications with the mbui d script and then describes platform specific issues for each supported platform mbui d helps automate the build process You can use the mbui d script to build the examples shipped with the library and to build your own stand alone C applications Packaging Stand Alone Applications To distribute a stand alone application you must include the application s executable as well as the shared libraries with which the application was linked The necessary shared libraries vary b
163. is not used and NULL is passed Note mi fSize is what s called a purevarargout function Pure varargout functions have no required or optional outputs and no return value The variable that would ordinarily be used to store the return value must instead be passed to the pure varargout function as the first argument of the ml fVarargout routine Constructing an mlfVarargoutList You recognize avarargout function prototype in the library by its argument of type ml f Varargout List The MATLAB C Math Library positions an ml fVarargoutList structureasthelast output argument for functions that can return any number of output values for example mxArray mlfVarargout_function mxArray y ml fVarargoutList varargout mxArray a mxArray b An mi fVarargoutList is always the last output argument passed to the function Any required and optional arguments precede it The MATLAB C Math Library provides two functions that construct an ml fVarargoutList structure mi fVarargout andmifindexVarargout Whether you pass indexed varargout arguments tothevarargout function determines which function you use e Usemi f Varargout if you re not applying a subscript to any of your varargout output arguments e Usemi fl ndexVarargout if you areapplying a subscript to at least one of your varargout output arguments How to Call MATLAB Functions Forming a List of Non Indexed varargout Arguments f you are not indexing into an
164. ith MATLAB Arrays 3 40 This code generates the following output tree 37 4000 birch category tree height 37 4000 name birch Using Assignment to Create Structures You can also create a structure by assigning a valuetoa location in a structure usingtheml f ndexAssi gn routine The MATLAB C Math Library creates a structure or array of structures large enough to accommodate the location specified by the index string For more information about structure indexing see Chapter 5 The following example is equivalent to the MATLAB statement A 2 struct name jim number 312 mxArray A NULL ml fl ndexAssi gn amp A aad Wee Ree Index subscript format string mlfScalar 2 Index subscript value ml fStruct mxCreateString name Field mxCreateString Jim Value mxCreateString number Field ml f Scal ar 312 Value NULL mi f Print Matrix A ml fDestroyArray A The following output shows the structure created by this code fragment 1x2 struct with fields name number For more detailed information about using ml f ndexAssi gn toassign values to fields in a structure see Chapter 5 Performing Common Array Programming Tasks Performing Common Array Programming Tasks The following sections describes common array programming tasks that you must perform for all types of MATLAB array Allocating and Freeing
165. ive OR ml f Union Set union ml f Uni que Set unique Special Operator Functions Function Purpose ml f Colon Create a sequence of indices ml fCreateColonindex Create an array that acts like the colon operator 3 fCtranspose fEnd fHorzcat fTranspose fVertcat Complex Conjugate Transpose Index to the end of an array dimension Horizontal concatenation Noncomplex conjugate transpose Vertical concatenation 9 7 9 Library Routines 9 8 Logical Functions Function Purpose ml f Find Find indices of nonzero elements ml f Finite Extract only finite elements from array ml fisa True if object is a given class ml flschar True for character arrays strings ml fl sempt y True for empty array ml fl sequal True for input arrays of the same type size and contents mflsfinite mi fl si nf mflsletter ml flslogical ml fl snan mi flsreal 3 flsspace 3 flogical f Tobool 3 True for finite elements of an array True for infinite elements True for elements of the string that are letters of the alphabet True for logical arrays True for Not a Number True for noncomplex matrices True for whitespace characters in string matrices Convert numeric values to logical Convert an array toa Boolean value by reducing the rank of the array toa scalar The MATLAB Builtln Library MATLAB as a Programming Language Function P
166. ix that indicates which elements in row two of matrix X are greater than 9 B is the result of the greater than gt operation ml fAssign amp target_row mi fIndexRef X mfScalar 2 ml f CreateCol onl ndex mi fAssign amp B mifGt target_row mlfScalar 9 and contains the vector 0110 Using mlflndexRef for Logical Indexing In MATLAB 8 X 2 gt 9 performs the same operation UseB as a logical index that selects those elements from matrix X mi fAssign amp C miflndexRef X mlfScalar 2 B selects these elements 11 10 Extending Logical Indexing to N Dimensions Logical indexing works on n dimensional arrays just as you d expect The logical filtering happens the same way and the subscript size governs the result size in the same manner For details on the syntax see Extending Two Dimensional Indexing to N Dimensions on page 5 29 5 35 5 Indexing into Arrays Using mlifindexAssign for Assignments This section describes how to assign e A single element to an array e Multiple elements to an array e Values to all the elements in an array The examples work with matrix A A wn e ao uw PA wo oom Thereis nofunctional difference between two dimensional indexed assignment and n dimensional indexed assignment where N gt 2 Because it is easier to understand two dimensional arrays most of the examples in this section deal with two dimensional arrays See
167. k function actually executes the target function 6 Prepare results for printing The output consists of four columns The first column is the time step and the other columns are the value of the function at that time step The values arereturnedin onelong column vector If there aren time steps the values in column 1 occupy positions 0 through n 1 in the result the values in column 2 positions n through 2n 1 and so on 7 Print oneline for each timestep The number of time steps is determined by the number of rows in the array t m returned from ml f 0de23 The function mx Get M returned the number of rows in its mxArray argument 8 Freeall bound arrays and exit 6 30 Passing Functions As Arguments to Library Routines Output The output from this program is several pages long Here are the last lines of the output pa WO WO LWO WO UWO LWO WO UWO LWO WO WO LWO WO UWO LWO WO UWO WO WO WO WO WO WO WO WO WO oO t 390 405 418 430 442 AgS 469 484 500 518 2939 ood 565 580 598 620 645 674 709 150 198 843 873 903 O31 960 988 000 41 39 38 37 35 34 32 31 29 28 26 25 24 23 22 21 20 19 18 17 IT 18 20 22 26 29 32 34 yl 218 828 530 135 717 229 711 185 657 123 563 635 764 861 818 682 488 280 143 SLIS 162 378 156 821 021 676 932 012 paa jt e N 1 ae S Va E E P A
168. ked to verify your information Changing the Default Compiler To change your default C compiler you select a different options file You can do this at any time by using thes et up command 1 24 Building a Stand Alone Application on Microsoft W indows This example shows the process of changing your default compiler to the Microsoft Visual C C Version 6 0 compiler mbuild setup Please choose your compiler for building standalone MATLAB applications Would you like mbuild to locate installed compilers y n n Choose your C C compiler 1 Borland C C version 5 0 5 2 or 5 3 2 Microsoft Visual C C version 4 2 5 2 or 6 0 3 Watcom C C version 10 6 or 11 0 None Compiler 2 Choose the version of your C C compiler 1 Microsoft Visual C C 4 2 2 Microsoft Visual C C 5 0 3 Microsoft Visual C C 6 0 version 3 Your machine has a Microsoft Visual C C compiler located at D Program Files DevStudi 06 Do you want to use this compiler y n y Please verify your choices Compiler Microsoft Visual C C 6 0 Location D Program Files DevStudi 06 Are these correct yl n y 1 25 1 G etting Ready 1 26 The default options file C WENNT Profiles username Application Data MathWorks MATLAB compopts bat is being updated If the specified compiler cannot be located you are given the message The default location for compiler name is directory name but th
169. ker Not Found On PCs running Windows if you get errorssuch asBad command or filename orFile not found make sure the command line tools are installed and the path and other environment variables are set correctly mbuild Nota Recognized Command If mbui ld is not recognized verify that lt mat ab gt bin ison your path On UNIX it may be necessary to rehash Cannot Locate Your Compiler PC If mbui d has difficulty locating your installed compilers it is useful to know how it goes about finding compilers mbui d automatically detects your installed compilers by first searching for locations specified in the following environment variables e BORLAND for the Borland C C Compiler Version 5 0 or 5 2 e WATCOM for the Watcom C C Compiler Version 10 6 or 11 0 Troubleshooting mbuild e MSVCDIR for Microsoft Visual C C Version 5 0 or 6 0 e MSDEVDI R for Microsoft Visual C C H Version 4 2 Next mbui d searches the Windows Registry for compiler entries Note that Watcom does not add an entry to the registry Internal Error When Using mbuild setup PC Some antivirus software packages such as Cheyenne AntiVirus and Dr Solomon may conflict with the mbuild setup process If you get an error message during mbui ld setup of the following form mex bat internal error in sub get_compiler_info don t recognize lt string gt then you need to disable your antivirus software temporarily and rerun mbuild setup Af
170. l Ea a rad Grease alae Wa a i 9 17 Data Types jc shes wh hated wh aed wae ee a eo 9 18 Timeand Dates 0 ec eee 9 19 Multidimensional Array Functions 2 0005 9 19 Cell Array Functions 00000 cece eee 9 19 Structure FUNCtIONS 0 cee ee 9 20 Sparse Matrix Functions 000 c eee ee 9 20 Utility Routines 2 0 ee ee 9 21 MATLAB M File Math Library 9 24 Operators and Special FunctionS 000 cece eee 9 24 Elementary Matrices and Matrix Manipulation 9 25 Elementary Math Functions 000c eee eens 9 27 Specialized Math FunctionS 0 00 cece eee eee 9 29 Numerical Linear Algebra 000 cee eee eee eee 9 31 Data Analysis and Fourier Transform Functions 9 33 Polynomial and Interpolation Functions 9 35 Function Functions and ODE Solvers 0 45 9 37 Character String FunctionS 0 00 e cence eens 9 38 Filel O FUNCHIONS 1 0 ccc teens 9 40 Timeand Dates cece ene 9 40 Multidimensional Array Functions 0 0005 9 42 Cell Array Functions 0 00000 cece eee 9 42 Structure FUNCtIONS Sess arreen eee ee 9 42 Sparse Matrix Functions 0 000 cece eee eee eens 9 43 Array Access and Creation Library 9 46 Directory Organization A Directory Organization on UNIX 005 A 3 matlab DIN aa
171. l f Assi gn is like the assignment operator Its first argument an mx Arr ay corresponds to the lefthand side of an assignment statement Its second argument an mx Arr ay corresponds to the righthand side For example ml fAssign amp B ml fRand dim is equivalent tothe MATLAB code B rand di m By passing a pointer to an initialized toNULL or a valid array array variable as an output argument to a function Internally the function assigns a value to it by calling ml f Assi gn For example mxArray U NULL S NULL V NULL ml fAssign amp U m fSvd amp S amp V X NULL ml f Svd callsml fAssign on the output arguments S and V making them bound arrays e You can nest calls to MATLAB C Math Library functions For example ml fAssign amp z mifPlus mfSin x ml fCos y e You must delete each array that is bound to a variable For example mxDestroyArray A Paradigm for Working with Local Array Variables If you follow this paradigm in your code managing memory for local array variables becomes straightforward Implied by the paradigm Let the library manage array memory between the initialization of arrays and the deletion of arrays Using Arrays Under Automated M emory M anagement e Declareand initializelocal array variables at the beginning of your function For example from the template code on page 4 2 mxArray local_return_value NULL mxArray local_varl NULL mxArray l
172. l f Mi n Smallest component ml f Prod Product of elements ml f Sort Sort in ascending order ml f Sum Sum of elements Filtering and Convolution Function Purpose ml f Filter One dimensional digital filter see online help Fourier Transforms Function Purpose ml f Ff t Discrete F ourier transform mi f Fftn Multidimensional fast Fourier transform 9 15 9 Library Routines Character String Functions General Function Purpose ml f Char ml f Double Create character array string Convert string to numeric character codes String Tests Function Purpose mi flschar mflsletter m flsspace True for character arrays True for elements of the string that are letters of the alphabet True for whitespace characters in strings String Operations Function Purpose m m 3 flower fStromp fStrempi fStrncmp fStrncmpi f Upper Convert string to lower case Compare strings Compare strings ignoring case Compare the first n characters of two strings Compare first n characters of strings ignoring case Convert string to upper case 9 16 The MATLAB Builtln Library String to Number Conversion Function Purpose ml f Sprint f Convert number to string under format control ml fSscanf Convert string to number under format control File I O Functions File Opening and Closing Function Purpos
173. l fHorzcat andmifVertcat functions to create the vectors and matrices that are used as indices ml f Horzcat concatenates its arguments horizontally ml f Vert cat concatenates its arguments vertically Assumptions for the Code Examples Refer to the online MATLAB C Math Library Reference for more information onmi fScalar mlfCreateCol onlndex mxCreateDoubl eMatrix mxGet Pr mlfHorzcat andmlfVertcat 5 17 5 Indexing into Arrays Using mifindex Ref for One Dimensional Indexing This section describes how to select e A single element with a one dimensional scalar index e A vector with a one dimensional vector index e A subarray with a one dimensional matrix index e All elements in the matrix with the colon index All examples work with example matrix 4 Notice that the value of each element in A is equal to that element s position in the column major enumeration order For example the third element of A is the number 3 and the ninth element of A is the number 9 7 8 9 wWwnr amp aw fs I Assumptions for the Code Examples on page 5 16 explains the conventions used in the examples Overview A one dimensional subscript contains a single index When you use the MATLAB C Math Library to perform one dimensional indexing you pass ml fI ndexRef a pointer to one array that represents the index The index array can contain a scalar vector matrix or the return from a call to the ml f Cr
174. le Program Defining Try Catch Blocks ex6 c on page 8 6 Release notes for the current release of the MATLAB C Math Library Directory O rganization on Microsoft W indows Directory Organization on Microsoft Windows This figure illustrates the folders that contain the MATLAB C Math Library files lt mat ab gt symbolizes the top level folder where MATLAB is installed on your system lt matl ab gt bin extern include exampl es cmath lt matiab gt bin The lt matlab gt bin directory contains the Dynamic Link Libraries DLLs required by stand alone C applications and the batch file mbui d which controls the build and link process for you lt mat ab gt bi n must be on your path for your applications to run All DLLs are in WIN 32 format libmat dll MAT file access routines to support ml f Load and ml fSave libmatib dll MATLAB Built In Math Library Contains stand alone versions of MATLAB built in math functions and operators Required for building stand alone applications libmi dl Internal MAT file access routines A Directory Organization li bmmfile di li bmx dl li but dl mbuild bat compopts bat Options files for mbui ld bat MATLAB M File Math Library Contains stand alone versions of the MATLAB math M files Needed for building stand alone applications that require MATLA
175. lement 000000 e ee eee 5 50 Deleting an Entire Dimension 0 005 5 50 vii viii Contents Indexing into MATLAB Structure Arrays 5 51 OVS EW a ae cre tar eae a a e oh area Sa eae a 5 51 Tips for Working with StructureArrays 5 52 Accessing a Field 0 0c cece tte 5 52 Accessing the Contents of a Structure Field 5 53 Assigning Values toa Structure Field 5 5 53 Assigning Values to Elements in a Field 05 5 54 Referencing a Single Structure in a Structure Array 5 54 Referencing into Nested Structures cece eee 5 54 Accessing the Contents of Structures Within Cells 5 55 Deleting Elements from a Structure Array 5 55 Deleting a Structure from the Array 4 5 5 56 Deleting a Field from All the Structures in an Array 5 56 Deleting an Element from an Array Contained by a Field 5 56 Comparison of C and MATLAB Indexing Syntax 5 57 Calling Library Routines OVERVICW oo Oh hese ee ete Be Nets Cae ticle Coe he 6 2 How to Call MATLAB Functions 63 Returning One Output Argument and Passing Only Required Input APQUMENES sc Gee ae ee ade ae ee 6 3 Passing Optional Input Arguments 0000 6 4 Passing Optional Output Arguments 0 00 6 4 Passing Optional Input and Output Arguments 65
176. lement in row 3 just as A 3 2 end does in MATLAB mxArray two NULL end_index NULL B NULL m fAssign amp two mfScalar 2 ml fAssign amp end index mfColon two mlfEnd A two two NULL ml fAssign amp B miflndexRef A ml fScalar 3 end_index The second argument to mi f End t wo identifies the dimension where ml fEnd iS used here the column dimension The third argument t wo indicates the number of indices in the subscript for two dimensional indexing it is always two This code selects these elements from matrix A 6 9 Selecting a Row or Column Use a colon index and a scalar index to select an entire row or column For example miflndexRef A mfScalar 1 mlfCreateCol onl ndex selects the first row 147 Using mlflndexRef for N Dimensional Indexing mlflndexRef A ml fCreateCol onl ndex mlfScalar 2 selects the second column 4 5 6 Selecting a Matrix Use two vector indices or a vector and a matrix index to extract a matrix You can usethefunction ml f HorzCat mlfVertcat ormlfCreateCol onl ndex to make each vector or matrix index or use mx Array variables that contain vectors or matrices returned from other functions The indexing code iterates over both vector indices in a pattern similar toa doubly nested f or loop for each element in the row index for each element J in the column index select the matrix element A l J For ea
177. lements from a row or column The examples work with matrix A and the logical array B A wn e wm co B 101 010 101 Assumptions for the Code Examples on page 5 16 explains the conventions used in the examples Overview Logical indexing is a special case of n dimensional indexing A logical index is a vector or a matrix that consists entirely of ones and zeros Applying a logical subscript toa matrix selects the elements of the matrix that correspond to the nonzero elements in the subscript Logical indices are generated by the relational operator functions mi f Lt ml f Gt mlfLle mlfGe ml fEq ml f Neq and by the function ml f Logi cal Because these functions attach a logical flag toa logical matrix you cannot create a logical index simply by assigning ones and zeros to a vector or matrix You can form an n dimensional logical subscript by combining a logical index with scalar vector matrix or colon indices 5 31 5 Indexing into Arrays 5 32 Using a Logical Matrix as a One Dimensional Index When you use a logical matrix as an index the result is a column vector F or example if the logical index matrix B equals ror oro 1 0 1 Then ml fAssign amp X mlflndexRef A B equals won Om Ww Pe Notice that B has ones at the corners and in the center and that the result isa column vector of the corner and center elements of A Note that you can createB by callin
178. library routines that take multiple optional arguments The example uses the singular value decomposition function ml f Svd You can find the code for this examplein the lt matlab gt extern examples cmath directory on UNIX systems or the lt matl ab gt extern exampl es cmath directory on PCs where lt mat ab gt represents the top level directory of your installation See Building C Applications in Chapter 1 for information on building the examples How to Call MATLAB Functions 1 ex3 c include include include include g lt st di lt stdl lt stri mat 0 h gt i b h gt ng h gt ab h static double data 1 3 5 7 2 4 6 8 mai n Initialize pointers to array arguments mxArray X mxArray U ml f As l ml f As ml f Pr ml f Pr Mu fAs fPr fPr fPr fPr a 132 Se Se Se Mu fAs fPr fPr fPr fPr See Se 1S Sr sign sign i ntf int Ma tip sign i ntf i ntf i ntf i ntf tip sign i ntf i ntf i ntf i ntf NU NU amp X m amp U m One tri x e out amp U m One Ys S Vy e inp amp U m Two Y S Vy Vie LL S NULL V NULL mifEnterNewContext 0 0 fDoubl eMatrix 4 2 data NULL Compute the singular value decomposition and print it fSvd NULL NULL X NULL input one output nU n U put arguments fSvd amp S amp V X NULL input
179. lls the installed print handler which in this example is the default print handler See the section Chapter 8 for details on writing and installing a print handler 5 Freethe matrices The program produces this output 1 3 5 2 4 6 1 0000 7 0000i 4 0000 10 0000i 2 0000 8 0000i 5 0000 11 00001 3 0000 9 0000i 6 0000 12 00001 3 17 3 W orking with MATLAB Arrays 3 18 Working with MATLAB Sparse Matrices The MATLAB C Math Library includes routines to create and manipulate Sparse arrays Sparse matrices provides a more efficient storage format for two dimensional numeric arrays with few non zero elements Only two dimensional numeric arrays can be converted to sparse storage format Table 3 2 lists the MATLAB C Math Library routines used to create sparse matrices and perform some basic tasks on them The sections that follow provide more detail about using these routines F or more detailed information about using sparse arrays see Using MATLAB For more detailed information about any of the library routines see the online MATLAB C Math Library Reference Table 3 2 Sparse Matrix Routines To Use Create a sparse matrix ml f Sparse Convert a sparse matrix into a full ml f Full matrix Replace nonzero sparse matrix ml f Spones elements with ones Replace nonzero sparse matrix ml f Sprand elements with random numbers ml f Sprandn ml f Sprandnsym Import from external sparse matrix mi f
180. matically configures itself for the appropriate compiler So for many users to create a C stand alone application you can simply enter mbuild filename c This simple method works for the majority of users It uses your installed C compiler as your default compiler for creating your stand alone applications e f you area user who does not need to change compilers or you do not need to modify your compiler options files you can skip ahead in this section to Verifying mbuild e f you need to know how to change the options file or select a different compiler continue with this section Systems with More than One Compiler On systems where there is more than one C compiler the mbui d utility lets you select which of the compilers you want to use Once you choose your C compiler that compiler becomes your default compiler and you no longer have to select one when you compile your stand alone applications 1 23 1 G etting Ready F or example if your system has both the Borland and Watcom compilers when you enter for the first time mbuild filename c you are asked to select which compiler to use mbuild has detected the following compilers on your machine 1 o 0 Borland compiler in T Borland BC 500 WATCOM compiler in T watcom c 106 None Please select a compiler This compiler will become the default Select the desired compiler by entering its number and pressing Return Y ou are then as
181. me operation in MATLAB Note that d is a scalar array not a cell array Indexing Nested Cell Arrays Toindex nested cells concatenate subscripts in the indexing string The first set of subscripts accesses the top layer of cells and subsequent sets of braces access successively deeper layers of cells 5 47 5 Indexing into Arrays 5 48 For example array A represented in this diagram has three levels of cell nesting the 1 by 2 cell array itself the 2 by 2 cell array nested in cell 1 2 and the 1 by 2 cell array nested in cell 2 2 cell 1 1 cell 1 2 1724 1 8 15 5 2 8 23 5 7 14 16 7 3 0 Test 1 4 6 13 20 22 6 7 3 10 12 19 21 3 11 18 25 2 9 2 4i 5 7i 17 Indexing the First Level To access the 2 by 2 cell array in cell 1 2 miflndexRef A mfScalar 1 mi fScalar 2 In MATLAB 4 1 2 performs the same operation Indexing the Second Level To access the 1 by 2 array in position 2 2 of cell 1 2 mi flndexRef A 2 mi fScalar 1 mfScalar 2 mi fScalar 2 mfScalar 2 A 1 2 1 1 in MATLAB performs the same operation Indexing the Third Level To access the empty cell in position 2 2 of cell 1 2 miflndexRef A mifScalar 1 mlfScalar 2 mlfScalar 2 m fScalar 2 mi fScalar 1 mfScalar 2 A 1 2 2 2 1 2 in MATLAB performs the same operation Indexing
182. ml f Print Matrix routine This routine can display all types of MATLAB arrays of any dimension The following code fragment creates a 2 by 2 matrix 3 41 3 W orking with MATLAB Arrays 3 42 filled with ones and then uses ml f Pri nt Mat rix to output the array tothe screen mxArray A NULL ml fAssign amp A m f Ones mf Scalar 2 mlfScalar 2 NULL ml f Print Matrix A mxDestroyArray A This code produces the following output 1 1 1 1 When used with a cell array the mi f Print Matrix output includes the type and size of the array stored in each cell but not the data in the array except for scalar arrays and character arrays To view the data in each cell in a cell array you must use theml f Cel di sp routine See page 3 34 for more information Formatting Output You can also create formatted array output using theml f Fpri ntf routine This routine allows you to create your own output formats and applies these formats toall the elements in a MATLAB array For example if you specify the format string d ml f Fprintf prints out each element in an array as an integer Note Donotconfusemffprintf withmfPrintf mlfFprintf can format MATLAB arrays ml f Printf does not ml fPrintf isthesameas the standard C pri nt f routine except that it directs output to the MATLAB print handler For more information about print handlers see Chapter 8 Performing Common Array Programming Task
183. mple to convert these MATLAB indexed assignment expressions into MATLAB C Math Library indexed assignment expressions A 2 eye 3 becomes m flndexAssign amp A mlfCreateCol onl ndex ml fCreateColonindex mlfScalar 2 ml fEye mlfScalar 3 NULL Asa result of this operation the 3 by 3 array on page 2 of A becomes oOo FF or o re Oo A 1 ones 1 3 2 becomes ml flndexAssign amp A mf Scalar 1 ml fCreateColonindex ml fCreateColonindex ml fOnes mifScalar 1 mfScalar 3 mifScalar 2 NULL As aresult of this operation row 1 on both pages of A becomes all ones Page 1 111 25 8 3 6 9 Page 2 1 1 1 11 14 17 12 15 18 Finally A 2 2 2 42 becomes ml flndexAssign A mlfScalar 2 mlfScalar 2 mlfScalar 2 mlfScalar 42 Using mlflndexAssign for Assignments As a result of this operation the element at 2 2 2 changes to the number 42 Page 2 10 13 16 1142 17 12 15 18 If the array A had more than three dimensions the index strings would have more than three s in them and they would be followed by more than three index values All of the other types of indexing discussed in this chapter assigning to entire rows and columns etc work equally well on N dimensional arrays 5 41 5 Indexing into Arrays Using mifindex Delete for Deletion 5 42 This section e Describes how to delete a single element from an array
184. must begin with a call toml fEnterNewContext Typically place the call after the declaration and initialization of local variables You must call mi f EnterNewContext before the first call to ml fAssign The call toml f Enter NewContext signals that MATLAB C Math Library automated memory management is in effect for the function ml f Enter NewContext operates on the output and input array arguments passed to your function It ensures that the memory allocated for those arrays whether temporary or bound persists for the duration of the function Prototype void mlfEnterNewContext int nout int nin Sample Call from Template ml fEnterNewContext 1 2 output_argl input_argl input_arg2 W riting Functions Under Automated Memory Management Arguments to mlifEnterN ewContext ml f Enter NewContext takes the number of output arguments the number of input arguments and a variable length list of the actual output and input arguments to the function Y ou do not need to terminate the list of arguments with aNULL argument Pass these arguments to ml f EnterNewContext in the order listed 1 Thenumber i nt nout of array output arguments declared by your function Specify 0 if there are no array output arguments declared in the same way the mai n template function does on page 4 16 The template function declares one output argument 2 Thenumber i nt nin of array input arguments declared by your function
185. mxArray B NULL ml f Assi gn amp B mi fl ndexRef A index format string mfScalar 2 row two mi f CreateCol onl ndex mf Print Matrix mlfSize NULL B NULL mf PrintMatrix mlfSize NULL ml fDebl ank B NULL mi f Print Matrix B mxDestroyArray B This code produces the following output 1 9 1 6 3 29 3 W orking with MATLAB Arrays 3 30 Working with MATLAB Cell Arrays MATLAB cell arrays provide a way to group together a collection of dissimilar MATLAB arrays Table 3 4 lists the MATLAB C Math Library routines used to create cell arrays and perform basic tasks with them The sections that follow provide more detail about using these routines F or more detailed information about using cell arrays see Using MATLAB For more detailed information about any of the library routines see the online MATLAB C Math Library Reference Table 3 4 Cell Array Routines To Use Create a multidimensional array of milf Cell empty cells Convert an array of blank padded mf Cell str character strings into a cell array of strings Create a cell array by concatenating mifCell hcat existing arrays Convert a structure into a cell array mifStruct2Cell Convert a numeric array into a cell ml f Num2cell array View the contents of each cell in a ml f Cell dis p cell array Creating Cell Arrays The MATLAB C Math Library allows you to create cell array
186. n Usingml f Vert cat and ml f Hor zcat you can only create two dimensional arrays To create a multidimensional numeric array through concatenation you must use the ml f Cat routine As arguments toml f Cat you Specify the dimensions along which to concatenate the arrays 3 10 W orking with MATLAB N umeric Arrays For example the following code fragment creates two matrices and then concatenates them to create a three dimensional array mxArray A NULL mxArray B NULL mxArray C NULL static double datal static double data2 folie she De E 6 7 10 8 11 9 12 ml fAssign amp A mifDoubleMatrix 2 3 datal NULL ml f Assign amp B milf DoubleMatrix 2 3 data2 NULL ml fAssign amp C mifCat mfScalar 3 A B NULL mi f Print Matrix C mxDestroyArray A mxDestroyArray B mxDestroyArray C This program displays the following output 25 2 1 E 1 2 3 4 5 6 2 5 8 10 11 12 Creating Numeric Arrays by Assignment You can also create a numeric array by assigning a value to a location in the array using theml f ndexAssi gn routine The MATLAB C Math Library creates a numeric array large enough to accommodate the specified location or expands an existing array 3 11 3 W orking with MATLAB Arrays 3 12 The following example is equivalent tothe MATLAB statement A 2 2 17 TheC character string specifies the format of the index subscrip
187. n the following indexing expression pass the values for the indices in the two dimensional subscript 2 1 1f A were an array with morethan two dimensions you could specify morethan two dimensions in the index string and pass more than two index values to mi fl ndexRef miflndexRef A mfScalar 2 mlfScalar 1 The indexing functions apply the subscript to the target array Each function constructs the subscript based on the content of the indexing string The indexing functions count the number of expressions that are delimited by commas within each parenthesized or bracketed subscript within the indexing string to determine the structure of the subscript s and the number of mx Array index arguments to expect How to Call the Indexing Functions Note Donot supply NULL to terminate the list of arguments passed to an indexing function Each function detects the end of the argument list by counting the number of arguments indicated by the indexing string itself Specifying a Source Array for Assignments ml f ndexAssi gn requires one more argument than the other two indexing functions a pointer to an mx Array that contains the new values for the target array Pass the source array after the mx Array arguments that specify the values for the subscript Note that this source array must be exactly the same size as the subset of the target array specified by the indexing expression 5 15 5 Indexing in
188. nctions will of course vary the number of input and output arguments Notice how ml f EnterNewContext andmlif RestorePreviousContext operate on the array arguments passed toFuncti onName milf ReturnVal ue manipulates the array returned from Functi onName mxArray FunctionName mxArray output_argl mxArray input_argl mxArray input_arg2 mxArray local_return_value NULL mxArray local_varl NULL mxArray local_var2 NULL ml fEnterNewContext 1 2 output_argl input_argl input_arg2 Perform the work of the function OOS gaa SI Note Don t destroy local_return_ value mxDestroyArray local_varl mxDestroyArray local_var2 mi f RestorePreviousContext 1 2 output_argl input_argl input_arg2 return ml fReturnValue local_return value 4 15 4 Managing Array Memory 4 16 Main Routine Template The template for the mai n routine is different from the general template because mai n does not take any array input or output arguments or return an array Passing0 as an argument toml f EnterNewContext and ml fRestorePrevi ousContext indicates that mai n hasnooutput and input array arguments A call toml f ReturnVal ue iS not required int main Initialize variables mi f Enter NewContext 0 0 Performthe work of main mi f RestorePreviousContext 0 0 return EXIT_SUCCESS Preparing Function Arguments for a New Context Each function that you write
189. nd mi fI ndexDel et e amp N mfScalar 2 in C to remove element 2 1 from N Deleting an Entire Dimension You can delete an entire dimension by using vector subscripting to delete a row or column of cells Use parentheses within the indexing string to indicate that you are deleting the cells themsd ves miflndexDelete amp N mf Scalar 2 mf CreateCol onl ndex N 2 performs the same operation in MATLAB N 2 isan error because the number of items on the right and left hand side of the assignment operator is not thesame MATLAB does not doscalar expansion on cell arrays In MATLAB if you want to set both cells in the second row of N to writeN 2 thereby assigning a 1 by 2 cell array to another 1 by 2 cell array Note Thelast subscript in an array deletion must use not Indexing into MATLAB Structure Arrays Indexing into MATLAB Structure Arrays This section describes how e Toaccess a field in a structure array e Toaccess elements within a field of a structure e Toassign a value toa field in a structure array e Toassign a value to an element of a field e Cell arrays and structure arrays interact e Todeletea field from a structure Overview A MATLAB structure is very much like a structurein C it is a variable that contains other variables Each of the contained variables is called a fidd of the structure and each field has a unique name F or exampl
190. ndexRef A mi fScalar 2 mi fHorzcat mlfScalar 1 m fScalar 3 NULL you select the first and third elements or first and third columns of row 2 2 8 If the vector index contains the same number multiple times the same element is extracted multiple times F or example ml f Assi gn amp B mi fI ndexRef A mi fScalar 2 mi f Horzcat mlfScalar 3 m fScalar 3 NULL returns two copies of the element at A 2 3 8 8 Note You can pass any number of arguments toml f Horzcat or ml f Vertcat You can nest calls to either function 5 25 5 Indexing into Arrays 5 26 Specifying a Vector Index with mlfEnd Theml f End function which corresponds to the MATLAB end function provides another way of specifying a vector index Given an array a dimension 1 row 2 column 3 page and soon and the number of indices in the subscript ml f End returns the index of the last element in the specified dimension You then use that scalar array to generate a vector index See Specifying a Vector Index with mlfEnd on page 5 20 for a more complete description of how and why you use theend function in MATLAB Given the row dimension ml f End returns the number of columns Given the column dimension it returns the number of rows The number of indices in the subscript corresponds to the number of index arguments you pass to mi fl ndexRef This code selects all but the first e
191. ndow procedure Fill in your own code here Create application main window window CreateWindowEx your specification Set print handler ml fSetPrintHandler PopupMessageBox The rest of the program This example does no real processing If it were a real program the main routine would contain calls to other routines or perform computations of its own 8 18 Library Routines Why Two MATLAB Math Libraries 9 3 The MATLAB Built InLibrary 9 4 MATLAB M FileMathLibrary 9 24 Array Access and Creation Library 9 46 9 Library Routines 9 2 This chapter serves as a reference guide to the more than 400 functions contained in the MATLAB C Math Library The functions are divided into three sections e The Built In Library e The M File Math Library e The Array Access and Creation Library Thetables that group the functions into categories include a short description of each function Refer to the online MATLAB C Math Library Reference for a complete definition of the function syntax and arguments W hy Two MATLAB Math Libraries Why Two MATLAB Math Libraries The MATLAB functions within the MATLAB C Math Library are delivered as two libraries the MATLAB Built In Library and the MATLAB M File Math Library The Built In Library contains the functions that every program using the MATLAB C Math Library needs including for example the eleme
192. nputs and outputs as their MATLAB interpreted counterparts Theml f Svd reference page that you find in the online MATLAB C Math Library Reference accessible from the Help Desk begins like this How to Call MATLAB Functions Purpose Singular value decomposition Syntax mxArray X mxArray U NULL S NULL V NULL ml fAssign amp S mi fSvd NULL NULL X NULL ml fAssign amp U mifSvd amp S amp V X NULL ml fAssign amp U mifSvd amp S amp V X mfScalar 0 In C a function can return only one value To overcome this limitation the MATLAB C Math Library places all output parameters in excess of the first in the function argument list The MATLAB svd function can havea maximum of three outputs therefore the ml f Svd function returns one value and takes two output parameters for a total of three outputs Notice that where thes vd function may be called with differing numbers of arguments the ml f Svd function is always called with the same number of arguments four ml f Svd always returns a single value However the calls to ml f Svd arenot identical each has a different number of NULL sin the argument list Each NULL argument takes the place of an optional argument Passing Any Number of Inputs Some MATLAB functions accept any number of input arguments In MATLAB these functions are called varargin functions When the variablevarar gin appears as the last input argument in the definition of a
193. ns d n B array NULL mxDestroyArray A mxDestroyArray B Because the array created is numeric this code produces the following output Isnumeric returns 1 Determining the Size of an Array To determine the size of an array use the ml f Si ze routine Theml f Si ze routine returns a row vector containing the dimensions of the array This code Performing Common Array Programming Tasks example creates a 2 by 3 by2 array and displays the size vector returned by mi f Size mxArray A NULL mxArray dims NULL Create three dimensional array ml fAssign amp A milf Ones milf Scalar 2 ml f Scalar 3 mf Scalar 2 NULL Determine size of array ml f Assign amp dims mi fSize NULL A NULL Display size vector mi f Print Matrix mxCreateString The size of the array is n mi f Print Matrix dims mxDestroyArray A mxDestroyArray di ms This code produces the following output The size of the array is 2 3 2 Obtaining the Length of a Single Dimension You can also get the size of one particular dimension of an array by specifying thedimension as an input argument To get the length of thelongest dimension of a multidimensional array usetheml f Length routine You can also use this routine to determine the size of a vector Returning the Dimensions in Separate Arrays The ml f Si ze routine can optionally return each dimension in a separate array
194. ns file is found mbui d displays an error message 1 13 1 G etting Ready Using the System Compiler If your supported C compiler is installed on your system you are ready to create C stand alone applications To create a stand alone C application you can simply enter mbuild filename c This simple method works for the majority of users Assuming filename c contains a main function this example uses the system s compiler as your default compiler for creating your stand alone application e f you area user who does not need to change C or C compilers or you do not need to modify your compiler options files you can skip ahead in this section to Verifying mbuild e f you need to know how to select a different compiler or change the options file continue with this section Changing the Default Compiler You need to use thes et up option if you want to change your default compiler At the UNIX prompt type mbuild setup Theset up option creates a user specific options file for your ANSI C or C compiler Using thes et up option sets your default compiler so that the new compiler is used every time you use the mb ui d script Note The options file is stored in the MATLAB subdirectory of your home directory for example HOME mat ab mbuil dopts sh This allows each user to have a separate mb ui d configuration Building a Stand Alone Application on UN IX Executing mbuild setup presents a lis
195. nsform functions basic operations 9 15 9 33 correlation 9 33 filtering and convolution 9 15 9 34 finite differences 9 33 Fourier transforms 9 15 9 34 sound and audio 9 34 data analysis basic operations 9 15 9 33 data interpolation 9 35 data type functions data types 9 18 object functions 9 19 date and time functions basic 9 40 current date and time 9 19 9 40 date 9 41 timing 9 41 dates basic functions 9 40 9 41 current 9 19 9 40 def files Microsoft Windows A 8 default handlers print 8 14 DefaultPrintHandl er C code 8 14 deleting arrays 4 11 deletion and indexing 5 42 dialog box modal 8 16 directory organization Microsoft Windows A 7 UNIX A 3 displaying arrays 3 41 distributing applications on Microsoft Windows 1 32 on UNIX 1 21 DLLs Microsoft Windows A 7 E efficiency 5 39 eigenvalues 9 14 9 31 elementary matrix and matrix manipulation functions basic array information 9 10 9 25 elementary matrices 9 10 9 25 matrix manipulation 9 11 9 26 special constants 9 10 specialized matrices 9 11 9 26 elementary sparse matrices 9 43 embedding calls to functions 4 8 4 11 4 27 environment variable library path 1 17 error handling 8 9 ml f SetErrorHandler 8 8 warnings 8 8 error handling functions 9 21 error messages printing to GUI 8 15 errors list of B 3 example building the examples 1 11 integrating a function 6 20 managing array memory 4 24 ml fLoad andmlifSave 7 4 optional arguments 6 14 pas
196. ntary mathematical functions that perform matrix addition and multiplication The M File Math Library is larger than the Built In Library and contains more specialized functions such as polynomial root finding or the two dimensional inverse discrete F ourier transformation Both libraries follow the same uniform naming convention and obey the same calling conventions MATLAB C Math Library programs link dynamically against both math libraries in addition to the Array Access and Creation Library See Building C Applications in Chapter 1 for a complete list of the required libraries 9 3 9 Library Routines The MATLAB Built In Library 9 4 The routines in the MATLAB Built In Library fall into three categories e C callable versions of MATLAB built in functions Each MATLAB built in function is named after its MATLAB equivalent F or example the mi f Tan function is the C callable version of the MATLAB built in tan function e C function versions of the MATLAB operators For example the C callable version of the MATLAB matrix multiplication operator is the function named ml f Mt i mes e Routines that initialize and control how the library operates These routines do not havea MATLAB equivalent For example there is no MATLAB equivalent for the ml f Set Print Handler routine Note You can recognize routines in the Built In and M File libraries by the ml f prefix at the beginning of each function name
197. ocal_var2 NULL Use the local array variables in the course of your function assigning values to them passing them as input or output arguments to other functions In the template code this section is simply commented Performthe work of the function e Destroy local array variables at the end of your function For example from the template code Note Don t destroy local _return value mxDestroyArray local_varl mxDestroyArray local_var2 Note You may be used to initializing local array variables to valid arrays when you declare the variables You can no longer do so Although you can initialize array variables toNULL when you declare them you must make a separate call to ml f Assi gn toinitialize the variable to a valid array Assigning Arrays to mxArray Variables You assign a value to an array variable mxArray by calling ml fAssign MATLAB C Math Library functions call ml f Assi gn to assign values tothe array output arguments passed to them Prototype mxArray mlfAssign mxArray dest mxArray src ml f Assi gn copies the array value from its second argument s r c representing the righthand side of the assignment toits first argument des t representing the lefthand side of the assignment Ifsrc isa temporary array ml f Assi gn only copies the pointer without copying the array data F or example ml f Assign amp Y milf Cos X 4 9 4 Managing Array Memory 4 10
198. oe ml fAssign amp A mi fOnes mifScalar 4 Bound Array Definition of a Temporary Array MATLAB C Math Library functions return pointers to newly allocated mx Ar r ay s as their return values The library marks these arrays as temporary arrays Key Behavior for a Temporary Array When you pass a temporary array as an input argument to another library function that function deletes the temporary array before it returns You do not have to delete it yourself This behavior allows you to embed calls to library functions as arguments to other library functions without leaking memory Definition of a Bound Array To make an array persist you must assign it toa variable by using the function ml f Assi gn or pass an array variable as an output array argument to a library function The MATLAB C Math Library marks the array as a bound array Key Behavior for a Bound array When you pass a bound array as an input argument to another library function the array still exists when the function completes Bound arrays are not automatically deleted you must explicitly delete the array by callingmxDestroyArray 4 7 4 Managing Array Memory 48 Rules for Array Usage You must follow these rules for using arrays under automated memory management e You can assign a valuetoan mxArray variable in two different ways By callingml f Assi gn toassign the return value from a library function to an mxArray variable Conceptually m
199. of structures to accommodate the location specified For more information about W orking with MATLAB Structures using assignment with structures see Using Assignment to Create Structures on page 3 40 Using a Structure Conversion Routine You can also create structures by converting an existing MATLAB cell array into a structure using theml f Cel 2st ruct routine This example creates a cell array to be converted and a second cell array that specifies the names of the fields in the structure You pass these two cell arrays along with the dimensions of the structure array as arguments toml f Cel 2struct mxArray C NULL cell array to convert mxArray F NULL cell array of field names mxArray S NULL structure tif create cell array to be converted ml fAssign amp C mfCell hcat mxCreateString tree mi fScalar 37 4 mxCreateString birch NULL create cell array of field names ml fAssign amp F mifCell hcat mxCreateString category mxCreateString height mxCreateString name NULL convert cell array to structure ml fAssign amp mfCell2struct C F mfScalar 2 fPrintMatrix C f Print Matrix S i 3 f DestroyArray C fDestroyArray F f DestroyArray S 3 3 Note that because ml f Cel hcat accepts a variable number of input arguments you must terminate the input argument list with a NULL 3 39 3 W orking w
200. ois ae ea a e diate eee tsa ews peers 2 2 A Simple Example Program 0 0c anra 2 2 Working with MATLAB Arrays 3 Overview zaeiou a E a E E E Wain ee 3 2 Supported MATLAB Array Types nsanu aaraa 3 2 MATLAB Array C Data Type 00 00 cee eee 3 3 Working with MATLAB Numeric Arrays 3 4 Creating Numeric ArrayS 000 cee eee 3 5 Using Numeric Array Creation Routines 3 5 Creating Numeric Arrays by Calling Arithmetic Routines 3 9 Creating Numeric Arrays by Concatenation 3 9 Creating Numeric Arrays by Assignment 3 11 Initializing a Numeric Array with Data 3 12 Column M ajor Storage versus Row Major Storage 3 14 Example Program Creating Numeric Arrays exl c 3 15 Working with MATLAB Sparse Matrices 3 18 Creating a Sparse Matrix 0 0 0 c cece 3 19 Converting an Existing Matrix into Sparse Format 3 19 Creating a Sparse Matrix from Data 5 3 21 Converting a Sparse Matrix to Full Matrix Format 3 23 Evaluating Arrays for Sparse Storage 0 55 3 23 Working with MATLAB Character Arrays 3 25 Creating MATLAB Character Arrays 0 0000 3 26 Using Explicit Character Array Creation Routines 3 26 Converting Numeric Arrays to Character Arrays 3 27 Creating Multidimensional Arrays of Strings 3 27 A
201. olean value You can also access individual elements in an array using standard MATLAB indexing syntax however the values returned by indexing are MATLAB arrays not scalar values For more information about indexing into arrays see Chapter 5 This call totheml f Catch macro defines the start of the application s catch block The call tothe ml f EndCat ch macro defines the end of the catch block Catch blocks contain error handling code This sample catch block calls the ml fLasterr routine to retrieve the text of the error message associated with the last error and then outputs the message to the user For more information about handling errors with try and catch blocks see Chapter 8 10 Free the MATLAB arrays that were assigned to variables using ml f Assi gn The arrays that were not assigned to variables are freed automatically by the library In the example the arrays returned by the nested calls tomi f Scal ar are deleted automatically The arrays assigned Overview tofactors1 andfactors2 are not deleted automatically For more information about assigning an array toa variable using theml f Assi gn routine see Chapter 4 11 The sample application ends by disabling automated memory management using theml f Rest orePrevi ousCont ext For more information about enabling automated memory management see Chapter 4 Output This sample program when run ina DOS Command Prompt window produces the following output
202. olumns If you join the end of each column to the beginning of the next the numbers are arranged in counting order To recreate this structure in C you need a two dimensional array static double square 3 1 4 7 2 5 8 3 6 9 Notice how the numbers are specified in row major order the numbers in each row are contiguous In memory C lays each number down next to the last so this array might have equivalently in terms of memory layout been declared static double square 1 4 7 2 5 8 3 6 9 Toa C program these arrays represent the matrix first presented a 3 by 3 matrix in which the numbers from one to nine follow one another in counting order down the columns However if you initialize a 3 by 3 MATLAB mxArray structure with either of these C arrays the results will be quite different MATLAB stores its arrays in column major order MATLAB treats the first three numbers in the array as the first column the next three as the second column and the last three as the third column Each group of numbers that C considers to be a row MATLAB treats as a column W orking with MATLAB N umeric Arrays ToMATLAB the C array above represents this matrix Note how the rows and columns are transposed Toconstruct a matrix where the counting order proceeds down the columns rather than across the rows the numbers need to be stored in the C array in column major order static double square 1 2 3 4
203. oma function that uses automated memory management The routine that calls Explicit _Mem Examp e whether it is main or another function cannot include calls toml f Ent erNewCont ext andmlfRestorePrevi ousContext If automated memory management were in effect the calls to the library functions in Explicit _Mem_Example could unexpectedly ddetethe temporary arrays passed to them as input arguments 4 31 4 Managing Array Memory 4 32 mxArray Explicit_Mem_Example mxArray z_out mxArray x_in mxArray resul mxArray templ In MATLAB templ milf Sin temp2 mi fCos temp3 mf Plu result_local mxDestroyArray mxDestroyArray mxDestroyArray In MATLAB templ mi fCos temp2 mf Sin temp3 mif Min q_local mlf mxDestroyArray mxDestroyArray mxDestroyArray In MATLAB templ mifSca mxArray y_in t_local q_local temp2 temp3 r sqrt sin x cos x x_in y_in s templ temp2 ml f Sqrt temp3 templ temp2 temp3 q sqrt cos y sin y y_in y_in us templ temp2 qrt temp3 templ temp2 temp3 z q r q 3 ar 3 temp2 mifPower q_local temp3 7 out ml fTimes q_local ml f Minus temp3 templ result_local temp2 mxDestroyArray mxDestroyArray mxDestroyArray mxDestroyArray return result_ templ temp2 temp3 q_local ocal Restrictions on Function Calling
204. on in theinterpreted MATLAB environment MATLAB takes the arguments you pass and stores them in the cell array called varargout A cell array can hold any size or kind of data The MATLAB function accesses the varying number of arguments passed to it through the cell array Whenever you see an ellipsis within the output argument list of a MATLAB syntax description the function is avarar gout function For example this syntax in the online MATLAB Function Reference specifies a version of the MATLAB function si ze that returns a variable number of outputs depending on the number of dimensions in the array passed to it M1 M2 M3 MN size X If the input argument X isa two dimensional array si ze returns the length of the first dimension in the first output value and the length of the second dimension in a second output value If the input argument is a four dimensional array it returns four lengths For example if the input array X has four dimensions this code retrieves the length of each dimension d1 d2 d3 d4 size X In the MATLAB C Math Library you invoke the same call tosi ze like this mi f Size mlfVarargout amp d1 amp d2 amp d3 amp d4 NULL X NULL 6 9 6 Calling Library Routines 6 10 wherex d1 d2 d3 andd4 aremxArray variables d1 d2 d3 andd4 are each initialized toNULL The final input argument toml f Si ze isan optional input argument in this version of the function that argument
205. ons e m flndexRef e miflndexAssi gn e mi fl ndexDel et e allow you to do exactly the same thing Overview Terminology These two diagrams illustrate the terminology used in this chapter Indices A 3 1 Target Array Subscript Figure 5 1 From the MATLAB Perspective Index Value le mfScalar 3 mfScalar 1 Ara ae aN Target Arra Index Value Indexing String miflndexRef A Figure 5 2 From the MATLAB C Math Library Perspective Dimensions and Subscripts In MATLAB There are three types of data in MATLAB multidimensional numeric arrays cell arrays and structures objects are just a special kind of structure Therefore there are three types of indexing one for each type of data 5 3 5 Indexing into Arrays 5 4 e Standard indexing which uses parentheses in MATLAB e Cell array indexing which uses curly braces in MATLAB e Structure indexing which uses named fields for example col or in MATLAB Both standard indexing and cell array indexing take numeric arguments one argument for each dimension of the array being indexed into while structure indexing uses only the name of the structure field Note Standard indexing can be used with all three types of data while cell array indexing can only be used on cell arrays and structure indexing only on structures You can combine for example standard indexing and structure indexing
206. ons on UNIX Continued Option Description lt name gt lt def gt outdir lt di r name gt output lt name gt 0 setup U lt name gt ENV Override options file setting for variable lt name gt If lt def gt contains spaces enclose it in single quotes for example CFLAGS opt1 opt2 Thedefinition lt def gt can reference other variables defined in the options file To reference a variable in the options file prepend the variable name with a for example CFLAGS CFLAGS opt2 No execute flag Using this option displays the commands that compile and link the target but does not execute them Place any generated object resource or executable files in the directory lt di r name gt Do not combine this option with output ifthe output option gives a full pathname Create an executable named lt name gt An appropriate executable extension is automatically appended Build an optimized executable Set up the default compiler and libraries This option should be the only argument passed Undefine C preprocessor macro lt name gt Verbose print all compiler and linker settings 1 20 Building a Stand Alone Application on UN IX Distributing Stand Alone UNIX Applications To distribute a stand alone application you must include the application s executable and the shared libraries against which the application was linked This package of files includes e
207. ormation 004 15 MATLAB C Math Library 1 2 Users 0 0 4 1 6 MATLAB C Math Library Version 1 2 Documentation 1 6 Migrating Your Code to Version 2 0 0 0005 1 6 Installing the MATLAB C Math Library 1 9 Installation with MATLAB 0 00 e eee eee 1 9 Installation Without MATLAB 00000 eee eae 1 9 Verifying a UNIX Workstation Installation 1 10 Verifying a PC Installation 00 00 e eee 1 10 Building C Applications 05 1 11 Packaging Stand Alone Applications 1 11 Overview 26 teens 1 11 Compiler Options Files 00 0000 c eee eee 1 12 Building a Stand Alone Application on UNIX 1 13 Configuring for C or C eee 1 13 Locating Options Files 0 0 00 eee eee ee 1 13 Using the System Compiler 0000 cee eee eee 1 14 Changing the Default Compiler 2 0 5 1 14 Modifying the Options File 0 00 0 00 1 15 Temporarily Changing the Compiler 1 16 Contents Verifying mbuild 2 0 6 eee 1 16 Locating Shared Libraries 0 0 eee eee 1 17 Running Your Application 000 eee ee eee 1 18 mbuild Options eis e aa EEE EE a Np B aa na E aaa 1 18 Distributing Stand Alone UNIX Applications 1 21 Building a Stand Alone Application on Microsoft WINGOWS 2 ee isc ie ite do
208. ormation is provided for those users who require more flexibility with the tool Building a Stand Alone Application on UN IX The mbui d syntax and options are mbuild options filenamel filename2 Table 1 2 mbuild Options on UNIX Option Description C D lt name gt lt def gt f lt optionsfile gt h elp lt pathname gt lt file gt L lt pathname gt lang lt language gt link lt target gt Compile only do not link Define C preprocessor macro lt name gt as having value lt def gt Use lt f il e gt to override the default options file lt file gt isa full pathname if it is not in the current directory Build an executable with debugging symbols included Help prints a description of mbui d and the list of options Include lt pat hname gt in the list of directories to search for header files Link against library i b lt file gt Include lt pat hname gt in the list of directories to search for libraries Override language choice implied by file extension lt language gt c forC cpp for C This option is necessary when you use an unsupported file extension or when you pass all o files and libraries Specify output type lt target gt exe for an executable default shared for shared library See Building Shared Libraries on page 1 33 for an example 1 19 1 G etting Ready Table 1 2 mbuild Opti
209. ou cannot for example write N 2 2 1 which attempts to add onetoa cell However N 2 2 1 works perfectly well 5 45 5 Indexing into Arrays 5 46 since the cell array indexing returns the contents of cell 2 2 rather than the cell itself e Cell array indexing follows thesamerules as standard indexing You can use the colon index to refer to multiple rows or columns you can use vector and matrix indices to extract sub cell arrays from a cell array etc For simplicity this documentation focuses on two dimensional cell arrays If N were a cell array of higher dimension the examples would still work on N if you added the appropriate number of dimensions to the indexing expressions Referencing a Cell in a Cell Array To obtain a cell from a cell array use parentheses in the indexing string to indicate that you are referencing the cell itself not its contents ml fAssign amp c mlflndexRef N mlfScalar 1 ml fScalar 2 c is a 1 by 1 cell array containing the string array Eric c N 1 2 performs the same operation in MATLAB Referencing a Subset of a Cell Array To obtain a subset of the cells in a cell array use the colon index or a vector or matrix index to access a group of cells For example to extract the second row of the cell array N write this code m fAssign amp B miflndexRef N mfScalar 2 mi f CreateCol onl ndex The result B is a 1 by 2 cell array containing
210. output One input one output U 14 2691 0 6268 One input three outputs U 0 1525 0 8226 0 3945 0 3800 0 3499 0 4214 0 2428 0 8007 0 5474 0 0201 0 6979 0 4614 0 7448 0 3812 0 5462 0 0407 S 14 2691 0 0 0 6268 0 0 0 0 V 0 6414 0 7672 0 7672 0 6414 Two inputs three outputs U 0 1525 0 8226 0 3499 0 4214 0 5474 0 0201 0 7448 0 3812 5 2 14 2691 0 0 0 6268 V 0 6414 0 7672 0 7672 0 6414 6 18 How to Call O perators How to Call Operators Every operator in MATLAB is mapped directly to a function in the MATLAB C Math Library Invoking MATLAB operators in C is simply a matter of determining the name of thefunction that corresponds tothe operator and then calling the function as explained above The section Operators and Special Functions on page 9 5 lists the MATLAB operators and the corresponding MATLAB C Math Library functions 6 19 6 Calling Library Routines Passing Functions As Arguments to Library Routines The MATLAB C Math Library includes function functions functions that execute a function that you provide For example the library function ml f Ode23 isa function function Other function functions include mfFzeros mfFmin mfFmins mfFunm andtheother ml f Ode functions In this section you ll learn e How the function functions use ml f Feval e HownlfFeval works e How to extend ml f Feval by writing a thunk function How Function
211. oyArray mat 0 mxDestroyArray mat 1 Disable automated memory management ml fRestorePreviousContext 0 0 return EXIT SUCCESS 3 16 W orking with MATLAB N umeric Arrays N otes 1 Include mat ab h This file contains the declaration of the mx Array data structure and the prototypes for all the functions in the library st dl ib h contains the definition of EXI T_ SUCCESS 2 Declare two static arrays of real numbers that are subsequently used to initialize matrices The data in the arrays is interpreted by the MATLAB C Math Library in column major order The first array real _ data stores the data for thereal part of both matrices and the second c pI x_ data stores the imaginary part of mat 1 3 Create two full matrices with ml f Doubl eMatrix mlfDoubl eMatri x takes four arguments the number of rows the number of columns a pointer to a standard C array of data to initialize the real part of the array anda pointer to a C array of data to initialize the imaginary part if present ml f Doubl eMatrix allocates an mx Array structure and storage space for the elements of the matrix initializing each entry in the matrix to the values specified in the initialization arrays The first matrix mat 0 does not have an imaginary part The second matrix mat 1 has an imaginary part mat 0 has two rows and three columns and mat 1 has three rows and two columns 4 Print the matrices mi f Print Matrix ca
212. ple C 4 produces the result ans 0 If you specify two subscripts i j indicating row column indices MATLAB calculates the offset as described above Two subscripts always access the first page of a multidimensional array provided they are within the range of the original array dimensions If more than one subscript is present all subscripts must conform to the original array dimensions F or example C 6 2 is invalid because all pages of C have only five rows If you specify more than two subscripts MATLAB extends its indexing scheme accordingly For example consider four subscripts i j k intoa four dimensional array with size d1 d2 d3 d4 MATLAB calculates the offset into the storage column by 1 1 d3 d2 d1 k 1 d2 d1 j 1 01 1 For example if you index the array C using subscripts 3 4 2 1 MATLAB returns the value 5 index 38 in the storage column In general the offset formula for an array with dimensions d d2 d3 dpl using any subscripts s4 5S2 53 Spn is Sn 1 dn 1 dn 2 d1 HSn 1 1 dn 2 d1 HS2 1 d1 51 Becauseof this scheme you can index an array using any number of subscripts You can append any number of 1s to the subscript list because these terms become zero For example C 3 2 1 1 1 1 1 1 is equivalent toC 3 2 5 9 5 Indexing into Arrays How to Call the Indexing Functions Using the three indexing functions ml fI ndexRef ml fl ndexAssign
213. ptional The word optional means that the input argument is optional to the working of the function however some value must always appear in that argument s position in the parameter list Therefore if you do not want to pass the second argument you must pass NULL in its place The two ways to call the MATLAB C Math library version of tri are ml fAssign amp L mlfTril X NULL and m fAssign amp lL mfTril X k whereL X andk are pointers tomxArray structures L must be initialized to NULL before being passed to the ml f Assi gn routine Passing Optional Output Arguments MATLAB functions may also have optional or multiple output arguments F or example you invokethef i nd function which locates nonzero entries in arrays with one two or three output arguments k find X i j find X i j v find X How to Call MATLAB Functions In interpreted MATLAB fi nd returns one two or three values In C a function cannot return more than one value Therefore the additional arrays must be passed tofi nd in the argument list They are passed as pointers to mxArray pointers mxArray variables Output arguments always appear before input arguments in the parameter list In order to accommodate all the combinations of output arguments the MATLAB C Math Library ml f Fi nd function takes three arguments the first two of which are mxArray parameters corresponding to output values Using the MATLAB C Ma
214. r a cell array indexing expression all in the argument positions See Indexing into Cell Arrays on page 5 44 tolearn more about indexing into cell arrays Exception for Built In Library Functions For built in MATLAB C Math Library functions that arevar ar gi n functions for example ml f Cat ml f Rand and ml f Ones consider the explicit argument that immediately precedes the as part of thevarargin arguments This argument can accept an indexed cell array expression 6 33 6 Calling Library Routines For example in this code the embedded call tom f ndexRef isin the position of the explicit argument that precedes the in the signature of the built in function ml f Cat In MATLAB F 1 pascal 3 F 2 magic 3 F 3 ones 3 F 4 magic 3 G cat 2 F si mxArray F NULL G NULL m flndexAssign amp F m fScalar 1 ml f Pascal ml fScalar 3 NULL m flndexAssign amp F mlfScalar 2 ml f Magi c mlfScalar 3 ml flndexAssign amp F mfScalar 3 mi f Ones ml fScalar 3 NULL mi flndexAssign amp F mlfScalar 4 ml f Magic ml fScalar 3 ml fAssign amp G mfCat mfScalar 2 mi fI ndexRef F ml fCreateColonlndex NULL 6 34 Importing and Exporting Array Data Overview aaa aa a a 7 2 Using mlfSave to Write Data toa File 7 2 Using mifLoad to Read
215. rHandler 8 8 9 21 m fSetLibraryAllocFcens 4 35 ml fSetPrintHandler 8 15 9 23 calling first 8 15 ml fSvd 6 14 ml fTobool 7 7 ml fVarargoutList constructing 6 10 ml fVertcat 5 16 creating arrays 5 16 number of arguments 5 25 Motif MessageDi al og widget 8 15 print handler 8 15 multidimensional array functions 9 19 9 42 multidimensional arrays concatenating 3 10 creating 3 6 of characters 3 27 mxArray array access routines 9 46 as input and output arguments 1 3 creating 3 3 deleting elements from 5 42 indexing with ml f CreateCol onl ndex 5 5 5 18 5 23 5 27 initialization of pointers to 4 8 paradigm for using as local variables 4 8 pointer to data in 3 12 reading from disk 7 3 7 6 saving to disk 7 2 7 6 string 6 20 6 24 mxCreateDoubl eMatrix 3 17 mxCreateString 6 28 mxCreateString 3 26 mxDestroyArray 42 4 10 4 12 4 13 4 22 in example 4 25 4 28 4 29 4 30 noreinitialization of pointer 4 12 passing NULL to 4 12 under automated memory management 4 7 4 8 under explicit memory management 4 4 4 5 mxMalloc 4 35 N naming conventions array access routines 9 46 math functions 1 3 N dimensional indexing 5 23 5 29 5 35 5 45 selecting a matrix of elements 5 27 selecting a single element 5 24 selecting a vector of elements 5 24 nesting calls to functions 4 8 4 11 4 27 nonzero elements Index determining number of 3 23 NULL initializing output arguments to 4 22 4 29 passin
216. raa Mar eesti a a E A 3 lt matlab gt extern lib ARCH 0 0 cece eee eens A 4 lt matlab gt extern include 0 ccc eens A 5 lt matlab gt extern examples cmath 0 00 020 eee eee A 5 Directory Organization on Microsoft Windows A 7 lt Matlab gt DIN seesi ee oemi eee eens A 7 lt matlab gt extern include 0 0 cece eens A 8 lt matlab gt extern examples cmath 0020 eee A 9 xii Contents Errors and Warnings Errors Warnings Getting Ready Introduction 3 Who Should Read This Book Mis eh te i New MATLAB C Math Library Features Library Routine Naming Convention MATLAB C Math Library Documentation MATLAB C Math Library 1 2 Users Installing the MATLAB C Math Peer Installation with MATLAB Installation Without MATLAB Verifying a UNIX Workstation Installation Verifying a PC Installation mes Building C acai Overview Building a Stand Alone Fin on UNIX Configuring for C or C PAR ets cs Verifying mbuild mbuild Options Distributing Stand Alone U N x Applications Building a Stand Alone Application on Microsoft Windows i Configuring for C or C Verifying mbuild mbuild Options Distributing Stand Alone M icrosoft Windows Applications Building Shared Libraries Troubleshooting mbuild Building on Your Own 1 2 1 2 1 3 1 3 1 6 1 9 1 9 1 9 1 10 1 10 1 11 1 11
217. rary does The syntax used with the macros is different than the C keywords The library error handling mechanism is built on thes et j mp ongj mp mechanism For more information about s et j mp ongj mp see your system documentation Example Program Defining Try Catch Blocks ex6 c The following example adds try and catch blocks to the example program introduced in the previous section page 8 4 Handling Errors You can find the code for this example in the lt matl ab gt extern examples cmath directory on UNIX systems or the lt matl ab gt extern examples cmath directory on PCs where lt mat ab gt represents the top level directory of your installation See Building C Applications in Chapter 1 for information on building the examples include lt stdio h gt include lt stdlib h gt Used for EXIT SUCCESS include lt string h gt include matlab h static double data 1 4 2 5 3 6 mai n mxArray matQ NULL mxArray matl NULL mxArray volatile mat2 NULL mi fEnterNewContext 0 0 m fAssign amp mat0 mi fDoubleMatrix 2 3 data NULL m fAssign amp matl ml fDoubleMatrix 3 2 data NULL ml fTry ml fAssign amp mat2 ml fRdivide matl mlfScalar 0 mfPrintf Return to try block after warning n mifPrintMatrix mlfPlus mat0 mat1 ml f Catch m fPrintf In catch block Caught an error mfPrintMatrix mlfLasterr NU
218. rary is available on UNIX workstations and PCs running Microsoft Windows Windows 95 Windows 98 and Windows NT The installation process is different for each platform Note that the MATLAB C Math Library runs on only those platforms processor and operating system combinations on which MATLAB runs In particular the Math Libraries do not run on DSP or other embedded systems boards even if those boards are controlled by a processor that is part of a system on which MATLAB runs Installation with MATLAB If you area licensed user of MATLAB there are no special requirements for installing the MATLAB C Math Library Follow the instructions in the MATLAB Installation Guide for your specific platform e Installation Guide for UNIX e Installation Guide for PC Choose the MATLAB C C Math Library selection from list of components that you can install displayed by the installation program Before you begin installing the MATLAB C Math Library you must obtain from The MathWorks a valid License F ile for concurrent licenses on UNIX systems or PCs or Personal License Password individual license PC users These are usually supplied by fax or e mail If you have not already received a License File or Personal License Password contact The MathWorks via e The Web at www mat hworks com On the MathWorks site click on the MATLAB Access option log in to the Access home page and follow the instructions MATLAB Access membership is free of
219. rate a Givens plane rotation ml fQrdelete Delete a column from a QR factorization mi f Qrinsert Insert a column into a QR factorization 3 fRsf2csf Real block diagonal form to complex diagonal form 9 32 MATLAB M File M ath Library Data Analysis and Fourier Transform Functions Basic Operations Function Purpose ml f Cumtrapz Cumulative trapezoidal numerical integration ml f Mean Average or mean value ml f Medi an Median value ml fSortrows Sort rows in ascending order ml f Std Standard deviation ml fTrapz Numerical integration using trapezoidal method Finite Differences Function Purpose ml f Del 2 Five point discrete Laplacian ml f Di f f Difference function and approximate derivative ml f Gradient Approximate gradient see online help Correlation Function Purpose ml f Corrcoef Correlation coefficients ml f Cov Covariance matrix ml f Subspace Angle between two subspaces 9 33 9 Library Routines Filtering and Convolution Function Purpose ml f Conv ml f Conv2 ml f Deconv mfFilter2 Convolution and polynomial multiplication Two dimensional convolution see online help Deconvolution and polynomial division Two dimensional digital filter see online help Fourier Transforms Function Purpose ml fF Ft 2 ml fFftshift ml fl ff t ml fl fft2 mflfftn Two dimensional discrete Fourier transform Shift DC
220. re Remove a field from each structure mi f Rmfi el d in an array of structures 3 37 3 W orking with MATLAB Arrays 3 38 Creating Structures The MATLAB C Math Library allows you to create structures by e Using a structure creation routine e Using a structure conversion routine e Assigning a value to an element in a structure Using a Structure Creation Routine You can createa structureusingtheml f St ruct routine This routinelets you define the fields in the structure and assign a value to each field For example the following code fragment creates a structure that contains two fields a text string and a scalar value mxArray A NULL m fAssign amp A mf Struct mxCreateString name Field mxCreateString J ohn Value mxCreateString number Field m fScalar 3ll Value NULL mi f Print Matrix A ml fDestroyArray A This code produces the following output name John number 311 Because theml f St ruct routine can accept a varying number of input arguments you must terminate the argument list with aNULL Creating Multidimensional Arrays of Structures Theml fstruct routine defines the fields and values in a single instance of a structure in effect a 1 by 1 structure array To create a multidimensional array of structures use MATLAB indexing to assign a value toa field in a structure with an index other than 1 1 MATLAB will extend the array
221. realloc_fcn malloc _proc malloc_fcn Set the MATLAB C Math Library s memory management functions Gives you complete control over memory management Printing Function Purpose int Format output just likeprintf Use mifPrintf const char fmt the installed print handler to display the output The MATLAB Builtln Library Printing Continued Function Purpose void mi f PrintMatrix mxArray m void mifSetPrintHandler void PH const char Print contents of matrix Specify pointer to external application s output function Scalar Array Creation Function Purpose mxArray mifScalar double v mxArray ml f Compl exScalar double v double i Create a 1 by 1 array whose contents are initialized to the value of v Create a complex 1 by 1 array whose contents are initialized to the real part v and the imaginary parti 9 23 9 Library Routines MATLAB M File Math Library The MATLAB M File Math Library contains callable versions of the M files in MATLAB For example MATLAB implements the functionr ank in an M file namedrank m The C callable version of rank is called ml f Rank Note You can recognize routines in the Built In and M File Libraries by the ml f prefix at the beginning of each function Operators and Special Functions Arithmetic Operator Functions Function Purpose ml f Kron Kronecker tensor product Logic
222. reates the MessageDi al og object that is used by the print handling routine Finally mai n calls ml f Set Print Handl er toinform the library that it should use PopupMessageBox instead of the default print handler If this were a complete application the main routine would also contain calls to other routines or code to perform computations Microsoft Windows Example This example uses the Microsoft Windows MessageBox dialog box This dialog box contains an information icon the message text and a single OK button The MessageBox is a Windows modal dialog box while it is posted your application will not accept other input You must press the OK button to dismiss the MessageBox dialog box before you can do anything else This example declares two functions The first PopupMessageBox is responsible for placing the message into the MessageBox and then posting the box to the screen The second mai n which in addition to creating and starting the Microsoft Windows application that code is not shown calls ml f Set PrintHandl er toset the print handling routinetoPopupMessageBox 8 17 8 Handling Errors and W riting a Print Handler Microsoft Windows example static HWND window static LPCSTR title Message from MATLAB The alternate print handler void PopupMessageBox const char message MessageBox window LPCTSTR message MB_ CONI NFORMATI ON mai n Register window class provide wi
223. result 4 6 1 7 3 9 Note An N dimensional subscript used in a deletion operation on the left side of the assignment statement can contain only one scalar vector or matrix index The other indices must be colon indices For example if an array is three dimensional and you delete row 2 you must delete row 2 from all pages Similar to reference and assignment two dimensional deletion extends to N dimensions If A has more than two dimensions simply specify more than two dimensions in the index string and pass more than two index values 5 43 5 Indexing into Arrays Indexing into Cell Arrays This section describes how to e Reference a cell in a cell array e Reference a subset of a cell array e Reference the contents of a cell e Reference a subset of the contents of a cell e Index nested cell arrays e Assign values to a cell array e Delete elements from a cell array The examples all use the cell array N N contains four cells a 2 by 2 double array a string array an array that contains a complex number and a scalar array cell 1 1 cell 1 2 1 2 Eric 45 cell 2 1 cell 2 2 2 4i 7 This MATLAB code creates the array N 1 1 1 2 4 5 N 1 2 Eric N 2 1 2 41 N 2 2 7 5 44 Indexing into Cell Arrays This MATLAB C Math Library code creates the array Note that dbl array must already exist ml fAssign amp N mfVertcat mlfCellhcat dbl
224. resulting array equals the number of non NULL arguments passed to the routine To illustrate the following example passes three arguments to ml f Ones to create a three dimensional array Because these routines allow you to create arrays of any number of dimensions you must signify the end of the argument list by specifying a NULL mxArray A NULL ml fAssign amp A mifOnes milf Scalar 2 mi f Scalar 3 mi fScalar 2 NULL ml f Print Matrix A mxDestroyArray A This code fragment creates the following array 1 1 1 1 1 1 1 itd a2 1 1 1 1 1 1 Creating Vectors of Number Sequences To create a one dimensional array vector that contains a number sequence use the ml f Col on routine This routine performs the same function as the MATLAB colon operator 3 8 W orking with MATLAB N umeric Arrays For example the following code fragment creates a vector of all the numbers between 1 and 10 mxArray A NULL mi fAssign amp A mifColon mfScalar 1 mfScalar 10 NULL mi f Print Matrix A mxDestroyArray A This code creates the following output 1234567 8 9 10 You can optionally specify an increment between the values in the vector F or more information see the ml f Col on reference pagein the MATLAB C Math Library Reference online documentation Creating Numeric Arrays by Calling Arithmetic Routines The MATLAB C Math Library arithmetic routines create numeric arrays as
225. riables from the file ex5 mat Note that the function ml f Load does not follow the standard C Math Library calling convention where output arguments precede input arguments The output arguments a b andc are interspersed with the input arguments Pass arguments in this order the array containing the filename then the name variable pairs themselves and finally aNULL to terminate the argument list An important difference between the syntax of ml f Load andml f Save isthetypeof the variable portion of each pair Because you re loading data intoa variable ml f Load needs the address of the variable amp a amp b amp c a b andc areoutput arguments whereasx y andz intheml f Save call were input arguments Notice how the name of the output argument does not have to match the name of the variable in the MAT file Overview Note mi fLload isnot atypesafe function It is declared as ml fLoad mxArray file Thecompiler will not complain if you forget to include an amp in front of the output arguments H owever your application will fail at runtime 6 Compare the data loaded from the file to the original data that was written tothe file a b andc contain the loaded data x y andz contain the original data Each call tomi f sEqual returns a temporary scalar mx Array containing TRUE if the compared arrays are the same type and size with identical contents ml f Tobool returns the Boolean value contained
226. ring function arguments to previous con text 4 18 as return values 4 20 4 28 returned by arithmetic routines 3 9 rules for using 4 8 scalar 3 5 sparse matrices 3 18 string 6 20 6 24 6 28 temporary 4 6 4 28 4 30 two dimensional 3 5 assigning values to arrays array already has a value 4 10 under automated memory management 4 8 4 9 under explicit memory management 4 5 assignment and indexing 5 36 creating cell arrays 3 34 creating structures 3 40 assignment by value 4 11 assignment operator Seeml f Assi gn automated memory management 4 2 4 3 4 18 4 20 4 22 B base number conversion 9 39 basic array information functions 9 10 9 25 binary file I O 9 18 blank character used as padding 3 27 bound arrays 4 6 4 14 4 21 4 27 4 30 behavior of 4 7 build script location Microsoft Windows A 8 UNIX A 3 building applications on Microsoft Windows 1 22 on UNIX 1 13 other methods 1 36 troubleshooting mb ui d 1 34 ANSI compiler 1 2 array and initialization of MATLAB array 3 14 function calling conventions 6 2 indexing 5 57 subscripts 5 57 calling conventions 6 2 8 9 mapping rules 6 13 overview 6 2 summary 6 13 Index calling library functions 6 3 calling operators 6 19 cell array functions 9 19 9 42 cell array indexing nested cell arrays 5 47 referencing a cell 5 46 referencing the contents of a cell 5 47 cell arrays concatenating 3 32 converting numeric arrays 3 31 converting to structure
227. rintMatrix common factors end m fTry O mi f Catch mifPrintf In catch block n mf PrintMatrix mlfLasterr NULL m fEndCatch end catch block Free any arrays that were allocated mxDestroyArray can handle NULL pointers 0 mxDestroyArray factorsl mxDestroyArray factors2 mxDestroyArray common factors O ml fRestorePreviousContext 0 0 return EXIT SUCCESS Notes 1 Include mat ab h This file contains the declaration of the mxArray data structure and the prototypes for all the functions in the library st dl ib h contains the definition of EXIT SUCCESS 2 Declare pointers to three MATLAB arrays mxArray All arguments to MATLAB routines must be MATLAB arrays In addition the routines return newly allocated MATLAB arrays as output These pointers are declared as volatile pointers because they are assigned values within a try block and so may change without warning due to an error For more 2 4 Overview information about working with MATLAB arrays in C programs see Chapter 3 3 Enable MATLAB C Math Library automated memory management by calling mi f EnterNewContext With the library memory management facility enabled the library can delete the arrays it creates automatically This allows you to compose functions that is nest one function call within another For more information about automated memory management see Chapter 4 4 Solicit input fromthe
228. rom the MATLAB C Math Built In Library DLL Contains names of functions exported from the MATLAB M File Math Library DLL Contains names of functions exported from i bmx dll lt matiab gt extern examples cmath The lt mat lab gt extern exampl es cmath directory contains sample C programs developed with the MATLAB C Math Library You ll find explanations for these examples throughout the book intro c exl c ex2 ex3 c ex4 c ex5 ex6 c release txt The source code for A Simple Example Program on page 2 2 The source code for Example Program Creating Numeric Arrays exl1 c on page 3 15 The source code for Example Program Managing Array Memory ex2 c on page 4 24 The source code for Example Program Calling Library Routines ex3 c on page 6 14 The source code for Example Program Passing Functions As Arguments ex4 c on page 6 22 The source code for Example Program Saving and Loading Data ex5 c on page 7 4 The source code for Example Program Defining Try Catch Blocks ex6 c on page 8 6 Release notes for the current release of the MATLAB C Math Library A 9 A Directory Organization A 10 Errors and Warnings EMrOrs oeu 26055 6 AE oe ee Se Ee A ee ek s B 3 Warnings 8 eee ee B 8 B Errors and W arnings B 2 This section lists the a subset of the error and warning messages issued by the MATLA
229. rpose ml fCondest 1 norm condition number estimate ml f Ei gs A few eigenvalues ml f Nor mest Estimate the matrix 2 norm ml f Svds A few singular values Linear Equations iterative methods Function Purpose ml f Bi cg BiConjugate Gradients Method ml f Bicgstab BiConjugate Gradients Stabilized Method ml f Cgs Conjugate Gradients Squared Method ml f Gmr es Generalized Minimum Residual Method ml f Pcg Preconditioned Conjugate Gradients Method ml f Qmr Quasi Minimal Residual Method MATLAB M File M ath Library Miscellaneous Function Purpose ml fSpaugment ml f Sppar ms ml fSymbf act Form least squares augmented system Set parameters for sparse matrix routines Symbolic factorization analysis 9 45 9 Library Routines 9 46 Array Access and Creation Library The Array Access and Creation Library contains the array access routines for the mx Array data type For example mxCreateDoubl eMatrix creates an mx Array mxDestroyArray destroys one Refer to the online Application Program Interface Reference and the MATLAB Application Program Interface Guidefor a detailed definition of each function Note You can recognize an Array Access and Creation Library routine by its prefix mx The functions listed are a subset of the Array Access and Creation Library Array Access Routines Function Purpose mxCalloc mxFree mxCl earLlogical mxCreate
230. s The following code prints the 2 by 2 array A created in the previous section to the display mxArray A NULL ml f Assign amp A mfOnes mfScalar 2 m fScalar 2 NULL mifFprintf mlfScalar 1 stdout mxCreateString Array A d n format string A NULL array This code produces the following output illustrating how ml f Fprintf applies the format to each element in an array array A array A array A array A PPE Determining Array Type The MATLAB C Math Library includes several routines that allow you to determine thetype of an array Each routine tests for a particular type of array and returns 1 if the array being tested matches the indicated type and 0 zero otherwise Table 3 6 Array Type Routines Array Type Routine Numeric array ml fl snumeric Character array ml fl schar Sparse array ml fl ssparse Cell array ml flscell Cell array of strings mflscellstr Structure ml flsstruct 3 43 3 W orking with MATLAB Arrays 3 44 Asan example the following code uses the ml f snumeric routine totest if a 2 by 2 array of ones is a numeric array mxArray A NULL mxArray B NULL Create two dimensional array m fAssign amp A mfOnes mfScalar 2 mlfScalar 2 NULL Determine if array is numeric ml fAssign amp B miflsnumeric A mfFprintf ml fScalar 1 stdout mxCreateString Isnumeric retur
231. s and deleting arrays You will use the library functions ml f Assi gn for assignment and mxDestroyArray for deletion e Shows you how to enable automated memory management in each function that you write The functions that you write follow the pattern of this template code In this code memory management routines are highlighted by grey boxes mxArray FunctionName mxArray output_argl mxArray input_argl mxArray input_arg2 mxArray local_return_value NULL mxArray local_ varl NULL mxArray local_var2 NULL ml fEnterNewContext 1 2 output_argl input_argl input_arg2 Perform the work of the function ngs gta 8 Note Don t destroy local_return_ value mxDestroyArray local_varl mxDestroyArray local_var2 mi f RestorePreviousContext 1 2 output_argl input_argl input_arg2 return mi fReturnValue local_ return_value 4 2 Overview Any main function that you write follows the pattern of this template code int main Initialize variables mi f Enter NewContext 0 0 Perform the work of main mi f RestorePreviousContext 0 0 return EXIT_ SUCCESS Note Besuretolook over the example program later in this chapter To use automated memory management you must follow explicit guidelines for each function that you write Why Choose Automated Memory Management The MATLAB C Math Library provides two ways for you to manage array memory e Autom
232. s 3 39 creating 3 30 creating by assignment 3 34 displaying contents of 3 34 using ml f Cell 3 31 character arrays accessing elements 3 29 creating 3 25 from numeric arrays 3 27 multidimensional 3 27 using mxCreateString 3 26 character string functions base number conversion 9 39 general 9 16 9 38 string operations 9 16 9 38 string tests 9 16 string to number conversion 9 17 9 39 closing files 9 17 coding to automated memory management inter face 4 14 4 22 coding to explicit memory management interface 4 31 column vector indexing as 5 6 column major order 3 17 MATLAB array storage 3 14 vs row major order 3 14 compatibility between explicit and automated memory management 4 33 compiler changing default on PC 1 24 changing default on UNIX 1 14 choosing on UNIX 1 14 complex functions 9 12 9 28 complex scalar arrays 9 23 compopts bat 1 23 concatenation creating arrays 3 9 creating cell arrays 3 32 creating multidimensional arrays 3 10 constants special 9 10 contexts for array memory management 4 16 4 18 conventions array access routine names 9 46 calling 6 2 math functions 1 3 conversion base number 9 39 string to number 9 17 9 39 coordinate system transforms 9 30 correlation 9 33 creating arrays 5 16 complex scalars 9 23 logical indices 5 31 ctranspose use instead of 9 7 D data in arrays 3 12 reading with ml f Load 7 6 Index writing with ml f Save 7 6 data analysis and Fourier tra
233. s by e Using a cell array creation function e Using a cell array conversion function e Concatenating existing arrays e Assigning a value to an element in a cell array W orking with MATLAB Cell Arrays Using the Cell Array Creation Routine You can create an array of empty cells using the ml f Cel routine The following code fragment creates a 2 by 3 by 2 array of empty cells mxArray A NULL mi fAssign amp A mifCell mlfScalar 2 ml f Scalar 3 mi fScalar 2 NULL mi f Print Matrix A mxDestroyArray A This code produces the following output ee ely 2S NR iT MATLAB uses brackets to indicate cell array elements and represents an empty cell You can then assign values to cells in the array using assignment For an example of assigning a value to a cell in a cell array see Using Assignment to Create Cell Arrays on page 3 34 Using Cell Array Conversion Routines You can also create cell arrays by converting other MATLAB arrays into cell arrays The MATLAB C Math Library includes routines that convert a numeric array into a cell array ml f Num2cel or a structure into a cell array ml f Struct2cell 3 31 3 W orking with MATLAB Arrays 3 32 The following code fragment creates a numeric array using ml f Ones and converts it into a cell array using the ml f Num2cel 1 routine mxArray N NULL mxArray C NULL Create a numeric array m
234. s in a character array 3 Display a character string fDisp ml fPrintMatrix Convert a number to its string ml f Num2Str representation specifying format Convert an array of integers intoa ml filnt2str string array Convert character string toa ml f Str2num numeric array Creating MATLAB Character Arrays Wherever you pass a character string toa MATLAB C Math Library routine the string must be a MATLAB character string array not a standard C null terminated character string MATLAB represents characters in 16 bit Unicode format Using Explicit Character Array Creation Routines The easiest way to create a MATLAB character string is with the MATLAB API routine mx Creat eString You pass this routine a standard C character string as an argument delimited by double quotation marks In the MATLAB interpreted environment strings are delimited by single quotation marks mxArray A NULL ml fAssign amp A mxCreateString my string ml f Print Matrix A mxDestroyArray A This code produces the following output my string W orking with MATLAB Character Arrays Converting Numeric Arrays to Character Arrays To convert a numeric array into a character array usetheml f Char routine The following code creates an array containing the ASCII codes for each character in my string and then call ml f Char to convert this numeric array intoa MATLAB character array mxArray i static dou
235. s required by or enz an array of mx Array s hs that stores the results from or enz an integer nrhs that indicates the number of input arguments required by or enz andan array of mxArray S rhs that stores theinput values Thel hs left hand side 6 25 6 Calling Library Routines 6 26 and rhs right hand side notation refers to the output arguments that appear on the left hand side of a MATLAB function call and the input arguments that appear on the right hand side Definethetype for thel or enz function pointer The pointer tol or enz comes into the thunk function with the type ml f Funcp a generalized type that applies to any function ml f Funcp is defined as follows typedef void mlfFuncp void The function pointer type that you define here must precisely specify the return type and argument types required by or enz The program casts pFunc tothe type you specify here ThenamePFCN_1_2 makes it easy toidentify that the function has 1 output argument the return and 2 input arguments U sea similar naming scheme when you write other thunk functions that require different numbers of arguments For example usePFCN_2_ 3 to identify a function that has two output arguments and three input arguments Verify that the expected number of input and output arguments have been passed or enz expects twoinput arguments and one output argument The return value counts as one output argument Exit the thunk
236. s the type of array stored in each cell but it does not display the contents of the cell except for string arrays and scalar values To view the contents of each cell you must use the ml f Cel I di sp routine 3 34 W orking with MATLAB Cell Arrays The ml f Cel disp routine supports a second optional argument which specifies the text string used to identify each cell in the output In the example the character D is passed toml f Cel disp as its second argument This appears in the output in the line that prefixes each cell such as D 1 If you do not specify this second argument ml f Cel disp uses the text string ans as in ans 1 The following code fragment creates a cell array and prints out the cell array using both mi f Print Matrix andmifCelldisp mxArray A NULL mxArray B NULL mxArray C NULL mxArray D NULL static double 3 fAssign amp A fAssign amp B ml f Assi gn amp C 3 ml f Assi gn amp D f Print Matrix f Print Matrix 3 33 f Print Matrix fCelldisp 0D 3 3 mxDestroyArray mxDestroyArray mxDestroyArray mxDestroyArray data 1 4 2 5 3 6 mi f Colon ml fScalar 1 ml fScalar 10 NULL mxCreateString my string n mi f Doubl eMatrix 2 3 data NULL mi f Cell hcat A B C NULL mxCreateString The mf PrintMatrix output D mxCreateString The mfCelldisp output mxCreateStr
237. sing functions as arguments 6 20 print handling Microsoft Windows 8 17 X Window system 8 15 saving and loading data 7 4 Index source code location UNIX A 5 A 9 template for managing array memory 4 15 templates for managing array memory 4 14 4 16 using explicit memory management 4 31 writing a function 4 24 examples creating arrays 3 15 exl c 3 15 explicit memory management 4 4 4 31 exponential functions 9 12 9 28 expression function call 6 2 F factorization utilities 9 14 9 32 file 1 O functions binary 9 18 file positioning 9 17 9 40 formatted I O 9 17 9 40 import and export 9 18 opening and closing 9 17 string conversion 9 18 file opening and closing 9 17 files binary file I O 9 18 formatted I O 9 17 9 40 import and export functions 9 18 positioning 9 17 9 40 string conversion 9 18 filtering and convolution 9 15 9 34 finite differences 9 33 formatted I O 9 17 9 40 Fourier transforms 9 15 9 34 free 4 35 freeing array memory 4 11 full to sparse conversion 9 20 9 43 function calling conventions 6 2 8 9 integrating 6 20 naming conventions 1 3 passing as argument 6 20 return values multiple 6 14 function functions 6 20 how they are called 6 20 ml fFmin 6 20 ml f Fmins 6 20 ml fFunm 6 20 ml fFzeros 6 20 ml f Ode functions 6 20 passing function name 6 30 function functions and ODE solvers numerical integration 9 37 ODE option handling 9 38 ODE solvers 9 37 optimization and root finding
238. sion by zero sincex y 1 x y and0 n 0 Non IEEE machines cannot represent infinity so division by zero is an error on those machines mostly DEC VAXes B 7 B Errors and W arnings Warnings All warnings begin with the string War ning By default programs written using t he library output a message after a warning level event has occurred and then continue processing For most warning messages there is a corresponding error message Generally warning messages are issued in place of errors on EEE floating point compliant machines when an arithmetic expression results in plus or minus infinity or a nonrepresentable number Where this is the case the error message explanation has not been reproduced See the section Errors for an explanation of these messages Warning Divide by zero Warning Log of zero Warn be i Warn Warn Warn ing Matrix is close to singular or badly scaled Results may naccurate ing Matrix is singular to working precision ing Singularity in ATAN ing Singularity in TAN Symbols 9 5 amp 9 6 9 5 9 5 9 5 9 5 9 5 9 5 9 7 1 9 5 9 7 lt 9 6 lt 9 6 Seeml f Assi gn 9 6 gt 9 6 gt 9 6 9 5 9 5 9 6 9 6 9 6 9 7 A Access members 1 10 allocation of memory for arrays 4 2 ANSI C compiler 1 2 arguments optional 6 4 6 5 example 6 14 order of 6 13 to a thunk funcion 6 25 arithmetic operator functions 9 5
239. ssign amp B myFunc mf Si n X Specifically ml fEnterNewContext mlfRestorePrevi ousContext and ml fReturnVal ue along with mi f Assi gn described in Assigning Arrays to mxArray Variables on page 4 9 manipulate the temporary and bound state of an array in order to e Preserve bound array input arguments across the call to your function e Delete any temporary array that is passed as an array input argument to your function just before your function returns e Return a temporary array from your function Using a Function Template As an Example You can usethetemplate code below as the basis for writing functions that use the library s automated memory management Internally all MATLAB C Math Library functions call the functions highlighted in the template by grey boxes Your functions must do the same You can find the general function template and a mai n routine template in lt matlab gt extern examples cmath mem_mgt_func_template c and 4 14 W riting Functions Under Automated Memory Management mem_mgt_main_template c respectively where lt mat ab gt represents the top level directory of your installation See Using Arrays Under Automated Memory Management on page 4 6 for information that applies to the sections of the templatethat aren t highlighted Function Template As an example this template function takes one array output argument two array input arguments and returns an array Your fu
240. struct an ml f VarargoutList by passing any number of array arguments to the function ml f Var argout or any mix of indexed and non indexed array arguments to ml fl ndexVarargout How to Call MATLAB Functions Summary of Library Calling Conventions Though this section has focused on just a few functions the principles presented apply to the majority of the functions in the MATLAB C Math Library In general a MATLAB C Math Library function call consists of a function name a set of input arguments and a set of output arguments In addition to being classified as input or output each argument is either required or optional Thetype of an argument determines where it appears in the function argument list All output arguments appear before any input argument Within that division all required arguments appear before any optional arguments The order therefore is required outputs optional outputs varargout or ml f VarargoutList output avarargout output list required inputs optional inputs and variable length inputs var ar gi n arguments Tomap a MATLAB function call toa MATLAB C Math Library function call follow these steps 1 Capitalize the first letter of the MATLAB function name that you want to call and add the prefix ml f 2 Examine the MATLAB syntax for the function Find the MATLAB call with the largest number of arguments Determine which input and output arguments are required and which are optional 3 M
241. t 5 Create a 3 by 1 array for the return value from the orenz function 6 Calculate the values of the Lorenz equations at the current time step lorenz doesn t use the input time step t m which is provided by ml f 0de23 Storethe values directly in thereal part of the array that or enz returns yp points to the real part of ypm the return value Passing Functions As Arguments to Library Routines The next section of this example defines the thunk function that actually calls or enz You must writea thunk function whenever you want to pass a function that you ve defined to one of MATLAB s function functions static int _lorenz_thunk_fcn_ mlfFuncp pFunc int nths mxArray I1 hs int mrhs mxArray rhs typedef mxArray PFCN 1 2 mxArray mxArray mxArray Qut if nihs gt 1 nrhs gt 2 return 0 Out PFCN 1 2 pFunc nrhs gt 0 rhs 0 NULL nrhs gt 1 rhs 1 NULL if nlhs gt 0 Ihs 0 Out return 1 Notes 1 Define the thunk function that calls the or enz function A thunk function acts as a translator between your function s interface and the interface needed by the MATLAB C Math Library The thunk function takes five arguments that describe any function with twoinputs and one output in this examplethe function is always or enz an ml f Funcp pointer that points tol orenz an integer nl hs that indicates the number of output argument
242. t For more information about array indexing see Chapter 5 mxArray A NULL ml fl ndexAssi gn amp A es ra ae Index subscript format mlfScalar 2 mlfScalar 2 subscripts ml fScalar 17 value to be assigned t mxDestroyArray A This call creates the array A and fills it with zeros before performing the assignment The following output shows the array created by this code fragment 0 0 0 17 Initializing a Numeric Array with Data You can specify the value of elements in an array using ml fl ndexAssign However if you want to assign values to many elements in an array this method can become tedious The fastest way to initializea MATLAB array is to obtain a pointer to the data area in the mx Array data type and copy data to this location You use the MATLAB API routinemxGet Pr toretrievethis pointer and copy your data to this location using the standard C memcpy routine The API alsoincludes a routine mxGet Pi that lets you initialize the imaginary part of an array in the same way Note Makesure the data you are copying into the array will fit into the storage associated with the pointer returned by mx Get Pr The MATLAB C Math Library will not grow or expand an array when you copy data directly into the mx Array data pointer W orking with MATLAB N umeric Arrays The following example illustrates this procedure which is a common MATLAB C Math Library programming idiom Note that
243. t to true when it was not expecting one For example most of the matrix creation functions for example ml f Eye andml f Zeros issue this error if any of their arguments are string matrices The only matrix norms available are 1 2 inf and fro The function ml f Nor m has an optional second argument This argument must be either thescalars 1 or 2 or thestringsi nf orfro inf indicates theinfinity norm and f r o the F norm This error occurs when the second argument to ml f Normis any value other than one of these four values Too many input arguments This error occurs when a function has more input arguments passed to it than it expects The MATLAB C Math Library should never issue this error as this condition should be detected by the C compiler Please notify The MathWorks if you see this error Too many output arguments This error occurs when a function has more output arguments passed to it than it expects The MATLAB C Math Library should never issue this error as this condition should be detected by the C compiler Please notify The MathWorks if you see this error Variable must contain a string An argument to a function should have been a string matrix i e a matrix with the string property set to true but was not Zero can t be raised to a negative power On machines with non IEEE floating point format the library does not permit you to raise zero to any negative power as this would result in a Errors divi
244. t of options files currently included in thebi n subdirectory of MATLAB mbuild setup Using the mbuild setup command selects an options file that is placed in matlab and used by default for mbuild An options file in the current working directory or specified on the command line overrides the default options file in matlab 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 mbuild f command see mbuild help for more information The options files available for mbuild are 1 matlab bin mbuildopts sh Build and link with MATLAB C C Math Library If there is more than one options file you can select the one you want by entering its number and pressing Return If there is only one options file available it is automatically copied to your MATLAB directory if you do not already havean mbui d options file If you already have an mbui d options file you are prompted to overwrite the existing one Modifying the Options File Another use of thes et up option is if you want to change your options file settings For example if you want to make a change tothe current linker settings or you want to disable a particular set of warnings you should use the setup option If you need to change the options that mbui d passes to your compiler or linker you must first run mbuild setup
245. t pass your data to the routines in the form of a MATLAB array This chapter e Describes the MATLAB arrays supported by the library and the C data type defined to represent them e Describes how to create arrays and perform other common array programming tasks Because the library routines work the same as the corresponding MATLAB functions this chapter does not describe their function in detail For more information about MATLAB arrays and their use see Using MATLAB Instead this chapter provides an overview of working with MATLAB arrays and highlights where the syntax of the library routine is significantly different than its MATLAB counterpart Supported MATLAB Array Types The MATLAB C Math Library supports the following MATLAB array types or classes e Numeric arrays The library supports multidimensional numeric arrays where values are represented in double precision format All MATLAB arithmetic functions operate on numeric arrays For moreinformation about working with numericarrays see Working with MATLAB NumericArrays on page 3 4 Sparse arrayS To conserve space two dimensional numeric arrays can be stored in sparse format where only nonzero elements of the array are stored Numeric arrays with more than two dimensions cannot be converted to sparse format For more information about working with sparse arrays see Working with MATLAB Sparse Matrices on page 3 18 Character arrays The library supports
246. t pointer to data Get a pointer to the dimensions array Get the number of bytes required to store each data element Get value of eps Get a field value given a field name and an index in a structure array Get a field value given a field number and an index ina structure array Get a field name given a field number in a structure array Get a field number given a field name in a structure array Get pointer to imaginary data of an mxArray Get the value of infinity Get thei r array of a sparse matrix Get thej c array of a sparse matrix Get the number of rows M and columns N of an array 9 47 9 Library Routines 9 48 Array Access Routines Continued Function Purpose mxGet Name mxSet Name Get and set the name of an mx Array mx Get NaN Get the value of N ot a N umber mxGet Number Of Di mensi ons mxGet Number Of El ements mxGet Number Of Fi el ds mx Get Nz max mxGet Pi mxGet Pr mxGet Scalar mxGet String mxi sChar mxi sCl ass mx sCompl ex mx sDouble mx sEmpt y mxIl sFinite mxi sl nf mxi sint8 mxi sl nt16 Get the number of dimensions Get number of elements in an array Get the number of fields in a structure mx Array Get the number of elements in their pr and if it exists pi arrays Get the real and imaginary parts of an mxArray Get the real component from the first data element of an mxArray Copy the data from a string mxArray into
247. t2pol Transform Cartesian coordinates to polar ml f Cart2sph Transform Cartesian coordinates to spherical ml f Pol 2cart Transform polar coordinates to Cartesian ml fSph2cart Transform spherical coordinates to Cartesian 9 30 MATLAB M File M ath Library Numerical Linear Algebra Matrix Analysis Function Purpose ml f Nor mest Estimate the matrix 2 norm ml f Nul Orthonormal basis for the null space ml f Orth Orthonormal basis for the range ml f Rank Number of linearly independent rows or columns ml f Rref Reduced row echelon form ml f Subspace Angle between two subspaces ml f Trace Sum of diagonal elements Linear Equations Function Purpose ml f Cond Condition number with respect to inversion ml f Condest 1 norm condition number estimate ml fLscov Least squares in the presence of known covariance ml f Nnis Nonnegative least squares ml f Pi ny Pseudoinverse Eigenvalues and Singular Values Function Purpose ml f Condei g Condition number with respect to eigenvalues ml f Pol y Characteristic polynomial ml f Pol yeig Polynomial eigenvalue problem 9 31 9 Library Routines Matrix Functions Function Purpose ml f Funm Evaluate general matrix function ml fLogm Matrix logarithm ml f Sqrtm Matrix square root Factorization Utilities Function Purpose ml f Cdf 2rdf Complex diagonal form to real block diagonal form ml f Pl anerot Gene
248. tatement Both are marked as bound arrays Sincegq_ ocal is a local variable it must be explicitly deleted within this function z_out is 4 27 4 Managing Array Memory 4 28 an output array argument that will be explicitly deleted in the calling function See Assigning Arrays to mxArray Variables on page 4 9 to learn how ml f Assi gn determines whether to delete the contents of the target argument and whether to make a shared data copy of the source argument 7 Freeany local bound array variables If you ve assigned by calling ml f Assi gn avaluetoany local variablethat isan array you must destroy it by calling mxDestroyArray Note The exception is a local bound array that is the return value from the function Do not call mxDestroyArray on your return value 8 Call ml fRestorePreviousContext torestorethe memory context that existed prior to the function call Supply the same arguments that you passed toml fEnterNewContext Before ending your function and returning a value you must call ml fRestorePrevi ousContext to reestablish the state temporary or bound of input arguments prior to the function call Any input argument that becomes temporary is then deleted by ml f RestorePreviousContext If you fail to call ml f RestorePreviousContext your program will leak memory If an input array is bound when it is passed to a function it will never be destroyed automatically by that function or
249. tends to multidimensional arrays You can think of an N dimensional array as a series of pages each of which is a two dimensional array The first two dimensions in the N dimensional array determine the shape of the pages and the remaining dimensions determine the number of pages In a three or higher dimensional array for example MATLAB iterates over the pages to create the storage column again appending elements col umnwise You can think of three dimensional arrays as books with a two dimensional array on each page Theterm pageis used frequently in this document to refer to a two dimensional array that is part of a larger N dimensional array Labeling the dimensions past three is more difficult You can imagine shelves of books for dimension 4 rooms of shelves for dimension 5 libraries of rooms Overview for dimension 6 etc This document rarely uses an array of dimension greater than three or four although MATLAB and the MATLAB C Math Library handle any number of dimensions that doesn t exceed the amount of memory available on your computer For example consider a 5 by 4 by 3 by 2 array C 5 7 5 Indexing into Arrays MATLAB stores C as MATLABdisplays C as 1 T TE bar a y N ooro y 2 x 2 D D D D D D EA 2 onoor 2 annoo 2 oooro 2 nanoo 2 ano bo S o a a a a a a T a a S a T 5 8 Overview Again a single subscript indexes directly into this column For exam
250. ter you have successfully run thes et up option you can re enable your antivirus software Verification of mbuild Fails If none of the previous solutions addresses your difficulty with mbui d contact Technical Support at The MathWorks at support mat hworks comor 508 647 7000 1 35 1 G etting Ready Building on Your Own 1 36 To build any of the examples or your own applications without mbui d compile the file with an ANSI C compiler You must set the include file search path to contain the directory that contains the file mat ab h compilers typically use the switch to add directories to the include file search path See Appendix A to determine where mat ab h is installed Link the resulting object files against the libraries in this order 1 MATLAB M File Math Library l i bmmfi e 2 MATLAB Built In Library i bmat b 3 MATLAB MAT File Library l i bmat 4 MATLAB Application Program Interface Library I i bmx 5 ANSI C Math Library i bm Specifying the libraries in the wrong order on the command line typically causes linker errors Note that on the PC if you are using the Microsoft Visual C compiler you must manually build the import libraries from the def files using i b If you are using the Borland C Compiler you can link directly against the def files usingi mpl ib If you are using Watcom you must build them from the DLLs using wl i b These commands are documented in your compiler documenta
251. th Library you call ml f Fi nd like this ml f Assign amp k milf Find NULL NULL X ml fAssign amp i milf Find amp j NULL X ml fAssign amp i milf Find amp amp v X wherei j k v andX aremxArray variables i j k andv areinitialized to NULL The general rule for multiple output arguments is that the function return value an mx Ar ray corresponds to the first output argument All additional output arguments are passed into the function as mxArray parameters Passing Optional Input and Output Arguments MATLAB functions may have both optional input and optional output arguments Consider the MATLAB functions v d Thes vd reference page begins like this Purpose Singular value decomposition Syntax s svd X U S V svd X U S V svd X 0 The function prototypes given under the Syntax heading are different from those in a C language reference guide Y et they contain enough information to tell you how to call the corresponding MATLAB C Math Library routine ml f Svd if you Know how to interpret them 6 5 6 Calling Library Routines 6 6 Thefirst thing to noticeis that the syntax lists three ways tocall s vd Thethree calls tosvd differ both in the number of arguments passed tosvd and in the number of values returned by s vd Notice that there is one constant among all three calls theX input parameter is always present in the parameter list X is therefore a required argument
252. the complex number 2 4i and the integer 7 B N 2 performs the same operation in MATLAB Cell arrays support vector based one dimensional indexing as well To extract the first and last elements of N first makea vector v that contains the integers 1 and4 useml fHorzcat toconstructv Then call mi fl ndexRef like this ml fAssign amp B miflndexRef N v Indexing into Cell Arrays The result B isa 1 by 2 cell array that contains a 2 by 2 matrix element 1 1 of N and the scalar 7 element 2 2 of N B N 1 4 performs the same operation in MATLAB Referencing the Contents of a Cell To obtain the contents of a single cell use braces in the indexing string to indicate that you are referencing the cell contents not the cell itself ml f Assi gn amp mflndexRef N mfScalar 1 mlfScalar 2 c isthestring array Eric c N 1 2 performs the same operation in MATLAB Referencing a Subset of the Contents of a Cell To obtain a subset of a cell s contents concatenate indexing expressions F or example to obtain element 2 2 from the array in cell N 1 1 use an indexing string that concatenates an index that references the entire contents of a cell with an index that references a portion of those contents ml f Assi gn amp d mi fI ndexRef N mi fScalar 1 m fScalar 1 mfScalar 2 mfScalar 2 d is 5 d N 1 1 2 2 performs the sa
253. the other four arguments U S V and 0 are optional arguments The MATLAB C Math Library function ml f Svd has an argument list that encompasses all the combinations of arguments the MATLAB svd function accepts All the arguments to ml f Svd are pointers Thereturn valueis a pointer as well Input arguments and return values are always declared as mxArray output arguments as mxArray mxArray mlfSvd mxArray S mxArray V mxArray X mxArray Zero The return value and the parameters S and V represent the output arguments of the corresponding MATLAB function svd The parameters X and Zero correspond tothe input arguments of svd Notice that all the output arguments are listed before any input argument appears this is a general rule for MATLAB C Math Library functions ml f Svd has four arguments in its parameter list and one return value for a total of five arguments Fiveis alsothe maximum number of arguments accepted by the MATLAB svd function Clearly ml f Svd can accept just as many arguments assvd But because C does not permit arguments to be left out of a parameter list there is still the question of how to specify the various combinations Thes vd reference page from the online MATLAB Function Referenceindicates that there arethree valid combinations of arguments for s v d one input and one output one input and three outputs and two inputs and three outputs All MATLAB C Math Library functions have the same number of i
254. thunk function then translates from the calling convention used by ml f Feval arrays of arguments to the standard C Math Library calling convention an explicit list of arguments executes the function and returns the results toml f Feval Extending the mifFeval Table In order to extend the built in mi f Feval table you must 1 Write the function that you want a function function to execute 2 Writea thunk function that knows how to call your function 6 21 6 Calling Library Routines 6 22 3 Declare a local function table and add the name of your function a pointer to your function and a pointer to your thunk function to that table 4 Register the local table with ml f Feval Note that your program can t contain more than 64 local function tables but each table can contain an unlimited number of functions Writing a Thunk Function A thunk function must 1 Ensure that the number of arguments in the input and output arrays matches the number of arguments required by the function to be executed Remember that functions in the MATLAB C Math Library can have optional arguments 2 Extract the input arguments from the input argument array 3 Call the function that was passed to it 4 Place the results from the function call into the output array Note You dont need to writea thunk function if you want a function function to execute a MATLAB C Math Library function A thunk function and an entry in the
255. tiate polynomial see online help mf Polyfit Fit polynomial to data ml f Pol yval Evaluate polynomial ml fPolyvalm Evaluate polynomial with matrix argument ml f Residue Partial fraction expansion residues ml f Resi 2 Residue of a repeated pole ml f Roots Find polynomial roots ml f Unmk pp Supply information about piecewise polynomial 9 36 MATLAB M File M ath Library Function Functions and ODE Solvers Optimization and Root Finding Function Purpose ml f Fmi n Minimize function of one variable ml f Fmi ns Minimize function of several variables ml f Fopti ons Set minimization options ml f Fzero Find zero of function of one variable Numerical Integration Quadrature Function Purpose ml f Dol quad Numerical double integration ml f Quad Numerically evaluate integral low order method ml f Quad8 Numerically evaluate integral high order method Ordinary Differential Equation Solvers Function Purpose ml f Ode23 Solve differential equations low order method ml f Ode45 Solve differential equations high order method ml f Ode113 Solve nonstiff differential equations variable order method ml f Odel5s Solve stiff differential equations variable order method ml f Ode23s Solve stiff differential equations low order method 9 37 9 Library Routines 9 38 ODE Option Handling Function Purpose ml f Odeget Extract properties fromopti ons stru
256. ting a Print Handler 8 OVErVICW oo eg cde ae ADEE Needy ee aos Oneal O 8 2 Handling Errors 0 0 0 cece ccc ccc ees 8 3 Customizing Error Handling 00eee eee eee 8 5 Continuing Processing After Errors 2 20 005 8 5 Example Program Defining Try Catch Blocks ex6 c 8 6 x Contents Replacing the Default Library Error Handler 8 9 Writing an Error Handler 000 e eee eee eee 8 9 Registering Your Error Handler 2 0045 8 10 Example Program 0c cece ete ee 8 10 Defining a Print Handler 000005 8 14 Providing Your Own Print Handler 0 4 8 14 Output to Se GU lh pee te ee E a oe oe beware eee dee 8 15 X Windows Motif Example 00 00 e eee 8 15 Microsoft Windows Example 0 0000e sea ee 8 17 Library Routines Why Two MATLAB Math Libraries 9 3 The MATLAB Built In Library 9 4 General Purpose Commards 0cee cence nee eees 9 5 Operators and Special FUNCtiIONS 000 cece eee 9 5 Elementary Matrices and Matrix Manipulation 9 10 Elementary Math Functions 00 cee eee eee 9 12 Numerical Linear Algebra 00 00 ce eee eee 9 13 Data Analysis and Fourier Transform Functions 9 15 Character String Functions 0 0 0c eee eee 9 16 Filel OFUNCtloOns iser nE a
257. tion On some platforms additional libraries are necessary see the platform specific section of the mbui d script for the names and order of these libraries on the platforms we support Writing Programs Overview 2 2 ee 2 2 A Simple Example Program 2 2 2 42 2 2 2 W riting Programs Overview The MATLAB C Math Library makes the powerful set of MATLAB math functions available to C applications While you can program with the library using standard coding techniques there are some programming idioms that you must know to use the library effectively This chapter presents a simple stand alone application that introduces these concepts including e Working with MATLAB arrays e Calling MATLAB C Math Library functions especially those that can accept optional input arguments and can return multiple values e Taking advantage of MATLAB C Math Library automated memory management e Using the MATLAB C Math Library error handling mechanism A Simple Example Program This example application determines if two numbers arerelatively prime that is the numbers share no common factors While its function is trivial the application serves well as an introduction to programming in C with the MATLAB C Math Library The notes following the example highlight points of particular interest in the example and contain pointers to other chapters in this manual where you find more detailed information The source code
258. tions file the mbui d script searches the following e The current directory e Theuser Profiles directory e lt matlab gt bin mb ui d uses the first occurrence of the options file it finds If no options file is found mb ui d searches your machine for a supported C compiler and uses the 1 22 Building a Stand Alone Application on Microsoft W indows factory default options file for that compiler If multiple compilers are found you are prompted to select one The User Profile Directory Under Windows The Windows user Pr of i es directory is a directory that contains user specific information such as Desktop appearance recently used files and Start Menu items The mbui d utility stores its options filecompopts bat that is created during the setup process in a subdirectory of your user Profiles directory named Application Data Mat hWorks MATLAB Under Windows NT and Windows 95 98 with user profiles enabled your user profile directory is wi ndi r Profiles username Under Windows 95 98 with user profiles disabled your user profile directory is wi ndi r Under Windows 95 98 you can determine whether or not user profiles are enabled by using the Passwords control panel Systems with Exactly One C C Compiler If your supported C compiler is installed on your system you are ready to create C stand alone applications On systems where there is exactly one C compiler available to you the mbui d utility auto
259. tions file that controls the switches and options for your C compiler It is architecture specific When you execute mbui Id setup this file is copied to your MATLAB root installation directory A Directory Organization lt matlab gt extern lib ARCH The lt mat ab gt extern ib ARCH directory contains the binary library files ARCH Specifies a particular UNIX platform For example on a Sun SPARCstation running Solaris the ARCH directory iss ol 2 The libraries that come with the MATLAB C Math Library are shown in this table li bmat ext i bmatlb ext li bmi ext i bmmfile ext i bmx ext li but ext MAT file access routines to support ml f Load and ml f Save MATLAB Built In Math Library Contains stand alone versions of MATLAB built in math functions and operators Required for building stand alone applications Internal MAT file access routines MATLAB M File Math Library Contains stand alone versions of the math M files Needed for building stand alone applications that require MATLAB M file math functions MATLAB Array Access and Creation Library Contains array creation and access routines MATLAB Utilities Library Contains the utility routines used by various components The filename extension ext is a on IBM RS 6000 s0 on Solaris Alpha Linux and SGI and s on HP 700 The libraries are shared libraries on all platforms Directory Organization on UN IX lt matia
260. tlab gt extern include ae lt matlab gt extern examples cmath A 9 A Directory Organization A 2 This chapter describes the directory organization of the MATLAB C Math Library on UNIX and Microsoft Windows systems The MATLAB C Math Library is part of a family of tools offered by The MathWorks All MathWorks products are stored under a single directory referred to as the MATLAB root directory Separate directories for the major product categories are located under the root The MATLAB C Math Library is installed in theext ern directory where products external to MATLAB areinstalled and in thebi n directory If you have other MathWorks products there are additional directories directly below the root Directory Organization on UN IX Directory Organization on UNIX This figure illustrates the directory structure for the MATLAB C Math Library files on UNIX lt mat I ab gt symbolizes the top level directory where MATLAB is installed on your system ARCH specifies a particular UNIX platform lt mat ab gt bin extern ARCH include exampl es cmath lt matiab gt bin The lt mat ab gt bi n directory contains the mbui d script and the scripts it uses to build your code mb ui ld Shell script that controls the building and linking of your code mbuildopts sh Op
261. to Arrays 5 16 Assumptions for the Code Examples The C code included in the following sections demonstrates how to perform indexing with the MATLAB C Math Library For the most part each example only presents the call to an indexing function As you read the examples assume that the code relies on declarations assignments and deletions that follow these conventions Automated memory management is in effect The functions that contain this code would begin with a call toml f Ent er NewCont ext and end with calls to ml fRestorePreviousContext andmlfReturnvVal ue Assignments are made by calling mi f Assi gn The source arrays are created using the ml f Doubl eMatri x function For example this code creates matrix A static double A array_data 1 2 3 4 5 6 7 8 9 mxArray A ml fAssign amp A mlfDoubl eMatrix 3 3 A_array_data NULL See Example Program Creating Numeric Arrays ex1 c in Chapter 3 for a complete example of how to use this function Matrix A which is used throughout the examples is equal to 147 25 8 3 6 9 Nested calls toml f Scal ar create the arrays that contain the indices Because automatic memory management is in effect these scalar arrays are automatically deleted by the library because they are temporary arrays Each mx Array that is the target of an assignment must be deleted after the program finishes with it mxDestroyArray A Many of the examples usethem
262. to ml f Load is always a NULL which terminates the argument list e You must indicate the name of each mx Array variable that you want to load e You can load as many variables as you want in one call tomi f Load e There is no call that loads all variables from a MAT file globally e You donot have to allocate space for the incoming mxArray ml fload allocates the space required based on the size of the variable being read e You must specify a full path for the file that contains the data The library appends the extension mat tothe filename if you do not specify it e You must load data from a binary MAT file not an ASCII MAT file Note Be sure to transmit MAT files in binary file mode when you exchange data between machines For moreinformation on MAT files consult the online version of the MATLAB Application Program Interface Guide 7 Importing and Exporting Array Data Example Program Saving and Loading Data ex5 c This example demonstrates how to use the functions ml f Save and ml f Load to write data to a disk file and read it back again You can find the code for this examplein the lt mat ab gt extern exampl es cmath directory on UNIX systems or the lt mat ab gt extern exampl es cmath directory on PCs where lt mat ab gt represents the top level directory of your installation See Building C Applications in Chapter 1 for information on building the examples 1 ex5 c include
263. tothe or enz thunk function When ml f 0de23 calls ml fFeval mlfFeval accesses the library s built in function table to locate the function pointers that are associated with a given function name in this example the string orenz Assign values to the equation parameters SI GMA RHO and BETA These parameters are shared between the main program and the or enz function Thel orenz function uses the parameters in its computation of the values of the Lorenz equations Create two arrays t sm andy s m which are passed as input arguments tothe ml f Ode23 function Initializet smtothevalues storedintspan Initializeys m to the values stored in y0 Call the library routine ml f 0de23 The return value and the first argument store results ml f 0de23 isavarargout function ml f Var argout NULL indicates that you are not interested in supplying any 6 29 6 Calling Library Routines varargout arguments Pass the name of the function two required input arguments and NULL values for the two optional input arguments ml f Ode23 callsml fFeval toevaluate the or enz function ml fFeval searches the function table for a given function name When it finds a match it composes a call tothe thunk function that it finds in the table passing the thunk function the pointer to the function to be executed also found in the table In addition ml f Feval passes the thunk function arrays of input and output arguments Thethun
264. troyArray ndi ms This code outputs the value 3 indicating that the array C isa three dimensional array Managing Array Memory Overview Why Choose Automated M emory M anagement 3 Using Explicit Memory Management i Using Arrays Under Automated Memory Management Definitions Rules for Array Usage Assigning Arrays to mxArray Variables i Nesting Calls to Functions that Return Arrays Deleting Your Arrays Wer Avoiding Memory Leaks in Your Functions 2 Writing Functions Under Automated Pe Management Using a Function Template As an n Example i Preparing Function Arguments for a New Context Restoring Function Arguments to their Previous Context Returning an Array from Y our Function Summary of Coding Steps Example Program Managing Array Memory ex2 c Example Without Automated Memory Management Restrictions on Function Calling Function Uses Automated Memory M anagement are Function Does Not Use Automated Memory Management Setting Up Your Own Allocation and Deallocation Routines 4 3 4 4 4 6 4 6 4 8 4 9 4 11 4 11 4 12 4 14 4 14 4 16 4 18 4 20 4 22 4 24 4 31 4 33 4 33 4 33 4 35 4 Managing Array Memory Overview This chapter shows you how to manage array memory in the functions that you write with the MATLAB C Math Library The chapter e Explains the rules for assigning values to arrays nesting calls to library function
265. tted I O Function Purpose ml f Fget Read line from file discard newline character ml fF gets Read line from file keep newline character File Positioning Function Purpose ml fFrewind Rewind file pointer to beginning of file Time and Dates Current Date and Time Function Purpose ml f Date Current date string ml f Now Current date and time Basic Functions Function Purpose ml f Dat enum Serial date number ml fDatestr Date string format ml fDatevec Date components 9 40 MATLAB M File M ath Library Date Functions Function Purpose ml f Calendar Calendar ml f Eomday End of month ml f Weekday Day of the week Timing Functions Function Purpose ml f Et i me Elapsed time function ml f Tic Stopwatch timer functions ml f Toc 9 41 9 Library Routines 9 42 Multidimensional Array Functions Function Purpose ml flnd2sub ml fl per mute ml f Shi ftdim ml f Sub2ind Subscript from linear index Inverse permute array dimensions Shift dimensions Linear index from multiple subscripts Cell Array Functions Function Purpose ml fCelldisp Display cell array contents mi fCellfun Apply a cell function to a cell array ml fCellstr Create cell array of strings from character array ml f Deal Deal inputs to outputs ml flscellstr True for a cell array of strings ml fNum2cel Convert numeric array into cell array
266. two local arrays that store the results from the previous calculations The function returns one result in the output argument and the other result as the return value from the function 3 Initializethelocal variablestoNULL or tovalid arrays result_local will be used to store the function s return value q_ ocal will be used in a local calculation Note All MATLAB C Math Library functions including ml f Assi gn require that output arguments are initialized toNULL or point to a valid array 4 Call ml fEnterNewContext tocreatea new memory context for your function ml f Ent erNewContext is always paired with a call to ml fRestorePrevi ousCont ext which appears at the end of the function The first integer argument 1 specifies the number of output array arguments not including the return value passed to Automated Mem _Exampl e the second integer argument 2 specifies the number of input array arguments The arrays themselves mx Array for Example Program M anaging Array Memory ex2 c output arguments mx Array for input arguments z_out x_in andy in are passed next in the same order as they were passed to the function You do not need to terminate the list with NULL Note that ml fEnterNewContext can take any number of arguments ml f Ent er NewCont ext changes the state of any temporary input arrays from temporary to bound enabling them to persist for the duration of the function If they are
267. ugh you can use fewer dimensions Tip for loops provide an easy model for thinking about indexing A one dimensional index is equivalent to a single f or loop a two dimensional index is equivalent to two nested f or loops The size of the subscript determines the number of iterations of thef or loop The value of the subscript determines the values of the loop iteration variables Array Storage MATLAB stores each array as a column of values regardless of the actual dimensions This column consists of the array columns appended top to bottom F or example MATLAB stores A 26 9 42 8 301 5 5 5 Indexing into Arrays 5 6 as e OW OND WwW amp PY Accessing A with a single subscript indexes directly into the storage column A 3 accesses the third value in the column the number 3 A 7 accesses the seventh value 9 and so on If you supply more subscripts MATLAB calculates an index into the storage column based on the array s dimensions For example assume a two dimensional array likeA has size d1 d2 whered1 is the number of rows in the array and d2 is the number of columns If you supply two subscripts i j representing row column indices the equivalent one dimensional index is j 1 d1 i Given the expression A 3 2 MATLAB calculates the offset into A s storage column as 2 1 3 3 or 6 Counting down six elements in the column accesses the value 0 This storage and indexing scheme also ex
268. ular C compiler The MathWorks provides options files for every supported C compiler Much of the information on options files in this chapter is provided for those users who may need to modify an options file to suit their specific needs Many users never have to be concerned with how the options files work Building a Stand Alone Application on UN IX Building a Stand Alone Application on UNIX This section explains how to compile and link C source code into a stand alone UNIX application Configuring for C or C mbui ld determines whether to compile in C or C by examining the type of files you are compiling Table 1 1 shows the supported file extensions If you include both C and C files mbui d uses the C compiler and the MATLAB C Math Library If mbui d cannot deduce from the file extensions whether to compile in C or C mbui d invokes the C compiler Table 1 1 UNIX File Extensions for mbuild Language Ex tension s C c CH cpp at EXX EC Note You can override the language choice that is determined from the extension by using the ang option of mbui d For more information about this option as well as all of the other mbui d options see Table 1 2 Locating Options Files mbui ld locates your options file by searching the following e Thecurrent directory e HOME matlab e lt matl ab gt bin mbui ld uses the first occurrence of the options file it finds If no optio
269. urpose ml f Feval mi flasterr mi f Mf i ename Function evaluation Last error message Return a NULL array M file execution does not apply to stand alone applications Message Display Function Purpose ml fError Display message and abort function ml fLastError Return string that contains the last error message ml f Warning Display warning message 9 9 9 Library Routines Elementary Matrices and Matrix Manipulation Elementary Matrices Function Purpose m m fEye f Ones f Rand fRandn f Zeros Identity matrix Matrix of ones 1s Uniformly distributed random numbers Normally distributed random numbers Matrix of zeros Os Basic Array Information Purpose Function ml f Disp ml fl sempt y ml fl sequal ml fl slogical ml fLength ml fLogical ml f Ndi ms ml f Size Display text or array True for empty array True for input arrays of the same type size and contents True for logical arrays Length of vector Convert numeric values to logical Number of dimensions Size of array Special Constants Function Purpose ml f Computer ml fEps Computer type Floating point relative accuracy 9 10 The MATLAB Builtln Library Special Constants Continued Function Purpose ml f Fl ops Floating point operation count Not reliablein stand alone applications ml f Return an array with the v
270. uses a built in table to find out how to execute a particular function The built in table provides ml f Feval with two pieces of information a pointer that points to the function to be executed and a pointer to what s called a thunk function As shipped ml f Feval s built in table contains each function inthe MATLAB C Math Library If you want ml f Feval toknow how toexecutea function that you ve written you must extend the built in table by creating a local function table that identifies your function for ml f Feval It s the thunk function however that actually knows how to execute your function In Example Program Passing Functions As Arguments ex4 c on page 6 22 the thunk function _ orenz_thunk_fcn_ executes orenz A thunk function s actions are solely determined by the number of input and output arguments to the function it is calling Therefore any functions that have the same number of input and output arguments can share the same thunk function For example if you wrote three functions that each take two inputs and produce three outputs you only need to write one thunk function to handle all three ml f Feval calls the thunk function through the pointer it retrieves from the built in table passing it a pointer to the function to be executed the number of input and output arguments and the input and output argument arrays Thunk functions also use the ml f Feval calling convention The
271. uses to perform memory allocation operations The function that you write must have the prototype void callocfcn size_t nmemb size_t size Your function should initialize the memory it allocates to 0 and should return NULL for requests of size 0 2 free _fcn isthe name of the function that mx Free uses to perform memory deallocation freeing operations The function that you write must have the prototype void freefcn void ptr Make sure your function handles NULL pointers free_fcn 0 should do nothing 4 35 4 Managing Array Memory 4 36 3 realloc_fcn isthe name of the function that mx Real oc uses to perform memory reallocation operations The function that you write must have the prototype void reallocfcn void ptr size_t size This function must grow or shrink memory It returns a pointer to the requested amount of memory which contains as much as possible of the previous contents 4 malloc_fcn isthe name of the function to be called in place of mal oc to perform memory allocation operations The prototype for your function must match void mallocfcn size_t n Your function should return NULL for requests of size 0 Refer to the MATLAB Application Program Interface Reference online help for more detailed information about writing these functions Indexing into Arrays Overview How to Call the Indexing Functions Assumptions for the Code Examples Using mifi ndexRef for One D
272. utine Any array that you assign toa variable you must also free using mxDestroyArray Arrays returned as output arguments by 2 W riting Programs library routines are implicitly assigned to the variables by the library and must also be destroyed For more information about assigning arrays to variables see Chapter 4 Determine if there are any common values in the two arrays of prime factors returned by the calls tothe ml f Factor routine Themlflntersect routinereturns an array of the common values in the two arrays if there are no common factors ml fl ntersect returns an empty array This call tomi flntersect illustrates the calling conventions the library uses for MATLAB functions that support optional input arguments routines The library routines include in their signatures all optional input and output arguments If you do not use these optional arguments you must pass NULL in their place For more information about calling MATLAB C Math library routines see Chapter 6 Test the return value of ml f I sempt y This routine returns an array containing the value 1 TRUE if the common factor array is empty and returns an array containing zero FALSE if the factor array contains data Because ml f sempty returns these values as a MATLAB array you cannot use the return value directly in thei f statement Instead pass this return valuetothenl f Tobool routine which converts the return value to a standard C Bo
273. w System and Microsoft Windows Each example demonstrates the interface between the MATLAB C Math Library and the windowing system In particular the examples do not demonstrate how to write a complete working program Each example assumes that you know how to write a program for a particular windowing system The code contained in each example is incomplete For example application start up and initialization code is missing Consult your windowing system s documentation if you need more information than the examples provide Each example presents a simple alternative output mechanism There are other output options as well for example sending output to a window or portion of a window inside an application The code in these examples should serve as a solid foundation for writing more complex output routines Note If you use an alternate print handler you must call ml f Set PrintHandl er before calling other library routines Otherwise the library uses the default print handler to display messages X Windows Motif Example The Motif Library provides aMessageDi al og widget which this example uses to display text messages TheMessageDi al og widget consists of a message text area placed above a row of three buttons labeled OK Cancel and Help 8 15 8 Handling Errors and W riting a Print Handler The message box is a modal dialog box once it displays you must dismiss it before the application will accept other input H
274. ws or columns from a matrix For example miflndexRef A mi f Horzcat mlfScalar 2 ml fScalar 3 NULL ml f CreateCol onl ndex performs the same operation as A 2 3 in MATLAB and selects all the elements in rows two and three 25 8 3 6 9 Using mlflndexRef for N Dimensional Indexing You can use the colon index in the row position as well For example the expression ml f Assi gn amp B miflndexRef A ml f CreateCol onl ndex mi fHorzcat mlfScalar 3 mlfScalar 1 NULL performs the same operation as A 3 1 in MATLAB and selects all the elements in columns 3 and 1 in that order won 1 2 3 Subscripts of this form make duplicating the rows or columns of a matrix easy Selecting an Entire Matrix Using the colon index as both the row and column index selects the entire matrix Although this usage is valid referring to the matrix itself without subscripting is much easier Extending Two Dimensional Indexing to N Dimensions Two dimensional indexing extends very naturally to N dimensions simply use more index arguments Let A be a 3 by 3 by 2 three dimensional array two 3 by 3 pages Page 1 wn e ao uw PA won Page 2 10 13 16 11 14 17 12 15 18 5 29 5 Indexing into Arrays 5 30 Then the MATLAB expression A 2 selects all of page2 A 1 selects all the columns in row 1 on all the pages A 2 2 2 selects the element at the middle of pag
275. x data you want to store in the sparse matrix Vectorsi j ands should all have the same length oe oe oe O O O 3 21 3 W orking with MATLAB Arrays 3 22 e Twoscalar arrays m and n that specify the dimensions of the sparse matrix to be created e An optional scalar array that specifies the maximum amount of storage that can be allocated for this sparse array The following code example illustrates how to create a sparse 8 by 7 sparse matrix from data This call specifies a single value 9 for all the nonzero elements of the sparse matrix which is replicated in all nonzero elements by scalar expansion To see the pattern formed by this sparse matrix see the output of this code which follows static double row subscripts static double col _subscripts mxArray i NULL mxArray j NULL mxArray S NULL mi fAssign amp i mi fDoubl eMatrix 1 6 row subscripts NULL mi fAssign amp mifDoubleMatrix 1 6 col_subscripts NULL ml fAssign amp mfSparse i Row subscripts XJ jiz Column subscripts m fScalar 9 Data m fScalar 8 ml fScalar 7 NULL mi f Print Matrix S mi fPrintMatrix mlfFull S mxDestroyArray i mxDestroyArray j mxDestroyArray S W orking with MATLAB Sparse M atrices This code produces the following output 3 3 4 4 5 w3 uF Dw wm amp WO WO WO WO WO WC ooo m R COO Oe G qG ee ee oo WO CO COCO OO C
276. xibility you lose the benefits of the library s automated memory management Mixing memory management styles is not recommended Choose one style or theother Usetheml f Ent erNewContext andml f RestorePreviousContext pair and ml f Assi gn for all your functions or none of your functions Note Some functions have changed between Version 1 2 and Version 2 0 of the library You must update any calls in existing code to the group of functions that have a different prototype for Version 2 0 of the MATLAB C Math Library See the release notes rel ease txt inthe lt matlab gt extern examples cmath directory of your installation for a list of these functions Setting Up Your Own Allocation and Deallocation Routines Setting Up Your Own Allocation and Deallocation Routines The MATLAB C Math Library calls mx Mal oc toallocate memory and mx Free to free memory These routines in turn call the standard C runtime library routines malloc andfree If your application requires a different memory management implementation you can register your allocation and deallocation routines with the MATLAB C Math Library by calling the function mi fSetLibraryAllocFcns void mlfSetLibraryAllocFens calloc_proc calloc_fcn free proc free fcn realloc_proc realloc_fcn malloc _proc malloc_fcn You must write four functions whose addresses you then pass to ml f SetLibraryAllocFcns 1 calloc_fcn is the name of the function that mx Cal oc
277. y Theindex string Theindex subscripts 6 11 6 Calling Library Routines 6 12 e Pass each non indexed array as The address of the pointer tothe array mxArray ANULL argument e Terminate your entire list of arguments with NULL For example if you want to pass threevar ar gout output arguments two of which are indexed to the examplevar ar gout function ml fVarargout Function presented above embed a call to ml findexVarargout asthe second argument In MATLAB the function call looks like this x y z 1 m n mlfVarargout_Function a b In C the function call looks like this mxArray x NULL y NULL z NULL m NULL n NULL ml fAssign amp x mlfVarargout Functi on amp y mi flndexVarargout amp mfScalar 1 amp m NULL amp m ml fCreateCol onl ndex NULL a b How Pure Varargout Functions Differ Some MATLAB functions define avarargout argument as their only output argument and are therefore called purevarargout functions For example function varargout Example Pure Varargout a b declares a purevarargout function in MATLAB The MATLAB C Math Library requires that you pass all varargout output arguments tomli f Varargout orml flndexVarargout The variable that would ordinarily be used to store the return value must instead be passed to the pure varargout function as the first argument of the ml f Var ar gout routine You con
278. y d n D1 D2 NULL 3 mxDestroyArray A mxDestroyArray Dl mxDestroyArray D2 As the following output illustrates ml f Char creates an 2 by 9 character array This indicates that it added three blanks characters to the string my dog to make it the same length as my string my string my dog Resulting array is 2 by 9 You can also usetheml fStrcat mlfStrvcat andmifStr2mat routines togroup strings intoa multidimensional character array For moreinformation about these routines see the online MATLAB C Math Library Reference W orking with MATLAB Character Arrays Accessing Individual Strings in an Array of Strings You can manipulate multidimensional character arrays just as you woulda standard MATLAB numericarray For example to extract an individual string from a character array use standard MATLAB indexing syntax Note however that a string extracted from a character array in this fashion may contain blank padding characters To remove these blank characters from the character array use the ml f Deb ank routine The following code fragment extracts the string my dog from the character array A created in the previous section This is equivalent to the MATLAB statement B A 2 The example displays the size of the extracted array B before and after removing blanks Note that the index format string is passed as a Standard C string it does not need to be a MATLAB character array
279. y of the arrays that you pass aS varar gout output arguments you form an ml f VarargoutList by passing the address of each mxArray to ml f Varar gout Its prototype is mlfVarargoutList mlfVarargout mxArray pp_array Follow these guidelines when you call mi f Varargout e Pass any number of mxArray variables tomi f Varargout e Terminate your list of arguments with NULL For example if you want to pass threevarar gout output arguments to the examplevarargout function ml f Varargout_ Function presented above embed a call tomi f Varargout asthe second argument ml f Assi gn amp x ml fVarargout_Function amp y m fVarargout amp z amp m amp n NULL a b where all variables aremxArray pointers x isthe return value y is a required output argument z m andn arevarargout output mxArray variables a and b areinput variables Note that this function is not a purevarargout function In MATLAB the function call looks like this x y z m n mfVarargout_Function a b Forming a List of Indexed varargout Arguments If you are indexing into at least one of the arrays that you pass as avarargout output argument you must form your ml f VarargoutList by passing indexed and nonindexed arguments to ml fl ndexVarargout follow these guidelines e Pass an indexed array as a Series of arguments just as you do when indexing an array with ml fl ndexRef The address of the pointer tothe array mxArra
280. y platform and are listed within the individual UNIX and Windows sections that follow Overview To build a stand alone application using the MATLAB C Math Library you must supply your ANSI C compiler with the correct set of compiler and linker options or switches To help you The MathWorks provides a command line utility called mbui d The mbui d script makes it easy to e Set your compiler and linker settings e Change compilers or compiler settings e Switch between C and C development e Build your application On UNIX and Microsoft Windows systems follow these steps to build C applications with mbui d 1 Verify that mbui d can create stand alone applications 2 Build your application You only need to reconfigure if you change compilers for example from Watcom to MSVC or upgrade your current compiler 1 11 1 G etting Ready 1 12 Figure 1 1 shows the sequence on both platforms The sections following the flowchart provide more specific details for the individual platforms Yes Reconfigure or use Test your mbui d configuration mbuild setup Does mbuild ex1 c work See Troubleshooting mbuild Figure 1 1 Sequence for Creating Stand Alone C Applications Compiler O ptions Files mbui d stores compiler and linker settings in an options file Options files contain the required compiler and linker settings for your partic
281. you must initialize its first argument an output 4 29 4 Managing Array Memory 4 30 argument toNULL or a valid array Note that if you pass a pointer toa valid array the contents of that array will be deleted before the assignment to the output argument takes place Pass 0 as the first and second argument to ml f EnterNewContext indicating that the mai n routine does not have any array output or input arguments Call ml f Assi gn toassign the return from the MATLAB C Math Library function ml f Doubl eMatrix tothe array variable mat 0 a pointer to an mx Array ml f Doubl eMatrix returns a 2 by 3 temporary array initialized with the data contained in the static C array real _datal mat0 becomes a bound array and will persist until explicitly deleted Call ml f Assi gn toassign the return from a user defined function to an array variable Automated Mem _Exampl e uses the automated memory management provided by the MATLAB C Math Library functions mat 0 is a bound array when it is passed as an input argument to Automated Mem Exampl e Thereturn value from ml f Doubl eMatrix isa temporary array After the call toAutomated_ Mem Example mat0 still exists the temporary array has been deleted by Automated Mem _Example Print the arrays ml f Print Matrix returnsvoid rather than an array mxArray Both ml fPrintMatrix andmlfPrintf use the installed print handling routine to display their output Because

Download Pdf Manuals

image

Related Search

Related Contents

Mode d'emploi de/fr    Digital UV AB Light Meter  Specifica tecnica battelli mt. 4,70  Untitled - Oceanic  SUPPORT.NINTENDO.COM SUPPORT.NINTENDO.COM  Interlink Navigator 2.4  MPEG-4 VIDEO SERVER User`s Manual 15-CD01NB - E  取扱説明書05  

Copyright © All rights reserved.
Failed to retrieve file