13.07.2015 Views

Fortran - Parent Directory

Fortran - Parent Directory

Fortran - Parent Directory

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

MATLAB ® 7Cand<strong>Fortran</strong>Function Reference


How to Contact The MathWorkswww.mathworks.comWebcomp.soft-sys.matlabNewsgroupwww.mathworks.com/contact_TS.html Technical Supportsuggest@mathworks.combugs@mathworks.comdoc@mathworks.comservice@mathworks.cominfo@mathworks.com508-647-7000 (Phone)508-647-7001 (Fax)The MathWorks, Inc.3 Apple Hill DriveNatick, MA 01760-2098Product enhancement suggestionsBug reportsDocumentation error reportsOrder status, license renewals, passcodesSales, pricing, and general informationFor contact information about worldwide offices, see the MathWorks Web site.MATLAB C and <strong>Fortran</strong> Function Reference© COPYRIGHT 1984–2007 by The MathWorks, Inc.The software described in this document is furnished under a license agreement. The software may be usedor copied only under the terms of the license agreement. No part of this manual may be photocopied orreproduced in any form without prior written consent from The MathWorks, Inc.FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentationby, for, or through the federal government of the United States. By accepting delivery of the Program orDocumentation, the government hereby agrees that this software or documentation qualifies as commercialcomputer software or commercial computer software documentation as such terms are used or definedin FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions ofthis Agreement and only those rights specified in this Agreement, shall pertain to and govern the use,modification, reproduction, release, performance, display, and disclosure of the Program and Documentationby the federal government (or other entity acquiring for or through the federal government) and shallsupersede any conflicting contractual terms or conditions. If this License fails to meet the government’sneeds or is inconsistent in any respect with federal procurement law, the government agrees to return theProgram and Documentation, unused, to The MathWorks, Inc.TrademarksMATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, and xPC TargetBoxare registered trademarks, and SimBiology, SimEvents, and SimHydraulics are trademarks ofThe MathWorks, Inc.Other product or brand names are trademarks or registered trademarks of their respectiveholders.PatentsThe MathWorks products are protected by one or more U.S. patents. Please seewww.mathworks.com/patents for more information.


Revision HistoryDecember 1996 First Printing New for MATLAB 5 (Release 8)May 1997 Online only Revised for MATLAB 5.1 (Release 9)January 1998 Online Only Revised for MATLAB 5.2 (Release 10)January 1999 Online Only Revised for MATLAB 5.3 (Release 11)September 2000 Online Only Revised for MATLAB 6.0 (Release 12)June 2001 Online only Revised for MATLAB 6.1 (Release 12.1)July 2002 Online only Revised for MATLAB 6.5 (Release 13)January 2003 Online only Revised for MATLAB 6.5.1 (Release 13SP1)June 2004 Online only Revised for MATLAB 7.0 (Release 14)October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1)March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2)September 2005 Online only Revised for MATLAB 7.1 (Release 14SP3)March 2006 Online only Revised for MATLAB 7.2 (Release 2006a)September 2006 Online only Revised for MATLAB 7.3 (Release 2006b)March 2007 Online only Revised and renamed for MATLAB 7.4 (Release 2007a)


Contents1Functions — By CategoryMAT-File Access ................................... 1-2MX Array Manipulation ............................ 1-2MEX-Files ......................................... 1-9MATLAB Engine ................................... 1-112Functions — Alphabetical ListIndexv


1Functions — By CategoryMAT-File Access (p. 1-2)MX Array Manipulation (p. 1-2)MEX-Files (p. 1-9)MATLAB Engine (p. 1-11)Incorporate and use MATLAB ® datain C and <strong>Fortran</strong> programsCreate and manipulate MATLABarrays from C and <strong>Fortran</strong> MEX andEngine routinesPerform operations in MATLABenvironment from C and <strong>Fortran</strong>MEX-filesCall MATLAB from C and <strong>Fortran</strong>programsSee also “External Interfaces” in MATLAB Function Reference for MATLABinterfaces to DLLs, Java, COM and ActiveX, DDE, Web services, and serialport devices.


1 Functions — By CategoryMAT-File AccessmatClose (C and <strong>Fortran</strong>)matDeleteVariable (C and<strong>Fortran</strong>)matGetDir (C and <strong>Fortran</strong>)matGetFp (C)matGetNextVariable (C and<strong>Fortran</strong>)Close MAT-fileDelete named mxArray from MAT-file<strong>Directory</strong> of mxArrays inMAT-fileFile pointer to MAT-fileRead next mxArray from MAT-filematGetNextVariableInfo (C and <strong>Fortran</strong>) Load array header information onlymatGetVariable (C and <strong>Fortran</strong>)matGetVariableInfo (C and<strong>Fortran</strong>)matOpen (C and <strong>Fortran</strong>)matPutVariable (C and <strong>Fortran</strong>)matPutVariableAsGlobal (C and<strong>Fortran</strong>)Read mxArrays from MAT-filesLoad array header information onlyOpen MAT-fileWrite mxArrays toMAT-filesPut mxArrays intoMAT-filesasoriginating from global workspaceMX Array ManipulationmwIndex (C and <strong>Fortran</strong>)mwPointer (<strong>Fortran</strong>)mwSize (C and <strong>Fortran</strong>)mxAddField (C and <strong>Fortran</strong>)mxArrayToString (C)mxAssert (C)Type for index valuesDeclare appropriate pointer type forplatformType for size valuesAdd field to structure arrayConvert array to stringCheck assertion value for debuggingpurposes1-2


MX Array ManipulationmxAssertS (C)mxCalcSingleSubscript (C and<strong>Fortran</strong>)mxCalloc (C and <strong>Fortran</strong>)mxChar (C)mxClassID (C)mxClassIDFromClassName(<strong>Fortran</strong>)mxComplexity (C)mxCopyCharacterToPtr (<strong>Fortran</strong>)mxCopyComplex16ToPtr (<strong>Fortran</strong>)mxCopyComplex8ToPtr (<strong>Fortran</strong>)mxCopyInteger1ToPtr (<strong>Fortran</strong>)mxCopyInteger2ToPtr (<strong>Fortran</strong>)mxCopyInteger4ToPtr (<strong>Fortran</strong>)mxCopyPtrToCharacter (<strong>Fortran</strong>)mxCopyPtrToComplex16 (<strong>Fortran</strong>)mxCopyPtrToComplex8 (<strong>Fortran</strong>)Check assertion value withoutprinting assertion textOffset from first element to desiredelementAllocate dynamic memory for arrayusing MATLAB memory managerData type for string mxArrayInteger value identifying class ofmxArrayIdentifier corresponding to classFlag specifying whether mxArrayhas imaginary componentsCopy character values from <strong>Fortran</strong>array to pointer arrayCopy COMPLEX*16 values from<strong>Fortran</strong> array to pointer arrayCopy COMPLEX*8 values from <strong>Fortran</strong>array to pointer arrayCopy INTEGER*1 values from <strong>Fortran</strong>array to pointer arrayCopy INTEGER*2 values from <strong>Fortran</strong>array to pointer arrayCopy INTEGER*4 values from <strong>Fortran</strong>array to pointer arrayCopy character values from pointerarray to <strong>Fortran</strong> arrayCopy COMPLEX*16 values frompointer array to <strong>Fortran</strong> arrayCopy COMPLEX*8 values from pointerarray to <strong>Fortran</strong> array1-3


1 Functions — By CategorymxCopyPtrToInteger1 (<strong>Fortran</strong>)mxCopyPtrToInteger2 (<strong>Fortran</strong>)mxCopyPtrToInteger4 (<strong>Fortran</strong>)mxCopyPtrToPtrArray (<strong>Fortran</strong>)mxCopyPtrToReal4 (<strong>Fortran</strong>)mxCopyPtrToReal8 (<strong>Fortran</strong>)mxCopyReal4ToPtr (<strong>Fortran</strong>)mxCopyReal8ToPtr (<strong>Fortran</strong>)mxCreateCellArray (C and<strong>Fortran</strong>)mxCreateCellMatrix (C and<strong>Fortran</strong>)mxCreateCharArray (C and<strong>Fortran</strong>)Copy INTEGER*1 values from pointerarray to <strong>Fortran</strong> arrayCopy INTEGER*2 values from pointerarray to <strong>Fortran</strong> arrayCopy INTEGER*4 values from pointerarray to <strong>Fortran</strong> arrayCopy pointer values from pointerarray to <strong>Fortran</strong> arrayCopy REAL*4 values from pointerarray to <strong>Fortran</strong> arrayCopy REAL*8 values from pointerarray to <strong>Fortran</strong> arrayCopy REAL*4 values from <strong>Fortran</strong>array to pointer arrayCopy REAL*8 values from <strong>Fortran</strong>array to pointer arrayCreate unpopulated N-D cellmxArrayCreate unpopulated 2-D cell mxArrayCreate unpopulated N-D stringmxArraymxCreateCharMatrixFromStrings (C Create and <strong>Fortran</strong>) populated 2-D string mxArraymxCreateDoubleMatrix (C and<strong>Fortran</strong>)mxCreateDoubleScalar (C and<strong>Fortran</strong>)mxCreateLogicalArray (C)mxCreateLogicalMatrix (C)Create 2-D, double-precision,floating-point mxArray initialized to0Create scalar, double-precision arrayinitialized to specified valueCreate N-D logical mxArrayinitialized to falseCreate 2-D, logical mxArrayinitialized to false1-4


MX Array ManipulationmxCreateLogicalScalar (C)mxCreateNumericArray (C and<strong>Fortran</strong>)mxCreateNumericMatrix (C and<strong>Fortran</strong>)mxCreateSparse (C and <strong>Fortran</strong>)mxCreateSparseLogicalMatrix(C)mxCreateString (C and <strong>Fortran</strong>)mxCreateStructArray (C and<strong>Fortran</strong>)mxCreateStructMatrix (C and<strong>Fortran</strong>)mxDestroyArray (C and <strong>Fortran</strong>)mxDuplicateArray (C and<strong>Fortran</strong>)mxFree (C and <strong>Fortran</strong>)mxGetCell (C and <strong>Fortran</strong>)mxGetChars (C)mxGetClassID (C and <strong>Fortran</strong>)mxGetClassName (C and <strong>Fortran</strong>)mxGetData (C and <strong>Fortran</strong>)mxGetDimensions (C and<strong>Fortran</strong>)mxGetElementSize (C and<strong>Fortran</strong>)mxGetEps (C and <strong>Fortran</strong>)Create scalar, logical mxArrayinitialized to falseCreate unpopulated N-D numericmxArrayCreate numeric matrix and initializedata elements to 0Create 2-D unpopulated sparsemxArrayCreate unpopulated 2-D, sparse,logical mxArrayCreate 1-by-N string mxArrayinitialized to specified stringCreate unpopulated N-D structuremxArrayCreate unpopulated 2-D structuremxArrayFree dynamic memory allocated bymxCreateMake deep copy of arrayFree dynamic memory allocated bymxCalloc, mxMalloc, ormxReallocContents of mxArray cellPointer to character array dataClass of mxArrayClass of mxArray as stringPointer to dataPointer to dimensions arrayNumber of bytes required to storeeach data elementValue of eps1-5


1 Functions — By CategorymxGetField (C and <strong>Fortran</strong>)mxGetFieldByNumber (C and<strong>Fortran</strong>)mxGetFieldNameByNumber (C and<strong>Fortran</strong>)mxGetFieldNumber (C and<strong>Fortran</strong>)mxGetImagData (C and <strong>Fortran</strong>)mxGetInf (C and <strong>Fortran</strong>)mxGetIr (C and <strong>Fortran</strong>)mxGetJc (C and <strong>Fortran</strong>)mxGetLogicals (C)mxGetM (C and <strong>Fortran</strong>)mxGetN (C and <strong>Fortran</strong>)mxGetNaN (C and <strong>Fortran</strong>)mxGetNumberOfDimensions (C and<strong>Fortran</strong>)mxGetNumberOfElements (C and<strong>Fortran</strong>)mxGetNumberOfFields (C and<strong>Fortran</strong>)mxGetNzmax (C and <strong>Fortran</strong>)mxGetPi (C and <strong>Fortran</strong>)mxGetPr (C and <strong>Fortran</strong>)mxGetScalar (C and <strong>Fortran</strong>)mxGetString (C and <strong>Fortran</strong>)Field value, given field name andindex into structure arrayField value, given field number andindex into structure arrayField name, given field number instructure arrayField number, given field name instructure arrayPointer to imaginary data of mxArrayValue of infinityir array of sparse matrixjc array of sparse matrixPointer to logical array dataNumber of rows in mxArrayNumber of columns in mxArrayValue of NaN (Not-a-Number)Number of dimensions in mxArrayNumber of elements in mxArrayNumber of fields in structuremxArrayNumber of elements in ir, pr, andpi arraysImaginary data elements in mxArrayReal data elements in mxArrayReal component of first data elementin mxArrayCopy string mxArray to C-style string1-6


MX Array ManipulationmxIsCell (C and <strong>Fortran</strong>)mxIsChar (C and <strong>Fortran</strong>)mxIsClass (C and <strong>Fortran</strong>)mxIsComplex (C and <strong>Fortran</strong>)mxIsDouble (C and <strong>Fortran</strong>)mxIsEmpty (C and <strong>Fortran</strong>)mxIsFinite (C and <strong>Fortran</strong>)mxIsFromGlobalWS (C and<strong>Fortran</strong>)mxIsInf (C and <strong>Fortran</strong>)mxIsInt16 (C and <strong>Fortran</strong>)mxIsInt32 (C and <strong>Fortran</strong>)mxIsInt64 (C and <strong>Fortran</strong>)mxIsInt8 (C and <strong>Fortran</strong>)mxIsLogical (C and <strong>Fortran</strong>)mxIsLogicalScalar (C)Determine whether input is cellmxArrayDetermine whether input is stringmxArrayDetermine whether mxArray ismember of specified classDetermine whether data is complexDetermine whether mxArrayrepresents data as double-precision,floating-point numbersDetermine whether mxArray isemptyDetermine whether input is finiteDetermine whether mxArray wascopied from MATLAB globalworkspaceDetermine whether input is infiniteDetermine whether mxArrayrepresents data as signed 16-bitintegersDetermine whether mxArrayrepresents data as signed 32-bitintegersDetermine whether mxArrayrepresents data as signed 64-bitintegersDetermine whether mxArrayrepresents data as signed 8-bitintegersDetermine whether mxArray is ofclass mxLogicalDetermine whether scalar mxArrayis of class mxLogical1-7


1 Functions — By CategorymxIsLogicalScalarTrue (C)mxIsNaN (C and <strong>Fortran</strong>)mxIsNumeric (C and <strong>Fortran</strong>)mxIsSingle (C and <strong>Fortran</strong>)mxIsSparse (C and <strong>Fortran</strong>)mxIsStruct (C and <strong>Fortran</strong>)mxIsUint16 (C and <strong>Fortran</strong>)mxIsUint32 (C and <strong>Fortran</strong>)mxIsUint64 (C and <strong>Fortran</strong>)mxIsUint8 (C and <strong>Fortran</strong>)mxMalloc (C and <strong>Fortran</strong>)mxRealloc (C and <strong>Fortran</strong>)mxRemoveField (C and <strong>Fortran</strong>)mxSetCell (C and <strong>Fortran</strong>)mxSetClassName (C)mxSetData (C and <strong>Fortran</strong>)Determine whether scalar mxArrayof class mxLogical is trueDetermine whether input is NaN(Not-a-Number)Determine whether mxArray isnumericDetermine whether mxArrayrepresents data as single-precision,floating-point numbersDetermine whether input is sparsemxArrayDetermine whether input isstructure mxArrayDetermine whether mxArrayrepresents data as unsigned 16-bitintegersDetermine whether mxArrayrepresents data as unsigned 32-bitintegersDetermine whether mxArrayrepresents data as unsigned 64-bitintegersDetermine whether mxArrayrepresents data as unsigned 8-bitintegersAllocate dynamic memory usingMATLAB memory managerReallocate memoryRemove field from structure arraySet value of one cell of mxArrayConvert structure array to MATLABobject arraySet pointer to data1-8


MEX-FilesmxSetDimensions (C and<strong>Fortran</strong>)mxSetField (C and <strong>Fortran</strong>)mxSetFieldByNumber (C and<strong>Fortran</strong>)mxSetImagData (C and <strong>Fortran</strong>)mxSetIr (C and <strong>Fortran</strong>)mxSetJc (C and <strong>Fortran</strong>)mxSetM (C and <strong>Fortran</strong>)mxSetN (C and <strong>Fortran</strong>)mxSetNzmax (C and <strong>Fortran</strong>)mxSetPi (C and <strong>Fortran</strong>)mxSetPr (C and <strong>Fortran</strong>)Modify number of dimensions andsize of each dimensionSet structure array field, given fieldname and indexSet structure array field, given fieldnumber and indexSet imaginary data pointer formxArraySet ir array of sparse mxArraySet jc array of sparse mxArraySet number of rows in mxArraySet number of columns in mxArraySet storage space for nonzeroelementsSet new imaginary data for mxArraySet new real data for mxArrayMEX-FilesmexAtExit (C and <strong>Fortran</strong>)mexCallMATLAB (C and <strong>Fortran</strong>)mexErrMsgIdAndTxt (C and<strong>Fortran</strong>)mexErrMsgTxt (C and <strong>Fortran</strong>)mexEvalString (C and <strong>Fortran</strong>)Register function to call whenMEX-function is cleared or MATLABterminatesCall MATLAB function oruser-defined M-file or MEX-fileIssue error message with identifierand return to MATLAB promptIssue error message and return toMATLAB promptExecute MATLAB command incaller’s workspace1-9


1 Functions — By CategorymexFunction (C and <strong>Fortran</strong>)mexFunctionName (C and<strong>Fortran</strong>)Entry point to C MEX-fileName of current MEX-functionmexGet (C) Value of specified Handle Graphics ®propertymexGetVariable (C and <strong>Fortran</strong>)mexGetVariablePtr (C and<strong>Fortran</strong>)mexIsGlobal (C and <strong>Fortran</strong>)mexIsLocked (C and <strong>Fortran</strong>)mexLock (C and <strong>Fortran</strong>)Copy of variable from specifiedworkspaceRead-only pointer to variable fromanother workspaceDetermine whether mxArray hasglobal scopeDetermine whether MEX-file islockedPrevent MEX-file from being clearedfrom memorymexMakeArrayPersistent (C and <strong>Fortran</strong>) Make mxArray persist after MEX-filecompletesmexMakeMemoryPersistent (C and <strong>Fortran</strong>) Make allocated memory MATLABpersist after MEX-functioncompletesmexPrintf (C and <strong>Fortran</strong>)mexPutVariable (C and <strong>Fortran</strong>)mexSet (C)mexSetTrapFlag (C and <strong>Fortran</strong>)mexUnlock (C and <strong>Fortran</strong>)mexWarnMsgIdAndTxt (C and<strong>Fortran</strong>)mexWarnMsgTxt (C and <strong>Fortran</strong>)ANSI C printf-style output routineCopy mxArray from MEX-functioninto specified workspaceSet value of specified HandleGraphics propertyControl response of mexCallMATLABto errorsAllowMEX-filetobeclearedfrommemoryIssue warning message withidentifierIssue warning message1-10


MATLAB EngineMATLAB EngineengClose (C and <strong>Fortran</strong>)engEvalString (C and <strong>Fortran</strong>)engGetVariable (C and <strong>Fortran</strong>)engGetVisible (C)engOpen (C and <strong>Fortran</strong>)engOpenSingleUse (C)engOutputBuffer (C and <strong>Fortran</strong>)engPutVariable (C and <strong>Fortran</strong>)engSetVisible (C)Quit MATLAB engine sessionEvaluate expression in stringCopy variable from MATLAB engineworkspaceDetermine visibility of MATLABengine sessionStart MATLAB engine sessionStart MATLAB engine session forsingle, nonshared useSpecify buffer for MATLAB outputPut variables into MATLAB engineworkspaceShow or hide MATLAB enginesession1-11


1 Functions — By Category1-12


Functions — AlphabeticalList2


engClose (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxQuit MATLAB engine session#include "engine.h"int engClose(Engine *ep);integer*4 engClose(ep)mwPointer epArgumentsepEngine pointerDescriptionCExamplesThis routine allows you to quit a MATLAB engine session.engClose sends a quit command to the MATLAB engine session andcloses the connection. It returns 0 on success, and 1 otherwise. Possiblefailure includes attempting to terminate a MATLAB engine session thatwas already terminated.UNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.<strong>Fortran</strong>ExamplesSee AlsoSee fengdemo.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a <strong>Fortran</strong> program.engOpen2-2


engEvalString (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionEvaluate expression in string#include "engine.h"int engEvalString(Engine *ep,const char *string);integer*4 engEvalString(ep, string)mwPointer epcharacter*(*) stringepEngine pointerstringString to executeengEvalString evaluates the expression contained in string for theMATLAB engine session, ep, previously started by engOpen. It returnsa nonzero value if the MATLAB session is no longer running, and zerootherwise.On UNIX systems, engEvalString sends commands to MATLAB bywriting down a pipe connected to the MATLAB stdin. Any outputresulting from the command that ordinarily appears on the screen isread back from stdout into the buffer defined by engOutputBuffer.To turn off output buffering in C, useengOutputBuffer(ep, NULL, 0);To turn off output buffering in <strong>Fortran</strong>, useengOutputBuffer(ep, '')Under Windows on a PC, engEvalString communicates with MATLABusing a Component Object Model (COM) interface.2-3


engEvalString (C and <strong>Fortran</strong>)CExamplesUNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.<strong>Fortran</strong>ExamplesSee AlsoSee fengdemo.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a <strong>Fortran</strong> program.engOpen, engOutputBuffer2-4


engGetVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCopy variable from MATLAB engine workspace#include "engine.h"mxArray *engGetVariable(Engine *ep, const char *name);mwPointer engGetVariable(ep, name)mwPointer epcharacter*(*) nameArgumentsepnameEngine pointerName of mxArray to get from MATLABDescriptionCExamplesengGetVariable reads the named mxArray from the MATLAB enginesession associated with ep and returns a pointer to a newly allocatedmxArray structure, or NULL if the attempt fails. engGetVariable fails ifthe named variable does not exist.Be careful in your code to free the mxArray created by this routine whenyou are finished with it.UNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.See AlsoengPutVariable2-5


engGetVisible (C)PurposeCSyntaxArgumentsDescriptionExamplesDetermine visibility of MATLAB engine session#include "engine.h"int engGetVisible(Engine *ep, bool *value);epEngine pointervaluePointer to value returned from engGetVisibleWindows OnlyengGetVisible returns the current visibility setting for MATLABengine session, ep. A visible engine session runs in a window onthe Windows desktop, thus making the engine available for userinteraction. An invisible session is hidden from the user by removingit from the desktop.engGetVisible returns 0 on success, and 1 otherwise.The following code opens engine session ep and disables its visibility.Engine *ep;bool vis;ep = engOpen(NULL);engSetVisible(ep, 0);To determine the current visibility setting, useengGetVisible(ep, &vis);See AlsoengSetVisible2-6


engOpen (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionStart MATLAB engine session#include "engine.h"Engine *engOpen(const char *startcmd);mwPointer engOpen(startcmd)character*(*) startcmdstartcmdString to start the MATLAB process. On Windows, the startcmdstring must be NULL.A pointer to an engine handle.This routine allows you to start a MATLAB process for the purpose ofusing MATLAB as a computational engine.engOpen(startcmd) starts a MATLAB process using the commandspecified in the string startcmd, establishes a connection, and returns aunique engine identifier, or NULL if the open fails.On UNIX systems, if startcmd is NULL or the empty string, engOpenstarts MATLAB on the current host using the command matlab. Ifstartcmd is a hostname, engOpen starts MATLAB on the designatedhost by embedding the specified hostname string into the larger string:"rsh hostname \"/bin/csh -c 'setenv DISPLAY\hostname:0; matlab'\""If startcmd is any other string (has white space in it, ornonalphanumeric characters), the string is executed literally to startMATLAB.On UNIX systems, engOpen performs the following steps:1 Creates two pipes.2-7


engOpen (C and <strong>Fortran</strong>)2 Forks a new process and sets up the pipes to pass stdin and stdoutfrom MATLAB (parent) to two file descriptors in the engine program(child).3 Executes a command to run MATLAB (rsh for remote execution).Under Windows on a PC, engOpen opens a COM channel to MATLAB.This starts the MATLAB that was registered during installation. Ifyou did not register during installation, on the command line you canenter the commandmatlab /regserverSee “Introducing MATLAB COM Integration” for additional details.CExamplesUNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.<strong>Fortran</strong>ExamplesSee fengdemo.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a <strong>Fortran</strong> program.2-8


engOpenSingleUse (C)PurposeCSyntaxArgumentsDescriptionStart MATLAB engine session for single, nonshared use#include "engine.h"Engine *engOpenSingleUse(const char *startcmd, void *dcom,int *retstatus);startcmdString to start MATLAB process. On Windows, the startcmdstring must be NULL.dcomReserved for future use; must be NULL.retstatusReturn status; possible cause of failure.WindowsThis routine allows you to start multiple MATLAB processesfor the purpose of using MATLAB as a computational engine.engOpenSingleUse starts a MATLAB process, establishes a connection,and returns a unique engine identifier, or NULL if the open fails.engOpenSingleUse starts a new MATLAB process each time it is called.engOpenSingleUse opens a COM channel to MATLAB. This starts theMATLAB that was registered during installation. If you did not registerduring installation, on the command line you can enter the commandmatlab /regserverengOpenSingleUse allows single-use instances of a MATLAB engineserver. engOpenSingleUse differs from engOpen, which allows multipleuserstousethesameMATLABengineserver.See “Introducing MATLAB COM Integration” for additional details.UNIXThis routine is not supported and simply returns.2-9


engOutputBuffer (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSpecify buffer for MATLAB output#include "engine.h"int engOutputBuffer(Engine *ep, char *p, int n);integer*4 engOutputBuffer(ep, p)mwPointer epcharacter*n pArgumentseppnEngine pointerPointer to character bufferLength of buffer pDescriptionengOutputBuffer defines a character buffer for engEvalString toreturn any output that ordinarily appears on the screen. It returns 1 ifyou pass it a NULL engine pointer. Otherwise, it returns 0.The default behavior of engEvalString is to discard any standard outputcaused by the command it is executing. A call to engOutputBuffer witha buffer of nonzero length tells any subsequent calls to engEvalStringto save output in the character buffer pointed to by p.To turn off output buffering in C, useengOutputBuffer(ep, NULL, 0);To turn off output buffering in <strong>Fortran</strong>, useengOutputBuffer(ep, '')2-10


engOutputBuffer (C and <strong>Fortran</strong>)Note The buffer returned by engEvalString is not guaranteed to beNULL terminated.CExamplesUNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.<strong>Fortran</strong>ExamplesSee AlsoSee fengdemo.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a <strong>Fortran</strong> program.engOpen, engEvalString2-11


engPutVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxPut variables into MATLAB engine workspace#include "engine.h"int engPutVariable(Engine *ep, const char *name, const mxArray*pm);integer*4 engPutVariable(ep, name, pm)mwPointer ep, pmcharacter*(*) nameArgumentsepnamepmEngine pointerName given to the mxArray in the engine’s workspacemxArray pointerDescriptionCExamplesengPutVariable writes mxArray pm to the engine ep, giving it thevariable name name. IfthemxArray does not exist in the workspace, itis created. If an mxArray withthesamenamealreadyexistsintheworkspace, the existing mxArray is replaced with the new mxArray.engPutVariable returns 0 if successful and 1 if an error occurs.UNIXSee engdemo.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to call the MATLAB enginefunctions from a C program.WindowsSee engwindemo.c in the eng_mat subdirectory of the examplesdirectory for a sample program that illustrates how to call the MATLABengine functions from a C program for Windows.2-12


engPutVariable (C and <strong>Fortran</strong>)See AlsoengGetVariable2-13


engSetVisible (C)PurposeCSyntaxArgumentsDescriptionExamplesShow or hide MATLAB engine session#include "engine.h"int engSetVisible(Engine *ep, bool value);epEngine pointervalueValue to set the Visible property to. Set value to 1 to make theengine window visible, or to 0 to make it invisible.Windows OnlyengSetVisible makes the window for the MATLAB engine session,ep, either visible or invisible on the Windows desktop. You can usethis function to enable or disable user interaction with the MATLABengine session.engSetVisible returns 0 on success, and 1 otherwise.The following code opens engine session ep and disables its visibility.Engine *ep;bool vis;ep = engOpen(NULL);engSetVisible(ep, 0);To determine the current visibility setting, useengGetVisible(ep, &vis);See AlsoengGetVisible2-14


matClose (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxClose MAT-file#include "mat.h"int matClose(MATFile *mfp);integer*4 matClose(mfp)mwPointer mfpArgumentsmfpPointertoMAT-fileinformationReturnsDescriptionCExamples<strong>Fortran</strong>ExamplesEOF in C (-1 in <strong>Fortran</strong>) for a write error, and 0 if successful.matClose closes the MAT-file associated with mfp.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.See matdemo1.F and matdemo2.F in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use thisMAT-file routine in a <strong>Fortran</strong> program.2-15


matDeleteVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDelete named mxArray from MAT-file#include "mat.h"int matDeleteVariable(MATFile *mfp, const char *name);integer*4 matDeleteVariable(mfp, name)mwPointer mfpcharacter*(*) nameArgumentsmfpnamePointertoMAT-fileinformationName of mxArray to deleteReturnsDescriptionCExamples0 if successful, and nonzero otherwise.matDeleteVariable deletes the named mxArray from the MAT-filepointed to by mfp.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-16


matGetDir (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>Syntax<strong>Directory</strong> of mxArrays inMAT-file#include "mat.h"char **matGetDir(MATFile *mfp, int *num);mwPointer matGetDir(mfp, num)mwPointer mfpinteger*4 numArgumentsmfpnumPointertoMAT-fileinformationAddress of the variable to contain the number of mxArrays intheMAT-fileReturnsDescriptionCExamplesA pointer to an internal array containing pointers to the names ofthe mxArrays intheMAT-filepointedtobymfp. InC,eachnameisa NULL-terminated string. The length of the internal array (numberof mxArrays intheMAT-file)isplacedintonum. If num is zero, mfpcontains no arrays.matGetDir returns NULL in C (0 in <strong>Fortran</strong>) and sets num to a negativenumber if it fails.This routine allows you to get a list of the names of the mxArrayscontained within a MAT-file.The internal array of strings that matGetDir returns is allocatedusing a single mxCalloc and must be freed using mxFree when youare finished with it.MATLAB variable names can be up to length mxMAXNAM, wheremxMAXNAM is defined in the C header file matrix.h.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-17


matGetDir (C and <strong>Fortran</strong>)<strong>Fortran</strong>ExamplesSee matdemo2.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this MAT-file routinein a <strong>Fortran</strong> program.2-18


matGetFp (C)PurposeCSyntaxFile pointer to MAT-file#include "mat.h"FILE *matGetFp(MATFile *mfp);ArgumentsmfpPointertoMAT-fileinformationReturnsDescriptionExamplesACfilehandletotheMAT-filewithhandlemfp. Returns NULL if mfp isa handle to a MAT-file in HDF5-based format.Use matGetFp to obtain a C file handle to a MAT-file. This can be usefulfor using standard C library routines like ferror() and feof() toinvestigate error situations.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-19


matGetNextVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxRead next mxArray from MAT-file#include "mat.h"mxArray *matGetNextVariable(MATFile *mfp, const char **name);mwPointer matGetNextVariable(mfp, name)mwPointer mfpcharacter*(*) nameArgumentsmfpnamePointertoMAT-fileinformationAddressofthevariabletocontainthemxArray nameReturnsDescriptionCExamplesA pointer to a newly allocated mxArray structure representing the nextmxArray from the MAT-file pointed to by mfp. The function returnsthenameofthemxArray in name.matGetNextVariable returns NULL in C (0 in <strong>Fortran</strong>) when theend-of-file is reached or if there is an error condition. In C, use feof andferror from the Standard C Library to determine status.matGetNextVariable allows you to step sequentially through aMAT-file and read all the mxArrays in a single pass. The function readsand returns the next mxArray from the MAT-file pointed to by mfp.Use matGetNextVariable immediately after opening the MAT-filewith matOpen and not in conjunction with other MAT-file routines.Otherwise, the concept of the next mxArray is undefined.Free the memory used by the mxArray created by this routine when youare finished with it.See matdgns.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use the MATLAB MAT-fileroutines in a C program.2-20


matGetNextVariableInfo (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxLoad array header information only#include "mat.h"mxArray *matGetNextVariableInfo(MATFile *mfp, const char **name);mwPointer matGetNextVariableInfo(mfp, name)mwPointer mfpcharacter*(*) nameArgumentsmfpnamePointertoMAT-fileinformationAddressofthevariabletocontainthemxArray nameReturnsDescriptionCExamplesA pointer to a newly allocated mxArray structure representing headerinformation for the next mxArray fromtheMAT-filepointedtobymfp.The function returns the name of the mxArray in name.matGetNextVariableInfo returns NULL in C (0 in <strong>Fortran</strong>) when theend-of-file is reached or if there is an error condition. In C, use feof andferror from the Standard C Library to determine status.matGetNextVariableInfo loads only the array header information,including everything except pr, pi, ir, andjc, from the file’s currentfile offset.If pr, pi, ir, andjc are set to nonzero values when loaded withmatGetVariable, matGetNextVariableInfo sets them to -1 instead.These headers are for informational use only and should never bepassed back to MATLAB or saved to MAT-files.Free the memory used by the mxArray created by this routine when youare finished with it.See matdgns.c in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use the MATLAB MAT-fileroutines in a C program.2-21


matGetNextVariableInfo (C and <strong>Fortran</strong>)See AlsomatGetNextVariable, matGetVariableInfo2-22


matGetVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxRead mxArrays fromMAT-files#include "mat.h"mxArray *matGetVariable(MATFile *mfp, const char *name);mwPointer matGetVariable(mfp, name)mwPointer mfpcharacter*(*) nameArgumentsmfpnamePointertoMAT-fileinformationName of mxArray to get from MAT-fileReturnsDescriptionCExamplesA pointer to a newly allocated mxArray structure representing themxArray named by name from the MAT-file pointed to by mfp.matGetVariable returns NULL in C (0 in <strong>Fortran</strong>) if the attempt toreturn the mxArray named by name fails.This routine allows you to copy an mxArray out of a MAT-file.Free the memory used by the mxArray created by this routine when youare finished with it.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-23


matGetVariableInfo (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxLoad array header information only#include "mat.h"mxArray *matGetVariableInfo(MATFile *mfp, const char *name);mwPointer matGetVariableInfo(mfp, name);mwPointer mfpcharacter*(*) nameArgumentsmfpnamePointertoMAT-fileinformationName of mxArray to get from MAT-fileReturnsDescriptionCExamplesA pointer to a newly allocated mxArray structure representing headerinformation for the mxArray named by name from the MAT-file pointedto by mfp.matGetVariableInfo returns NULL in C (0 in <strong>Fortran</strong>) if the attempt toreturn header information for the mxArray named by name fails.matGetVariableInfo loads only the array header information,including everything except pr, pi, ir, andjc. It recursively creates thecells and structures through their leaf elements, but does not includepr, pi, ir, andjc.If pr, pi, ir, andjc are set to nonzero values when loaded withmatGetVariable, matGetVariableInfo sets them to -1 instead. Theseheaders are for informational use only and should never be passed backto MATLAB or saved to MAT-files.Free the memory used by the mxArray created by this routine when youare finished with it.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-24


matGetVariableInfo (C and <strong>Fortran</strong>)See AlsomatGetVariable2-25


matOpen (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsOpen MAT-file#include "mat.h"MATFile *matOpen(const char *filename, const char *mode);mwPointer matOpen(filename, mode)character*(*) filename, modefilenameName of file to openmodeFile opening mode. Valid values for mode are listed in the followingtable.ruww4wLOpens file for reading only; determines the currentversion of the MAT-file by inspecting the files andpreserves the current version.Opens file for update, both reading and writing,butdoesnotcreatethefileifthefiledoesnotexist(equivalent to the r+ mode of fopen); determines thecurrent version of the MAT-file by inspecting the filesand preserves the current version.Opensfileforwritingonly;deletespreviouscontents,if any.Creates a Level 4 MAT-file, compatible with MATLABVersions 4 and earlier.Opens file for writing character data using the defaultcharactersetforyoursystem.TheresultingMAT-filecan be read with MATLAB Version 6 or 6.5.IfyoudonotusethewL mode switch, MATLAB writescharacter data to the MAT-file using Unicode characterencoding by default.2-26


matOpen (C and <strong>Fortran</strong>)wzOpens file for writing compressed data.w7.3 Creates a MAT-file in an HDF5-based format that canstore objects occupy more than 2 GB.ReturnsDescriptionCExamples<strong>Fortran</strong>ExamplesAfilehandle,orNULL in C (0 in <strong>Fortran</strong>) if the open fails.This routine opens a MAT-file for reading and writing.See “Writing Character Data” in the External Interfaces documentationfor more information on how MATLAB uses character encodings.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.See matdemo1.F and matdemo2.F in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a <strong>Fortran</strong> program.2-27


matPutVariable (C and <strong>Fortran</strong>)PurposeCSyntaxWrite mxArrays toMAT-files#include "mat.h"int matPutVariable(MATFile *mfp, const char *name, const mxArray*pm);<strong>Fortran</strong>Syntaxinteger*4 matPutVariable(mfp, name, pm)mwPointer mfp, pmcharacter*(*) nameArgumentsmfpnamepmPointertoMAT-fileinformationName of mxArray to put into MAT-filemxArray pointerReturnsDescriptionCExamples0 if successful and nonzero if an error occurs. In C, use feof and ferrorfrom the Standard C Library along with matGetFp to determine status.This routine allows you to put an mxArray into a MAT-file.matPutVariable writes mxArray pm to the MAT-file mfp. IfthemxArraydoes not exist in the MAT-file, it is appended to the end. If an mxArraywith the same name already exists in the file, the existing mxArray isreplaced with the new mxArray by rewriting the file. The size of the newmxArray can be different from the existing mxArray.See matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-28


matPutVariableAsGlobal (C and <strong>Fortran</strong>)PurposeCSyntaxPut mxArrays into MAT-files as originating from global workspace#include "mat.h"int matPutVariableAsGlobal(MATFile *mfp, const char *name, constmxArray *pm);<strong>Fortran</strong>Syntaxinteger*4 matPutVariableAsGlobal(mfp, name, pm)mwPointer mfp, pmcharacter*(*) nameArgumentsmfpnamepmPointertoMAT-fileinformationName of mxArray to put into MAT-filemxArray pointerReturnsDescription0 if successful and nonzero if an error occurs. In C, use feof and ferrorfrom the Standard C Library with matGetFp to determine status.This routine puts an mxArray into a MAT-file. matPutVariableAsGlobalis similar to matPutVariable, except that the array, when loaded byMATLAB, is placed into the global workspace and a reference to it isset in the local workspace. If you write to a MATLAB 4 format file,matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable.matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp. Ifthe mxArray does not exist in the MAT-file, it is appended to the end. Ifan mxArray with the same name already exists in the file, the existingmxArray is replaced with the new mxArray by rewriting the file. Thesize of the new mxArray can be different from the existing mxArray.2-29


matPutVariableAsGlobal (C and <strong>Fortran</strong>)CExamplesSee matcreat.c and matdgns.c in the eng_mat subdirectory of theexamples directory for sample programs that illustrate how to use theMATLAB MAT-file routines in a C program.2-30


mexAtExit (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsRegister function to call when MEX-function is cleared or MATLABterminates#include "mex.h"int mexAtExit(void (*ExitFcn)(void));integer*4 mexAtExit(ExitFcn)subroutine ExitFcn()ExitFcnPointer to function you want to run on exitReturns Always returns 0.DescriptionCExamplesSee AlsoUse mexAtExit to register a function to be called just before theMEX-function is cleared or MATLAB is terminated. mexAtExit givesyour MEX-function a chance to perform tasks such as freeing persistentmemory and closing files. Typically, the named ExitFcn performs taskslike closing streams or sockets.Each MEX-function can register only one active exit function at a time.If you call mexAtExit more than once, MATLAB uses the ExitFcn fromthe more recent mexAtExit call as the exit function.If a MEX-function is locked, all attempts to clear the MEX-file will fail.Consequently, if a user attempts to clear a locked MEX-file, MATLABdoes not call the ExitFcn.In <strong>Fortran</strong>, you must declare the ExitFcn as external in the <strong>Fortran</strong>routine that calls mexAtExit if it is not within the scope of the file.See mexatexit.c in the mex subdirectory of the examples directory.mexLock, mexUnlock, mexSetTrapFlag2-31


mexCallMATLAB (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCall MATLAB function or user-defined M-file or MEX-file#include "mex.h"int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs,mxArray *prhs[], const char *name);integer*4 mexCallMATLAB(nlhs, plhs, nrhs, prhs, name)integer*4 nlhs, nrhsmwPointer plhs(*), prhs(*)character*(*) namenlhsplhsNumber of desired output arguments. This value must be lessthan or equal to 50.Array of pointers to mxArrays. The called command puts pointersto the resultant mxArrays intoplhs and allocates dynamicmemory to store the resultant mxArrays. By default, MATLABautomatically deallocates this dynamic memory when you clearthe MEX-file. However, if heap space is at a premium, you maywant to call mxDestroyArray as soon as you are finished with themxArrays thatplhs points to.nrhsprhsnameNumber of input arguments. This value must be less than orequal to 50.Array of pointers to input arguments.Character string containing the name of the MATLAB built-in,operator, M-file, or MEX-file that you are calling. If name is anoperator, just place the operator inside a pair of single quotes,for example, '+'.Returns0 if successful, and a nonzero value if unsuccessful.2-32


mexCallMATLAB (C and <strong>Fortran</strong>)DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions,MATLAB operators, M-files, or other MEX-files. See mexFunction for acomplete description of the arguments.By default, if name detects an error, MATLAB terminates the MEX-fileand returns control to the MATLAB prompt. If you want a differenterror behavior, turn on thetrapflagbycallingmexSetTrapFlag.It is possible to generate an object of type mxUNKNOWN_CLASS usingmexCallMATLAB. For example, if you create an M-file that returns twovariables but assigns only one of them a value,function [a,b]=foo(c)a=2*c;you get this warning message in MATLAB:Warning: One or more output arguments not assignedduring call to 'foo'.MATLAB assigns output b to an empty matrix. If you then call foousing mexCallMATLAB, the unassigned output variable is given typemxUNKNOWN_CLASS.CExamplesSee mexcallmatlab.c in the mex subdirectory of the examples directory.Additional examples:• sincall.c in the refbook subdirectory of the examples directory• mexevalstring.c and mexsettrapflag.c in the mex subdirectoryof the examples directory• mxcreatecellmatrix.c and mxisclass.c in the mx subdirectoryof the examples directorySee AlsomexFunction, mexSetTrapFlag2-33


mexErrMsgIdAndTxt (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionIssue error message with identifier and return to MATLAB prompt#include "mex.h"void mexErrMsgIdAndTxt(const char *errorid,const char *errormsg, ...);subroutine mexErrMsgIdAndTxt(errorid, errormsg)character*(*) errorid, errormsgerroridString containing a MATLAB message identifier. See “MessageIdentifiers” in the MATLAB documentation for information onthis topic.errormsgString containing the error message to be displayed. In C, thestring may include formatting conversion characters, such asthose used with the ANSI C sprintf function....In C, any additional arguments needed to translate formattingconversion characters used in errormsg. Each conversioncharacter in errormsg is converted to one of these values.Call mexErrMsgIdAndTxt to write an error message and itscorresponding identifier to the MATLAB window. After the errormessage prints, MATLAB terminates the MEX-file and returns controlto the MATLAB prompt.Calling mexErrMsgIdAndTxt does not clear the MEX-file from memory.Consequently, mexErrMsgIdAndTxt does not invoke the functionregistered through mexAtExit.If your application called mxCalloc or one of the mxCreate routines toallocate memory, mexErrMsgIdAndTxt automatically frees the allocatedmemory.2-34


mexErrMsgIdAndTxt (C and <strong>Fortran</strong>)Note If you get warnings when using mexErrMsgIdAndTxt, youmay have a memory management compatibility problem. For moreinformation, see “Memory Management Compatibility Issues” in theExternal Interfaces documentation.See AlsomexErrMsgTxt, mexWarnMsgIdAndTxt, mexWarnMsgTxt2-35


mexErrMsgTxt (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionIssue error message and return to MATLAB prompt#include "mex.h"void mexErrMsgTxt(const char *errormsg);subroutine mexErrMsgTxt(errormsg)character*(*) errormsgerrormsgString containing the error message to be displayedCall mexErrMsgTxt to write an error message to the MATLAB window.Aftertheerrormessageprints,MATLABterminatestheMEX-fileandreturns control to the MATLAB prompt.Calling mexErrMsgTxt does not clear the MEX-file from memory.Consequently, mexErrMsgTxt does not invoke the function registeredthrough mexAtExit.If your application called mxCalloc or one of the mxCreate routinesto allocate memory, mexErrMsgTxt automatically frees the allocatedmemory.Note If you get warnings when using mexErrMsgTxt, youmayhaveamemory management compatibility problem. For more information, see“Memory Management Compatibility Issues”.CExamplesSee AlsoSee xtimesy.c in the refbook subdirectory of the examples directory.For additional examples, see convec.c, findnz.c, fulltosparse.c,phonebook.c, revord.c, andtimestwo.c in the refbook subdirectoryof the examples directory.mexErrMsgIdAndTxt, mexWarnMsgIdAndTxt, mexWarnMsgTxt2-36


mexEvalString (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionExamplesSee AlsoExecute MATLAB command in caller’s workspace#include "mex.h"int mexEvalString(const char *command);integer*4 mexEvalString(command)character*(*) commandcommandA string containing the MATLAB command to execute0 if successful, and a nonzero value if unsuccessful.Call mexEvalString to invoke a MATLAB command in the workspaceof the caller.mexEvalString and mexCallMATLAB both execute MATLAB commands.However, mexCallMATLAB provides a mechanism for returning results(left-hand side arguments) back to the MEX-file; mexEvalStringprovides no way for return values to be passed back to the MEX-file.All arguments that appear to the right of an equal sign in the commandstring must already be current variables of the caller’s workspace.See mexevalstring.c in the mex subdirectory of the examples directory.mexCallMATLAB2-37


mexFunction (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionEntry point to C MEX-file#include "mex.h"void mexFunction(int nlhs, mxArray *plhs[], int nrhs,const mxArray *prhs[]);subroutine mexFunction(nlhs, plhs, nrhs, prhs)integer*4 nlhs, nrhsmwPointer plhs(*), prhs(*)nlhsplhsnrhsprhsThe number of expected output mxArraysArray of pointers to the expected output mxArraysThe number of input mxArraysArray of pointers to the input mxArrays. These mxArrays are readonly and should not be modified by your MEX-file. Changing thedata in these mxArrays may produce undesired side effects.mexFunction is not a routine you call. Rather, mexFunction is the nameofafunctioninC(subroutinein<strong>Fortran</strong>)thatyoumustwriteineveryMEX-file. When you invoke a MEX-function, MATLAB finds and loadsthe corresponding MEX-file of the same name. MATLAB then searchesfor a symbol named mexFunction within the MEX-file. If it finds one, itcalls the MEX-function using the address of the mexFunction symbol.If MATLAB cannot find a routine named mexFunction inside theMEX-file, it issues an error message.When you invoke a MEX-file, MATLAB automatically seeds nlhs, plhs,nrhs, andprhs with the caller’s information. In the syntax of theMATLAB language, functions have the general form[a,b,c,...] = fun(d,e,f,...)2-38


mexFunction (C and <strong>Fortran</strong>)where the ... denotes more items of the same format. The a,b,c...are left-hand side arguments, and the d,e,f... are right-hand sidearguments. The arguments nlhs and nrhs contain the number ofleft-hand side and right-hand side arguments, respectively, with whichthe MEX-function is called. prhs is an array of mxArray pointers whoselength is nrhs. plhs is an array whose length is nlhs, whereyourfunction must set pointers for the returned left-hand side mxArrays.CExamplesSee mexfunction.c in the mex subdirectory of the examples directory.2-39


mexFunctionName (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReturnsDescriptionCExamplesName of current MEX-function#include "mex.h"const char *mexFunctionName(void);character*(*) mexFunctionName()The name of the current MEX-function.mexFunctionName returns the name of the current MEX-function.See mexgetarray.c in the mex subdirectory of the examples directory.2-40


mexGet (C)PurposeCSyntaxArgumentsReturnsDescriptionExamplesSee AlsoValue of specified Handle Graphics ® property#include "mex.h"const mxArray *mexGet(double handle, const char *property);handleHandle to a particular graphics objectpropertyA Handle Graphics propertyThe value of the specified property in the specified graphics object onsuccess. Returns NULL on failure. The return argument from mexGet isdeclared as constant, meaning that it is read only and should not bemodified. Changing the data in these mxArrays may produce undesiredside effects.Call mexGet to get the value of the property of a certain graphics object.mexGet is the API equivalent of the MATLAB get function. To set agraphics property value, call mexSet.See mexget.c in the mex subdirectory of the examples directory.mexSet2-41


mexGetVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCopy of variable from specified workspace#include "mex.h"mxArray *mexGetVariable(const char *workspace, const char*varname);mwPointer mexGetVariable(workspace, varname)character*(*) workspace, varnameworkspaceSpecifies where mexGetVariable should search in order to findarray varname. The possible values arebasecallerglobalSearch for the variable in the base workspace.Search for the variable in the caller’s workspace.Search for the variable in the global workspace.varnameNameofthevariabletocopyReturnsDescriptionCExamplesSee AlsoA copy of the variable on success. Returns NULL in C (0 on <strong>Fortran</strong>) onfailure. A common cause of failure is specifying a variable that is notcurrently in the workspace. Perhaps the variable was in the workspaceat one time but has since been cleared.Call mexGetVariable to get a copy of the specified variable. Thereturned mxArray contains a copy of all the data and characteristicsthat the variable had in the other workspace. Modifications to thereturned mxArray do not affect the variable in the workspace unless youwrite the copy back to the workspace with mexPutVariable.See mexgetarray.c in the mex subdirectory of the examples directory.mexGetVariablePtr, mexPutVariable2-42


mexGetVariablePtr (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsRead-only pointer to variable from another workspace#include "mex.h"const mxArray *mexGetVariablePtr(const char *workspace,const char *varname);mwPointer mexGetVariablePtr(workspace, varname)character*(*) workspace, varnameworkspaceSpecifies which workspace you want mexGetVariablePtr tosearch. The possible values arebasecallerglobalSearch for the variable in the base workspace.Search for the variable in the caller’s workspace.Search for the variable in the global workspace.varnameName of a variable in another workspace. This is a variable name,not an mxArray pointer.ReturnsDescriptionA read-only pointer to the mxArray on success. Returns NULL in C (0 in<strong>Fortran</strong>) on failure.Call mexGetVariablePtr to get a read-only pointer to the specifiedvariable, varname, into your MEX-file’s workspace. This command isuseful for examining an mxArray’s data and characteristics. If you needto change data or characteristics, use mexGetVariable (along withmexPutVariable) insteadofmexGetVariablePtr.If you simply need to examine data or characteristics,mexGetVariablePtr offers superior performance because the callerneeds to pass only a pointer to the array.2-43


mexGetVariablePtr (C and <strong>Fortran</strong>)CExamplesSee AlsoSee mxislogical.c in the mx subdirectory of the examples directory.mexGetVariable2-44


mexIsGlobal (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray has global scope#include "matrix.h"bool mexIsGlobal(const mxArray *pm);integer*4 mexIsGlobal(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) ifthemxArray has global scope, and logical 0 (false)otherwise.Use mexIsGlobal to determine whether the specified mxArray hasglobal scope.See mxislogical.c in the mx subdirectory of the examples directory.mexGetVariable, mexGetVariablePtr, mexPutVariable, global2-45


mexIsLocked (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReturnsDescriptionCExamplesSee AlsoDetermine whether MEX-file is locked#include "mex.h"bool mexIsLocked(void);integer*4 mexIsLocked()Logical 1 (true) iftheMEX-fileislocked;logical0 (false) ifthefileis unlocked.Call mexIsLocked todeterminewhethertheMEX-fileislocked. Bydefault, MEX-files are unlocked, meaning that users can clear theMEX-file at any time.To unlock a MEX-file, call mexUnlock.See mexlock.c in the mex subdirectory of the examples directory.mexLock, mexMakeArrayPersistent, mexMakeMemoryPersistent,mexUnlock2-46


mexLock (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDescriptionCExamplesSee AlsoPrevent MEX-file from being cleared from memory#include "mex.h"void mexLock(void);subroutine mexLock()By default, MEX-files are unlocked, meaning that a user can clear themat any time. Call mexLock to prohibit a MEX-file from being cleared.To unlock a MEX-file, you must call mexUnlock. Donotusethemunlockfunction.mexLock increments a lock count. If you call mexLock n times, you mustcall mexUnlock n times to unlock your MEX-file.See mexlock.c in the mex subdirectory of the examples directory.mexIsLocked, mexMakeArrayPersistent, mexMakeMemoryPersistent,mexUnlock2-47


mexMakeArrayPersistent (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxMake mxArray persist after MEX-file completes#include "mex.h"void mexMakeArrayPersistent(mxArray *pm);subroutine mexMakeArrayPersistent(pm)mwPointer pmArgumentspmPointer to an mxArray created by an mxCreate* functionDescriptionBy default, mxArrays allocated by mxCreate* functionsarenotpersistent. The MATLAB memory management facility automaticallyfrees nonpersistent mxArrays when the MEX-function finishes. Ifyou want the mxArray to persist through multiple invocations of theMEX-function, you must call mexMakeArrayPersistent.Note If you create a persistent mxArray, youareresponsiblefordestroying it when the MEX-file is cleared. If you do not destroy apersistent mxArray, MATLAB leaks memory. See mexAtExit to see howto register a function that gets calledwhentheMEX-fileiscleared.SeemexLock to see how to lock your MEX-file so that it is never cleared.See AlsomexAtExit, mexLock, mexMakeMemoryPersistent, andthemxCreate*functions2-48


mexMakeMemoryPersistent (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxMake allocated memory MATLAB persist after MEX-function completes#include "mex.h"void mexMakeMemoryPersistent(void *ptr);subroutine mexMakeMemoryPersistent(ptr)mwPointer ptrArgumentsptrPointer to the beginning of memory allocated by one of theMATLAB memory allocation routinesDescriptionBy default, memory allocated by MATLAB is nonpersistent, so it isfreed automatically when the MEX-function finishes. If you want thememory to persist, you must call mexMakeMemoryPersistent.Note If you create persistent memory, you are responsible for freeingit when the MEX-function is cleared. If you do not free the memory,MATLAB leaks memory. To free memory, use mxFree. SeemexAtExit tosee how to register a function that gets called when the MEX-functionis cleared. See mexLock to see how to lock your MEX-function so thatit is never cleared.See AlsomexAtExit, mexLock, mexMakeArrayPersistent, mxCalloc, mxFree,mxMalloc, mxRealloc2-49


mexPrintf (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionANSI C printf-style output routine#include "mex.h"int mexPrintf(const char *message, ...);integer*4 mexPrintf(message)character*(*) messagemessageString to be displayed. In C, the string may include formattingconversion characters, such as those used with the ANSI C printffunction....In C, any additional arguments needed to translate formattingconversion characters used in message. Each conversion characterin message is converted to one of these values.The number of characters printed. This includes characters specifiedwith backslash codes, such as \n and \b.This routine prints a string on the screen and in the diary (if the diaryis in use). It provides a callback to the standard C printf routinealready linked inside MATLAB, and avoids linking the entire stdiolibrary into your MEX-file.In a C MEX-file, you must call mexPrintf instead of printf to displayastring.Note If you want the literal % in your message, you must use %% in yourmessage string since % has special meaning to mexPrintf. Failingtodoso causes unpredictable results.2-50


mexPrintf (C and <strong>Fortran</strong>)CExamplesSee AlsoSee• mexfunction.c in the mex subdirectory of the examples directory• phonebook.c in the refbook subdirectory of the examples directory.mexErrMsgIdAndTxt, mexErrMsgTxt, mexWarnMsgIdAndTxt,mexWarnMsgTxt2-51


mexPutVariable (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCopy mxArray from MEX-function into specified workspace#include "mex.h"int mexPutVariable(const char *workspace, const char *varname,const mxArray *pm);integer*4 mexPutVariable(workspace, varname, pm)character*(*) workspace, varnamemwPointer pmworkspaceSpecifies the scope of the array that you are copying. The possiblevalues arebasecallerglobalCopy mxArray to the base workspace.Copy mxArray to the caller’s workspace.Copy mxArray to the list of global variables.varnameName given to the mxArray in the workspacepmPointer to the mxArrayReturnsDescription0 on success; 1 on failure. A possible cause of failure is that pm is NULLin C (0 in <strong>Fortran</strong>).Call mexPutVariable to copy the mxArray, atpointerpm, fromyourMEX-function into the specified workspace. MATLAB gives the name,varname, tothecopiedmxArray in the receiving workspace.mexPutVariable makes the array accessible to other entities, such asMATLAB, M-files, or other MEX-functions.If a variable of the same name already exists in the specified workspace,mexPutVariable overwrites the previous contents of the variable with2-52


mexPutVariable (C and <strong>Fortran</strong>)the contents of the new mxArray. For example, suppose the MATLABworkspace defines variable Peaches asPeaches1 2 3 4and you call mexPutVariable to copy Peaches into the same workspace:mexPutVariable("base", "Peaches", pm)Then the old value of Peaches disappears and is replaced by the valuepassed in by mexPutVariable.CExamplesSee AlsoSee mexgetarray.c in the mex subdirectory of the examples directory.mexGetVariable2-53


mexSet (C)PurposeCSyntaxArgumentsReturnsSet value of specified Handle Graphics property#include "mex.h"int mexSet(double handle, const char *property,mxArray *value);handleHandle to a particular graphics objectpropertyString naming a Handle Graphics propertyvaluePointer to an mxArray holding the new value to assign to theproperty0 on success; 1 on failure. Possible causes of failure include:• Specifying a nonexistent property.• Specifying an illegal value for that property, for example, specifying astring value for a numerical property.DescriptionExamplesSee AlsoCall mexSet to set the value of the property of a certain graphics object.mexSet is the API equivalent of the MATLAB set function. To get thevalue of a graphics property, call mexGet.See mexget.c in the mex subdirectory of the examples directory.mexGet2-54


mexSetTrapFlag (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsControl response of mexCallMATLAB to errors#include "mex.h"void mexSetTrapFlag(int trapflag);subroutine mexSetTrapFlag(trapflag)integer*4 trapflagtrapflagControl flag. Possible values are0 On error, control returns to the MATLAB prompt.1 On error, control returns to your MEX-file.DescriptionCall mexSetTrapFlag to control the MATLAB response to errors inmexCallMATLAB.If you do not call mexSetTrapFlag, then whenever MATLAB detects anerror in a call to mexCallMATLAB, MATLAB automatically terminatesthe MEX-file and returns control to the MATLAB prompt. CallingmexSetTrapFlag with trapflag set to 0 is equivalent to not callingmexSetTrapFlag at all.If you call mexSetTrapFlag and set the trapflag to 1, then wheneverMATLAB detects an error in a call to mexCallMATLAB, MATLAB doesnot automatically terminate the MEX-file. Rather, MATLAB returnscontrol to the line in the MEX-file immediately following the callto mexCallMATLAB. The MEX-file is then responsible for taking anappropriate response to the error.If you call mexSetTrapFlag, thevalueofthetrapflag you set remainsin effect until the next call to mexSetTrapFlag within that MEX-file or,if there are no more calls to mexSetTrapFlag, until the MEX-file exits.If a routine defined in a MEX-file calls another MEX-file,1 The current value of the trapflag in the first MEX-file is saved.2-55


mexSetTrapFlag (C and <strong>Fortran</strong>)2 The second MEX-file is called with the trapflag initialized to 0within that file.3 When the second MEX-file exits, the saved value of the trapflag inthe first MEX-file is restored within that file.CExamplesSee AlsoSee mexsettrapflag.c in the mex subdirectory of the examplesdirectory.mexAtExit, mexErrMsgTxt2-56


mexUnlock (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDescriptionCExamplesSee AlsoAllowMEX-filetobeclearedfrommemory#include "mex.h"void mexUnlock(void);subroutine mexUnlock()By default, MEX-files are unlocked, meaning that a user can clearthem at any time. Calling mexLock locks a MEX-file so that it cannotbe cleared. Calling mexUnlock removes the lock so that the MEX-filecan be cleared.mexLock increments a lock count. If you called mexLock n times, youmust call mexUnlock n times to unlock your MEX-file.See mexlock.c in the mex subdirectory of the examples directory.mexIsLocked, mexLock, mexMakeArrayPersistent,mexMakeMemoryPersistent2-57


mexWarnMsgIdAndTxt (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxIssue warning message with identifier#include "mex.h"void mexWarnMsgIdAndTxt(const char *warningid,const char *warningmsg, ...);subroutine mexWarnMsgIdAndTxt(warningid, warningmsg)character*(*) warningid, warningmsgArgumentsDescriptionSee AlsowarningidString containing a MATLAB message identifier. See “MessageIdentifiers” in the MATLAB documentation for information onthis topic.warningmsgString containing the warning message to be displayed. In C,the string may include formatting conversion characters, such asthose used with the ANSI C sprintf function....In C, any additional arguments needed to translate formattingconversion characters used in warningmsg. Each conversioncharacter in warningmsg is converted to one of these values.Call mexWarnMsgIdAndTxt to write a warning message and itscorresponding identifier to the MATLAB window.Unlike mexErrMsgIdAndTxt, mexWarnMsgIdAndTxt does not cause theMEX-file to terminate.mexErrMsgTxt, mexErrMsgIdAndTxt, mexWarnMsgTxt2-58


mexWarnMsgTxt (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionCExamplesIssue warning message#include "mex.h"void mexWarnMsgTxt(const char *warningmsg);subroutine mexWarnMsgTxt(warningmsg)character*(*) warningmsgwarningmsgString containing the warning message to be displayedmexWarnMsgTxt causesMATLABtodisplaythecontentsofwarningmsg.Unlike mexErrMsgTxt, mexWarnMsgTxt does not cause the MEX-file toterminate.See yprime.c in the mex subdirectory of the examples directory.Additional examples:• explore.c in the mex subdirectory of the examples directory• fulltosparse.c in the refbook subdirectory of the examplesdirectory• mxisfinite.c and mxsetnzmax.c in the mx subdirectory of theexamples directorySee AlsomexErrMsgTxt, mexErrMsgIdAndTxt, mexWarnMsgIdAndTxt2-59


mwIndex (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDescriptionSee AlsoType for index values#include "matrix.h"#include "fintrf.h"mwIndex is a type that represents index values, such as indices intoarrays. This function is provided for purposes of cross-platformflexibility. By default, mwIndex is equivalent to int in C. When usingthe mex -largeArrayDims switch, mwIndex is equivalent to size_t inC. mwIndex is equivalent to INTEGER*4 in <strong>Fortran</strong>.In <strong>Fortran</strong>, mwIndex is implemented as a preprocessor macro.mex, mwSize2-60


mwPointer (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxDescriptionExamplesDeclare appropriate pointer type for platform#include "fintrf.h"mwPointer is a preprocessor macro that declares the appropriate<strong>Fortran</strong> type representing a pointer to an mxArray or to other datathat is not of a native <strong>Fortran</strong> type, such as memory allocated bymxMalloc. On 32-bit platforms, the <strong>Fortran</strong> type that represents apointer is INTEGER*4; on 64-bit platforms, it is INTEGER*8. The <strong>Fortran</strong>preprocessor translates mwPointer to the <strong>Fortran</strong> declaration that isappropriate for the platform on which you compile your file.If your <strong>Fortran</strong> compiler supports preprocessing, you can use mwPointerto declare functions, arguments, and variables that represent pointers.If you cannot use mwPointer, you must ensure that your declarationshave the correct size for the platform on which you are compiling<strong>Fortran</strong> code.This example declares the arguments for mexFunction in a <strong>Fortran</strong>MEX-file:SUBROUTINE MEXFUNCTION(NLHS, PLHS, NRHS, PRHS)MWPOINTER PLHS(*), PRHS(*)INTEGER NLHS, NRHSFor additional examples, see the <strong>Fortran</strong> files with names ending in.F in the $MATLAB/extern/examples directory, where $MATLAB is thestring returned by the matlabroot command.2-61


mwSize (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDescriptionSee AlsoType for size values#include "matrix.h"#include "fintrf.h"mwSize isatypethatrepresentssizevalues, such as array dimensions.This function is provided for purposes of cross-platform flexibility.By default, mwIndex is equivalent to int in C. When using the mex-largeArrayDims switch, mwSize is equivalent to size_t in C. mwIndexis equivalent to INTEGER*4 in <strong>Fortran</strong>.In <strong>Fortran</strong>, mwSize is implemented as a preprocessor macro.mex, mwIndex2-62


mxAddField (C and <strong>Fortran</strong>)PurposeCSyntaxAdd field to structure array#include "matrix.h"extern int mxAddField(mxArray pm, const char *fieldname);<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionSee Alsointeger*4 mxAddField(pm, fieldname)mwPointer pmcharacter*(*) fieldnamepmPointer to a structure mxArrayfieldnameThenameofthefieldyouwanttoaddField number on success or -1 if inputs are invalid or an out-of-memorycondition occurs.Call mxAddField to add a field to a structure array. You must then createthe values with the mxCreate* functions and use mxSetFieldByNumberto set the individual values for the field.mxRemoveField, mxSetFieldByNumber2-63


mxArrayToString (C)PurposeCSyntaxConvert array to string#include "matrix.h"char *mxArrayToString(const mxArray *array_ptr);ArgumentsReturnsDescriptionarray_ptrPointer to a string mxArray; thatis,apointertoanmxArrayhaving the mxCHAR_CLASS class.A C-style string. Returns NULL on out of memory.Call mxArrayToString to copy the character data of a string mxArrayinto a C-style string. The C-style string is always terminated with aNULL character.Ifthestringarraycontainsseveralrows, they are copied, one columnat a time, into one long string array. This function is similar tomxGetString, exceptthat• It does not require the length of the string as an input.• It supports multibyte character sets.mxArrayToString does not free the dynamic memory that the charpointer points to. Consequently, you should typically free the string(using mxFree) immediately after you have finished using it.ExamplesSee AlsoSee mexatexit.c in the mex subdirectory of the examples directory.For additional examples, see mxcreatecharmatrixfromstr.c andmxislogical.c in the mx subdirectory of the examples directory.mxCreateCharArray, mxCreateCharMatrixFromStrings,mxCreateString, mxGetString2-64


mxAssert (C)PurposeCSyntaxCheck assertion value for debugging purposes#include "matrix.h"void mxAssert(int expr, char *error_message);ArgumentsDescriptionexprValue of assertionerror_messageDescription of why assertion failedSimilar to the ANSI C assert() macro, mxAssert checks the valueof an assertion, and continues execution only if the assertion holds.If expr evaluates to logical 1 (true), mxAssert does nothing. If exprevaluates to logical 0 (false), mxAssert prints an error to the MATLABcommand window consisting of the failed assertion’s expression, thefilename and line number where the failed assertion occurred, and theerror_message string. The error_message string allows you to specifya better description of why the assertionfailed.Useanemptystringifyou don’t want a description to follow the failed assertion message.After a failed assertion, control returns to the MATLAB command line.Note that the MEX script turns off these assertions when buildingoptimized MEX-functions, so use this for debugging purposes only.Build the MEX-file using the syntax mex -g filename in order touse mxAssert.Assertions are a way of maintaining internal consistency of logic. Usethem to keep yourself from misusing your own code and to preventlogical errors from propagating before they are caught; do not useassertions to prevent users of your code from misusing it.Assertions can be taken out of your code by the C preprocessor. You canuse these checks during development and then remove them when thecode works properly, letting you use them for troubleshooting duringdevelopment without slowing down the final product.2-65


mxAssertS (C)PurposeCSyntaxCheck assertion value without printing assertion text#include "matrix.h"void mxAssertS(int expr, char *error_message);ArgumentsDescriptionexprValue of assertionerror_messageDescription of why assertion failedmxAssertS is similar to mxAssert, exceptmxAssertS does not print thetext of the failed assertion. mxAssertS checks the value of an assertion,and continues execution only if the assertion holds. If expr evaluates tological 1 (true), mxAssertS does nothing. If expr evaluates to logical 0(false), mxAssertS prints an error to the MATLAB command windowconsisting of the filename and line number where the assertion failedand the error_message string. The error_message string allows you tospecify a better description of why the assertion failed. Use an emptystring if you don’t want a description to follow the failed assertionmessage.After a failed assertion, control returns to the MATLAB command line.Note that the mex script turns off these assertions when buildingoptimized MEX-functions, so use this for debugging purposes only.Build the MEX-file using the syntaxmex -g filename in order to usemxAssert.2-66


mxCalcSingleSubscript (C and <strong>Fortran</strong>)PurposeCSyntaxOffset from first element to desired element#include mwIndex mxCalcSingleSubscript(const mxArray *pm, mwSize nsubs,mwIndex *subs);<strong>Fortran</strong>SyntaxArgumentsmwIndex mxCalcSingleSubscript(pm, nsubs, subs)mwPointer pmmwSize nsubsmwIndex subspmPointer to an mxArraynsubsThe number of elements in the subs array. Typically, you setnsubs equal to the number of dimensions in the mxArray thatpm points to.subsAn array of integers. Each value in the array should specify thatdimension’s subscript. In C syntax, the value in subs[0] specifiesthe row subscript, and the value in subs[1] specifies the columnsubscript. Use zero-based indexing for subscripts. For example,to express the starting element of a two-dimensional mxArray insubs, setsubs[0] to 0 and subs[1] to 0.In <strong>Fortran</strong> syntax, the value in subs(1) specifies the rowsubscript, and the value in subs(2) specifies the columnsubscript. Use 1-based indexing for subscripts. For example, toexpress the starting element of a two-dimensional mxArray insubs, setsubs(1) to 1 and subs(2) to 1.ReturnsThe number of elements between the start of the mxArray and thespecified subscript. This returned number is called an index; manymxroutines (for example, mxGetField) require an index as an argument.2-67


mxCalcSingleSubscript (C and <strong>Fortran</strong>)If subs describes the starting element of an mxArray,mxCalcSingleSubscript returns 0. If subs describes the final elementof an mxArray, mxCalcSingleSubscript returns N-1 (where N is thetotal number of elements).DescriptionCall mxCalcSingleSubscript to determine how many elementsthere are between the beginning of the mxArray and a givenelement of that mxArray. For example, given a subscript like (5,7),mxCalcSingleSubscript returns the distance from the first element ofthe array to the (5,7) element. Remember that the mxArray data typeinternally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have.MATLAB uses a column-major numbering scheme to represent dataelements internally. That means that MATLAB internally stores dataelements from the first column first, then data elements from thesecond column second, and so on through the last column. For example,suppose you create a 4-by-2 variable. It is helpful to visualize the dataas follows.ABCDEFGHIn fact, though, MATLAB internally represents the data as thefollowing:A B C D E F G HIndex0Index1Index2Index3Index4Index5Index6Index7If an mxArray is N-dimensional, MATLAB represents the data inN-major order. For example, consider a three-dimensional array havingdimensions 4-by-2-by-3. Although you can visualize the data as2-68


mxCalcSingleSubscript (C and <strong>Fortran</strong>)MATLAB internally represents the data for this three-dimensionalarray in the following order:A B C D E F G H I J K L M N O P Q R S T U V W X0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23Avoid using mxCalcSingleSubscript to traverse the elements of anarray. In C, it is more efficient to do this by finding the array’s startingaddress and then using pointer auto-incrementing to access successiveelements. For example, to find the starting address of a numericalarray, call mxGetPr or mxGetPi.CExamplesSee AlsoSee mxcalcsinglesubscript.c in the mx subdirectory of the examplesdirectory.mxGetCell, mxSetCell2-69


mxCalloc (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionAllocate dynamic memory for array using MATLAB memory manager#include "matrix.h"#include void *mxCalloc(size_t n, size_t size);mwPointer mxCalloc(n, size)mwSize n, sizensizeNumber of elements to allocate. This must be a nonnegativenumber.Number of bytes per element. (The C sizeof operator calculatesthenumberofbytesperelement.)A pointer to the start of the allocated dynamic memory, if successful.If unsuccessful in a stand-alone (non-MEX-file) application, mxCallocreturns NULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, theMEX-file terminates and control returns to the MATLAB prompt.mxCalloc is unsuccessful when there is insufficient free heap space.MATLAB applications should always call mxCalloc rather than callocto allocate memory. Note that mxCalloc works differently in MEX-filesthan in stand-alone MATLAB applications.In MEX-files, mxCalloc automatically• Allocates enough contiguous heap space to hold n elements.• Initializes all n elements to 0.• Registers the returned heap space with the MATLAB memorymanagement facility.2-70


mxCalloc (C and <strong>Fortran</strong>)The MATLAB memory management facility maintains a list of allmemory allocated by mxCalloc. The MATLAB memory managementfacility automatically frees (deallocates) all of a MEX-file’s parcels whencontrol returns to the MATLAB prompt.In stand-alone MATLAB C applications, mxCalloc calls the ANSI Ccalloc function.By default, in a MEX-file, mxCalloc generates nonpersistentmxCalloc data. In other words, the memory management facilityautomatically deallocates the memoryassoonastheMEX-fileends.If you want the memory to persist after the MEX-file completes, callmexMakeMemoryPersistent after calling mxCalloc. If you write aMEX-file with persistent memory, be sure to register a mexAtExitfunction to free allocated memory in the event your MEX-file is cleared.When you finish using the memory allocated by mxCalloc, callmxFree.mxFree deallocates the memory.CExamplesSee• explore.c in the mex subdirectory of the examples directory• phonebook.c and revord.c in the refbook subdirectory of theexamples directoryFor additional examples, see mxcalcsinglesubscript.c andmxsetdimensions.c in the mx subdirectory of the examples directory.See AlsomexAtExit, mexMakeArrayPersistent, mexMakeMemoryPersistent,mxDestroyArray, mxFree, mxMalloc, mxRealloc2-71


mxChar (C)PurposeCSyntaxDescriptionExamplesData type for string mxArraytypedef Uint16 mxChar;All string mxArrays storetheirdataelementsasmxChar rather than aschar. The MATLAB API defines an mxChar as a 16-bit unsigned integer.See mxmalloc.c in the mx subdirectory of the examples directory.Additional examples:• explore.c in the mex subdirectory of the examples directory• mxcreatecharmatrixfromstr.c in the mx subdirectory of theexamples directorySee AlsomxCreateCharArray2-72


mxClassID (C)PurposeInteger value identifying class of mxArrayCSyntax typedef enum {mxUNKNOWN_CLASS = 0,mxCELL_CLASS,mxSTRUCT_CLASS,mxLOGICAL_CLASS,mxCHAR_CLASS,,mxDOUBLE_CLASS,mxSINGLE_CLASS,mxINT8_CLASS,mxUINT8_CLASS,mxINT16_CLASS,mxUINT16_CLASS,mxINT32_CLASS,mxUINT32_CLASS,mxINT64_CLASS,mxUINT64_CLASS,mxFUNCTION_CLASS} mxClassID;ConstantsmxUNKNOWN_CLASSThe class cannot be determined. You cannot specify this categoryfor an mxArray; however, mxGetClassID can return this valueif it cannot identify the class.mxCELL_CLASSIdentifies a cell mxArray.mxSTRUCT_CLASSIdentifies a structure mxArray.mxLOGICAL_CLASSIdentifies a logical mxArray, anmxArray that stores Booleanelements logical 1 (true) andlogical0 (false).2-73


mxClassID (C)mxCHAR_CLASSIdentifies a string mxArray, anmxArray whose data is representedas mxCHAR’s.mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored asdouble-precision, floating-point numbers.mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored assingle-precision, floating-point numbers.mxINT8_CLASSIdentifies a numeric mxArray whosedataisstoredassigned8-bitintegers.mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as unsigned8-bit integers.mxINT16_CLASSIdentifies a numeric mxArray whosedataisstoredassigned16-bit integers.mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as unsigned16-bit integers.mxINT32_CLASSIdentifies a numeric mxArray whosedataisstoredassigned32-bit integers.mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as unsigned32-bit integers.mxINT64_CLASSIdentifies a numeric mxArray whosedataisstoredassigned64-bit integers.2-74


mxClassID (C)mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as unsigned64-bit integers.mxFUNCTION_CLASSIdentifies a function handle mxArray.DescriptionExamplesSee AlsoVarious mx* calls require or return an mxClassID argument. mxClassIDidentifies the way in which the mxArray represents its data elements.See explore.c in the mex subdirectory of the examples directory.mxCreateNumericArray2-75


mxClassIDFromClassName (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionIdentifier corresponding to classinteger*4 mxClassIDFromClassName(classname)character*(*) classnameclassnameA character array specifying a MATLAB class name. Use one ofthe strings from the following table.A numeric identifier used internally by MATLAB to represent theMATLAB class, classname. Returns0 if classname is not a recognizedMATLAB class.Use mxClassIDFromClassName to obtain an identifier for any classthat is recognized by MATLAB. This function is most commonlyused to provide a classid argument to mxCreateNumericArray andmxCreateNumericMatrix.Valid choices for classname are listed in the following table. MATLABreturns 0 if classname is unrecognized.cell char double function_handleint8 int16 int32 logicalobject single struct uint8uint16uint32See AlsomxGetClassName, mxCreateNumericArray, mxCreateNumericMatrix2-76


mxComplexity (C)PurposeCSyntaxConstantsDescriptionExamplesSee AlsoFlag specifying whether mxArray has imaginary componentstypedef enum mxComplexity {mxREAL=0, mxCOMPLEX};mxREALIdentifies an mxArray with no imaginary components.mxCOMPLEXIdentifies an mxArray with imaginary components.Various mx* calls require an mxComplexity argument. You can set anmxComplex argument to either mxREAL or mxCOMPLEX.See mxcalcsinglesubscript.c in the mx subdirectory of the examplesdirectory.mxCreateNumericArray, mxCreateDoubleMatrix, mxCreateSparse2-77


mxCopyCharacterToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy character values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyCharacterToPtr(y, px, n)character*(*) ymwPointer pxmwSize nArgumentsypxncharacter <strong>Fortran</strong> arrayPointer to character or name arrayNumber of elements to copyDescriptionSee AlsomxCopyCharacterToPtr copies n character values from the <strong>Fortran</strong>character array y into the MATLAB string array pointed to by px. Thissubroutine is essential for copying character data between MATLABpointer arrays and ordinary <strong>Fortran</strong> character arrays.mxCopyPtrToCharacter, mxCreateCharArray, mxCreateString,mxCreateCharMatrixFromStrings2-78


mxCopyComplex16ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy COMPLEX*16 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyComplex16ToPtr(y, pr, pi, n)complex*16 y(n)mwPointer pr, pimwSize nArgumentsyprpinCOMPLEX*16 <strong>Fortran</strong> arrayPointer to the real data of a double-precision MATLAB arrayPointer to the imaginary data of a double-precision MATLABarrayNumber of elements to copyDescriptionSee AlsomxCopyComplex16ToPtr copies n COMPLEX*16 values from the <strong>Fortran</strong>COMPLEX*16 array y into the MATLAB arrays pointed to by pr and pi.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.mxCopyPtrToComplex16, mxCreateNumericArray,mxCreateNumericMatrix, mxGetData, mxGetImagData2-79


mxCopyComplex8ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy COMPLEX*8 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyComplex8ToPtr(y, pr, pi, n)complex*8 y(n)mwPointer pr, pimwSize nArgumentsyprpinCOMPLEX*8 <strong>Fortran</strong> arrayPointer to the real data of a single-precision MATLAB arrayPointer to the imaginary data of a single-precision MATLAB arrayNumber of elements to copyDescriptionSee AlsomxCopyComplex8ToPtr copies n COMPLEX*8 values from the <strong>Fortran</strong>COMPLEX*8 array y into the MATLAB arrays pointed to by pr and pi.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.mxCopyPtrToComplex8, mxCreateNumericArray,mxCreateNumericMatrix, mxGetData, mxGetImagData2-80


mxCopyInteger1ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*1 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyInteger1ToPtr(y, px, n)integer*1 y(n)mwPointer pxmwSize nArgumentsypxnINTEGER*1 <strong>Fortran</strong> arrayPointer to ir or jc arrayNumber of elements to copyDescriptionmxCopyInteger1ToPtr copies n INTEGER*1 values from the <strong>Fortran</strong>INTEGER*1 array y into the MATLAB array pointed to by px, eitheran ir or jc array. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyPtrToInteger1, mxCreateNumericArray,mxCreateNumericMatrix2-81


mxCopyInteger2ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*2 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyInteger2ToPtr(y, px, n)integer*2 y(n)mwPointer pxmwSize nArgumentsypxnINTEGER*2 <strong>Fortran</strong> arrayPointer to ir or jc arrayNumber of elements to copyDescriptionmxCopyInteger2ToPtr copies n INTEGER*2 values from the <strong>Fortran</strong>INTEGER*2 array y into the MATLAB array pointed to by px, eitheran ir or jc array. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyPtrToInteger2, mxCreateNumericArray,mxCreateNumericMatrix2-82


mxCopyInteger4ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*4 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyInteger4ToPtr(y, px, n)integer*4 y(n)mwPointer pxmwSize nArgumentsypxnINTEGER*4 <strong>Fortran</strong> arrayPointer to ir or jc arrayNumber of elements to copyDescriptionmxCopyInteger4ToPtr copies n INTEGER*4 values from the <strong>Fortran</strong>INTEGER*4 array y into the MATLAB array pointed to by px, eitheran ir or jc array. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyPtrToInteger4, mxCreateNumericArray,mxCreateNumericMatrix2-83


mxCopyPtrToCharacter (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy character values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToCharacter(px, y, n)mwPointer pxcharacter*(*) ymwSize nArgumentspxynPointer to character or name arraycharacter <strong>Fortran</strong> arrayNumber of elements to copyDescriptionExamplesSee AlsomxCopyPtrToCharacter copies n character values from the MATLABarray pointed to by px into the <strong>Fortran</strong> character array y. Thissubroutine is essential for copying character data from MATLABpointer arrays into ordinary <strong>Fortran</strong> character arrays.See matdemo2.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.mxCopyCharacterToPtr, mxCreateCharArray, mxCreateString,mxCreateCharMatrixFromStrings2-84


mxCopyPtrToComplex16 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy COMPLEX*16 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToComplex16(pr, pi, y, n)mwPointer pr, picomplex*16 y(n)mwSize nArgumentsprpiynPointer to the real data of a double-precision MATLAB arrayPointer to the imaginary data of a double-precision MATLABarrayCOMPLEX*16 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionSee AlsomxCopyPtrToComplex16 copies n COMPLEX*16 values from the MATLABarrays pointed to by pr and pi into the <strong>Fortran</strong> COMPLEX*16 array y.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.mxCopyComplex16ToPtr, mxCreateNumericArray,mxCreateNumericMatrix, mxGetData, mxGetImagData2-85


mxCopyPtrToComplex8 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy COMPLEX*8 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToComplex8(pr, pi, y, n)mwPointer pr, picomplex*8 y(n)mwSize nArgumentsprpiynPointer to the real data of a single-precision MATLAB arrayPointer to the imaginary data of a single-precision MATLAB arrayCOMPLEX*8 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionSee AlsomxCopyPtrToComplex8 copies n COMPLEX*8 values from the MATLABarrays pointed to by pr and pi into the <strong>Fortran</strong> COMPLEX*8 array y.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.mxCopyComplex8ToPtr, mxCreateNumericArray,mxCreateNumericMatrix, mxGetData, mxGetImagData2-86


mxCopyPtrToInteger1 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*1 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToInteger1(px, y, n)mwPointer pxinteger*1 y(n)mwSize nArgumentspxynPointer to ir or jc arrayINTEGER*1 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionmxCopyPtrToInteger1 copies n INTEGER*1 values from the MATLABarray pointed to by px, eitheranir or jc array, into the <strong>Fortran</strong>INTEGER*1 array y. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyInteger1ToPtr, mxCreateNumericArray,mxCreateNumericMatrix2-87


mxCopyPtrToInteger2 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*2 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToInteger2(px, y, n)mwPointer pxinteger*2 y(n)mwSize nArgumentspxynPointer to ir or jc arrayINTEGER*2 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionmxCopyPtrToInteger2 copies n INTEGER*2 values from the MATLABarray pointed to by px, eitheranir or jc array, into the <strong>Fortran</strong>INTEGER*2 array y. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyInteger2ToPtr, mxCreateNumericArray,mxCreateNumericMatrix2-88


mxCopyPtrToInteger4 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy INTEGER*4 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToInteger4(px, y, n)mwPointer pxinteger*4 y(n)mwSize nArgumentspxynPointer to ir or jc arrayINTEGER*4 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionmxCopyPtrToInteger4 copies n INTEGER*4 values from the MATLABarray pointed to by px, eitheranir or jc array, into the <strong>Fortran</strong>INTEGER*4 array y. This subroutine is essential for use with <strong>Fortran</strong>compilers that do not support the %VAL construct in order to set upstandard <strong>Fortran</strong> arrays for passing as arguments to the computationroutine of a MEX-file.Note This function can only be used with sparse matrices.See AlsomxCopyInteger4ToPtr, mxCreateNumericArray,mxCreateNumericMatrix2-89


mxCopyPtrToPtrArray (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy pointer values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToPtrArray(px, y, n)mwPointer pxmwPointer y(n)mwSize nArgumentspxynPointer to pointer array<strong>Fortran</strong> array of mwPointer valuesNumber of pointers to copyDescriptionExamplesSee AlsomxCopyPtrToPtrArray copies n pointers from the MATLAB arraypointed to by px into the <strong>Fortran</strong> array y. This subroutine is essentialfor copying the output of matGetDir into an array of pointers. Aftercalling this function, each element of y contains a pointer to a string.You can convert these strings to <strong>Fortran</strong> character arrays by passingeach element of y as the first argument to mxCopyPtrToCharacter.See matdemo2.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.matGetDir, mxCopyPtrToCharacter2-90


mxCopyPtrToReal4 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy REAL*4 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToReal4(px, y, n)mwPointer pxreal*4 y(n)mwSize nArgumentspxynPointer to the real or imaginary data of a single-precisionMATLAB arrayREAL*4 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionSee AlsomxCopyPtrToReal4 copies n REAL*4 values from the MATLAB arraypointed to by px, eitherapr or pi array, into the <strong>Fortran</strong> REAL*4 array y.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.mxCopyReal4ToPtr, mxCreateNumericArray, mxCreateNumericMatrix,mxGetData, mxGetImagData2-91


mxCopyPtrToReal8 (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy REAL*8 values from pointer array to <strong>Fortran</strong> arraysubroutine mxCopyPtrToReal8(px, y, n)mwPointer pxreal*8 y(n)mwSize nArgumentspxynPointer to the real or imaginary data of a double-precisionMATLAB arrayREAL*8 <strong>Fortran</strong> arrayNumber of elements to copyDescriptionExamplesSee AlsomxCopyPtrToReal8 copies n REAL*8 values from the MATLAB arraypointed to by px, eitherapr or pi array, into the <strong>Fortran</strong> REAL*8 array y.This subroutine is essential for use with <strong>Fortran</strong> compilers that do notsupport the %VAL construct in order to set up standard <strong>Fortran</strong> arraysfor passing as arguments to the computation routine of a MEX-file.See fengdemo.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.mxCopyReal8ToPtr, mxCreateNumericArray, mxCreateNumericMatrix,mxGetData, mxGetImagData2-92


mxCopyReal4ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy REAL*4 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyReal4ToPtr(y, px, n)real*4 y(n)mwPointer pxmwSize nArgumentsypxnREAL*4 <strong>Fortran</strong> arrayPointer to the real or imaginary data of a single-precisionMATLAB arrayNumber of elements to copyDescriptionSee AlsomxCopyReal4ToPtr(y,px,n) copies n REAL*4 values from the <strong>Fortran</strong>REAL*4 array y into the MATLAB array pointed to by px, eitherapr orpi array. This subroutine is essential for use with <strong>Fortran</strong> compilersthat do not support the %VAL construct in order to set up standard<strong>Fortran</strong> arrays for passing as arguments to the computation routine ofaMEX-file.mxCopyPtrToReal4, mxCreateNumericArray, mxCreateNumericMatrix,mxGetData, mxGetImagData2-93


mxCopyReal8ToPtr (<strong>Fortran</strong>)Purpose<strong>Fortran</strong>SyntaxCopy REAL*8 values from <strong>Fortran</strong> array to pointer arraysubroutine mxCopyReal8ToPtr(y, px, n)real*8 y(n)mwPointer pxmwSize nArgumentsypxnREAL*8 <strong>Fortran</strong> arrayPointer to the real or imaginary data of a double-precisionMATLAB arrayNumber of elements to copyDescriptionExamplesSee AlsomxCopyReal8ToPtr(y,px,n) copies n REAL*8 values from the <strong>Fortran</strong>REAL*8 array y into the MATLAB array pointed to by px, eitherapr orpi array. This subroutine is essential for use with <strong>Fortran</strong> compilersthat do not support the %VAL construct in order to set up standard<strong>Fortran</strong> arrays for passing as arguments to the computation routine ofaMEX-file.See matdemo1.F and fengdemo.F in the eng_mat subdirectory of theexamples directory for a sample program that illustrates how to usethis routine in a <strong>Fortran</strong> program.mxCopyPtrToReal8, mxCreateNumericArray, mxCreateNumericMatrix,mxGetData, mxGetImagData2-94


mxCreateCellArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCreate unpopulated N-D cell mxArray#include "matrix.h"mxArray *mxCreateCellArray(mwSize ndim, const mwSize *dims);mwPointer mxCreateCellArray(ndim, dims)mwSize ndim, dimsndimThe desired number of dimensions in the created cell. Forexample, to create a three-dimensional cell mxArray, setndim to 3.dimsThe dimensions array. Each element in the dimensions arraycontainsthesizeofthemxArray in that dimension. For example,in C, setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. In <strong>Fortran</strong>, setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray. In most cases, there should be ndimelements in the dims array.ReturnsDescriptionA pointer to the created cell mxArray, if successful. If unsuccessful ina stand-alone (nonMEX-file) application, mxCreateCellArray returnsNULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, the MEX-fileterminates and control returns to the MATLAB prompt. The mostcommon cause of failure is insufficient free heap space.Use mxCreateCellArray to create a cell mxArray whose size is definedby ndim and dims. For example, in C, to establish a three-dimensionalcell mxArray having dimensions 4-by-8-by-7, setndim = 3;dims[0] = 4; dims[1] = 8; dims[2] = 7;In <strong>Fortran</strong>, to establish a three-dimensional cell mxArray havingdimensions 4-by-8-by-7, setndim = 3;2-95


mxCreateCellArray (C and <strong>Fortran</strong>)dims(1) = 4; dims(2) = 8; dims(3) = 7;The created cell mxArray is unpopulated; mxCreateCellArray initializeseach cell to NULL. To put data into a cell, call mxSetCell.Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.CExamplesSee AlsoSee phonebook.c in the refbook subdirectory of the examples directory.mxCreateCellMatrix, mxGetCell, mxSetCell, mxIsCell2-96


mxCreateCellMatrix (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCreate unpopulated 2-D cell mxArray#include "matrix.h"mxArray *mxCreateCellMatrix(mwSize m, mwSize n);mwPointer mxCreateCellMatrix(m, n)mwSize m, nArgumentsmnThe desired number of rowsThe desired number of columnsReturnsDescriptionCExamplesSee AlsoA pointer to the created cell mxArray, if successful. If unsuccessful in astand-alone (non-MEX-file) application, mxCreateCellMatrix returnsNULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, the MEX-fileterminates and control returns to the MATLAB prompt. Insufficientfree heap space is the only reason for mxCreateCellMatrix to beunsuccessful.Use mxCreateCellMatrix to create an m-by-n two-dimensional cellmxArray. The created cell mxArray is unpopulated; mxCreateCellMatrixinitializes each cell to NULL in C (0 in <strong>Fortran</strong>). To put data into cells,call mxSetCell.mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only,but mxCreateCellArray can create mxArrays having any number ofdimensions greater than 1.See mxcreatecellmatrix.c in the mx subdirectory of the examplesdirectory.mxCreateCellArray2-97


mxCreateCharArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCreate unpopulated N-D string mxArray#include "matrix.h"mxArray *mxCreateCharArray(mwSize ndim, const mwSize *dims);mwPointer mxCreateCharArray(ndim, dims)mwSize ndim, dimsndimThe desired number of dimensions in the string mxArray.You must specify a positive number. If you specify 0, 1, or 2,mxCreateCharArray creates a two-dimensional mxArray.dimsThe dimensions array. Each element in the dimensions arraycontains the size of the array in that dimension. For example,in C, setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. In <strong>Fortran</strong>, setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray. The dims array musthave at least ndim elements.ReturnsDescriptionA pointer to the created string mxArray, if successful. If unsuccessfulin a stand-alone (non-MEX-file) application, mxCreateCharArrayreturns NULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, theMEX-file terminates and control returns to the MATLAB prompt.Insufficient free heap space is the only reason for mxCreateCharArrayto be unsuccessful.Call mxCreateCharArray to create an N-dimensional string mxArray.The created mxArray is unpopulated; that is, mxCreateCharArrayinitializes each cell to NULL in C (0 in <strong>Fortran</strong>).Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.2-98


mxCreateCharArray (C and <strong>Fortran</strong>)CExamplesSee AlsoSee mxcreatecharmatrixfromstr.c in the mx subdirectory of theexamples directory.mxCreateCharMatrixFromStrings, mxCreateString2-99


mxCreateCharMatrixFromStrings (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCreate populated 2-D string mxArray#include "matrix.h"mxArray *mxCreateCharMatrixFromStrings(mwSize m, const char **str);mwPointer mxCreateCharMatrixFromStrings(m, str)mwSize mcharacter*(*) str(m)ArgumentsmstrThe desired number of rows in the created string mxArray. Thevalue you specify for m should equal the number of strings in str.In C, an array of strings containing at least m strings. In <strong>Fortran</strong>,a character*n array of size m, where each element of the arrayis n bytes.ReturnsDescriptionA pointer to the created string mxArray, if successful. Ifunsuccessful in a stand-alone (non-MEX-file) application,mxCreateCharMatrixFromStrings returns NULL in C (0 in <strong>Fortran</strong>). Ifunsuccessful in a MEX-file, the MEX-file terminates and control returnsto the MATLAB prompt. Insufficient free heap space is the primaryreason for mxCreateCharArray to be unsuccessful. Another possiblereason for failure is that str contains fewer than m strings.Use mxCreateCharMatrixFromStrings to create a two-dimensionalstring mxArray, where each row is initialized to a string from str. InC, the created mxArray has dimensions m-by-max, wheremax is thelength of the longest string in str. In <strong>Fortran</strong>, the created mxArray hasdimensions m-by-n, wheren is the number of characters in str(i).Note that string mxArrays represent their data elements as mxCharrather than as C char.CExamplesSee mxcreatecharmatrixfromstr.c in the mx subdirectory of theexamples directory.2-100


mxCreateCharMatrixFromStrings (C and <strong>Fortran</strong>)See AlsomxCreateCharArray, mxCreateString, mxGetString2-101


mxCreateDoubleMatrix (C and <strong>Fortran</strong>)Purpose Create 2-D, double-precision, floating-point mxArray initialized to 0CSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescription#include "matrix.h"mxArray *mxCreateDoubleMatrix(mwSize m, mwSize n,mxComplexity ComplexFlag);mwPointer mxCreateDoubleMatrix(m, n, ComplexFlag)mwSize m, ninteger*4 ComplexFlagmnThe desired number of rowsThe desired number of columnsComplexFlagSpecify either mxREAL or mxCOMPLEX. Ifthedatayouplantoputinto the mxArray has no imaginary components, specify mxREALin C (0 in <strong>Fortran</strong>). If the data has some imaginary components,specify mxCOMPLEX in C (1 in <strong>Fortran</strong>).A pointer to the created mxArray, if successful. If unsuccessful ina stand-alone (non-MEX-file) application, mxCreateDoubleMatrixreturns NULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, theMEX-file terminates and control returns to the MATLAB prompt.mxCreateDoubleMatrix is unsuccessful when there is not enough freeheap space to create the mxArray.Use mxCreateDoubleMatrix to create an m-by-n mxArray.mxCreateDoubleMatrix initializes each element in the pr arrayto 0. If you set ComplexFlag to mxCOMPLEX in C (1 in <strong>Fortran</strong>),mxCreateDoubleMatrix also initializes each element in the pi arrayto 0.If you set ComplexFlag to mxREAL in C (0 in <strong>Fortran</strong>),mxCreateDoubleMatrix allocates enough memory to hold m-by-n realelements. If you set ComplexFlag to mxCOMPLEX in C (1 in <strong>Fortran</strong>),2-102


mxCreateDoubleMatrix (C and <strong>Fortran</strong>)mxCreateDoubleMatrix allocates enough memory to hold m-by-n realelements and m-by-n imaginary elements.Call mxDestroyArray whenyoufinishusingthemxArray.mxDestroyArray deallocates the mxArray and its associated real andcomplex elements.CExamplesSee AlsoSee convec.c, findnz.c, sincall.c, timestwo.c, timestwoalt.c, andxtimesy.c in the refbook subdirectory of the examples directory.mxCreateNumericArray2-103


mxCreateDoubleScalar (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionCreate scalar, double-precision array initialized to specified value#include "matrix.h"mxArray *mxCreateDoubleScalar(double value);mwPointer mxCreateDoubleScalar(value)real*8 valuevalueThedesiredvaluetowhichyouwanttoinitializethearrayA pointer to the created mxArray, if successful. mxCreateDoubleScalaris unsuccessful if there is not enough free heap space to create themxArray. If mxCreateDoubleScalar is unsuccessful in a MEX-file,theMEX-fileprintsan“OutofMemory”message,terminates,andcontrol returns to the MATLAB prompt. If mxCreateDoubleScalaris unsuccessful in a stand-alone (nonMEX-file) application,mxCreateDoubleScalar returns NULL in C (0 in <strong>Fortran</strong>).Call mxCreateDoubleScalar to create a scalar double mxArray.mxCreateDoubleScalar is a convenience function that can be used inplace of the following C code:pa = mxCreateDoubleMatrix(1, 1, mxREAL);*mxGetPr(pa) = value;mxCreateDoubleScalar can be used in place of the following <strong>Fortran</strong>code:pm = mxCreateDoubleMatrix(1, 1, 0)mxCopyReal8ToPtr(value, mxGetPr(pm), 1)When you finish using the mxArray, callmxDestroyArray to destroy it.See AlsomxGetPr, mxCreateDoubleMatrix2-104


mxCreateLogicalArray (C)PurposeCSyntaxArgumentsCreate N-D logical mxArray initialized to false#include "matrix.h"mxArray *mxCreateLogicalArray(mwSize ndim, const mwSize *dims);ndimNumber of dimensions. If you specify a value for ndim that is lessthan 2, mxCreateLogicalArray automatically sets the numberof dimensions to 2.dimsThe dimensions array. Each element in the dimensions arraycontains the size of the array in that dimension. For example,setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. Thereshouldbendim elements in the dims array.ReturnsDescriptionA pointer to the created mxArray, if successful. If unsuccessful ina stand-alone (non-MEX-file) application, mxCreateLogicalArrayreturns NULL. If unsuccessful in a MEX-file, the MEX-file terminatesand control returns to the MATLAB prompt. mxCreateLogicalArrayis unsuccessful when there is not enough free heap space to create themxArray.Call mxCreateLogicalArray to create an N-dimensional mxArray oflogical 1 (true) andlogical0 (false) elements. After creating themxArray, mxCreateLogicalArray initializes all its elements to logical 0.mxCreateLogicalArray differs from mxCreateLogicalMatrix in thatthe latter can create two-dimensional arrays only.mxCreateLogicalArray allocates dynamic memory to store thecreated mxArray. When you finish with the created mxArray, callmxDestroyArray to deallocate its memory.Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.2-105


mxCreateLogicalArray (C)See AlsomxCreateLogicalMatrix, mxCreateSparseLogicalMatrix,mxCreateLogicalScalar2-106


mxCreateLogicalMatrix (C)PurposeCSyntaxCreate 2-D, logical mxArray initialized to false#include "matrix.h"mxArray *mxCreateLogicalMatrix(mwSize m, mwSize n);ArgumentsmnThe desired number of rowsThe desired number of columnsReturnsDescriptionSee AlsoA pointer to the created mxArray, if successful. If unsuccessful ina stand-alone (non-MEX-file) application, mxCreateLogicalMatrixreturns NULL. If unsuccessful in a MEX-file, the MEX-file terminatesand control returns to the MATLAB prompt. mxCreateLogicalMatrixis unsuccessful when there is not enough free heap space to create themxArray.Use mxCreateLogicalMatrix to create an m-by-n mxArray of logical1 (true) andlogical0 (false) elements. mxCreateLogicalMatrixinitializes each element in the array to logical 0.Call mxDestroyArray whenyoufinishusingthemxArray.mxDestroyArray deallocates the mxArray.mxCreateLogicalArray, mxCreateSparseLogicalMatrix,mxCreateLogicalScalar2-107


mxCreateLogicalScalar (C)PurposeCSyntaxArgumentsReturnsDescriptionCreate scalar, logical mxArray initialized to false#include "matrix.h"mxArray *mxCreateLogicalScalar(mxLogical value);valueThe desired logical value, logical 1 (true) orlogical0 (false), towhich you want to initialize the arrayA pointer to the created mxArray, if successful. mxCreateLogicalScalaris unsuccessful if there is not enough free heap space to create themxArray. If mxCreateLogicalScalar is unsuccessful in a MEX-file,theMEX-fileprintsan“OutofMemory”message,terminates,andcontrol returns to the MATLAB prompt. If mxCreateLogicalScalar isunsuccessful in a stand-alone (non-MEX-file) application, the functionreturns NULL.Call mxCreateLogicalScalar to create a scalar logical mxArray.mxCreateLogicalScalar is a convenience function that can be used inplace of the following code:pa = mxCreateLogicalMatrix(1, 1);*mxGetLogicals(pa) = value;When you finish using the mxArray, callmxDestroyArray to destroy it.See AlsomxCreateLogicalArray, mxCreateLogicalMatrix,mxIsLogicalScalar, mxIsLogicalScalarTrue, mxGetLogicals2-108


mxCreateNumericArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCreate unpopulated N-D numeric mxArray#include "matrix.h"mxArray *mxCreateNumericArray(mwSize ndim, const mwSize *dims,mxClassID classid, mxComplexity ComplexFlag);mwPointer mxCreateNumericArray(ndim, dims, classid,ComplexFlag)mwSize ndim, dimsinteger*4 classid, ComplexFlagndimNumber of dimensions. If you specify a value for ndim that is lessthan 2, mxCreateNumericArray automatically sets the numberof dimensions to 2.dimsThe dimensions array. Each element in the dimensions arraycontains the size of the array in that dimension. For example,in C, setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. In <strong>Fortran</strong>, setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray. In most cases, there should be ndimelements in the dims array.classidAn identifier for the class of the array, which determines theway the numerical data is represented in memory. For example,specifying mxINT16_CLASS in C causes each piece of numericaldata in the mxArray to be represented as a 16-bit signed integer.In <strong>Fortran</strong>, use the function mxClassIDFromClassName toderive the classid value from a MATLAB class name. See theDescription section for more information.ComplexFlagIf the data you plan to put into the mxArray has no imaginarycomponents, specify mxREAL in C (0 in <strong>Fortran</strong>). If the datahas some imaginary components, specify mxCOMPLEX in C (1 in<strong>Fortran</strong>).2-109


mxCreateNumericArray (C and <strong>Fortran</strong>)ReturnsDescriptionA pointer to the created mxArray, if successful. If unsuccessful ina stand-alone (non-MEX-file) application, mxCreateNumericArrayreturns NULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, theMEX-file terminates and control returns to the MATLAB prompt.mxCreateNumericArray is unsuccessful when there is not enough freeheap space to create the mxArray.Call mxCreateNumericArray to create an N-dimensional mxArrayin which all data elements have the numeric data type specifiedby classid. After creating the mxArray, mxCreateNumericArrayinitializes all its real data elements to 0. If ComplexFlag equalsmxCOMPLEX in C (1 in <strong>Fortran</strong>), mxCreateNumericArray also initializesall its imaginary data elements to 0. mxCreateNumericArray differsfrom mxCreateDoubleMatrix in two important respects:• All data elements in mxCreateDoubleMatrix are double-precision,floating-point numbers. The data elements in mxCreateNumericArraycould be any numerical type, including different integer precisions.• mxCreateDoubleMatrix can create two-dimensional arrays only;mxCreateNumericArray can create arrays of two or more dimensions.mxCreateNumericArray allocates dynamic memory to store thecreated mxArray. When you finish with the created mxArray, callmxDestroyArray to deallocate its memory.Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.The following table shows the C classid values and the <strong>Fortran</strong> datatypes that are equivalent to MATLAB classes.2-110


mxCreateNumericArray (C and <strong>Fortran</strong>)MATLAB ClassName C classid Value <strong>Fortran</strong> Typeint8 mxINT8_CLASS BYTEuint8mxUINT8_CLASSint16 mxUINT16_CLASS INTEGER*2uint16mxUINT16_CLASSint32 mxINT32_CLASS INTEGER*4uint32mxUINT32_CLASSint64 mxINT64_CLASS INTEGER*8uint64mxUINT64_CLASSsingle mxSINGLE_CLASS REAL*4double mxDOUBLE_CLASS REAL*8single, withimaginarycomponentsdouble, withimaginarycomponentsmxSINGLE_CLASSmxDOUBLE_CLASSCOMPLEX*8COMPLEX*16CExamples<strong>Fortran</strong>ExamplesSee phonebook.c and doubleelement.c in the refbook subdirectory ofthe examples directory. For an additional example, see mxisfinite.cin the mx subdirectory of the examples directory.To create a 4-by-4-by-2 array of REAL*8 elements having no imaginarycomponents, useCCreate 4x4x2 mxArray of REAL*8data dims / 4, 4, 2 /mxCreateNumericArray(3, dims,+ mxClassIDFromClassName('double'), 0)2-111


mxCreateNumericArray (C and <strong>Fortran</strong>)See AlsomxClassId, mxClassIdFromClassName, mxComplexity,mxCreateNumericMatrix2-112


mxCreateNumericMatrix (C and <strong>Fortran</strong>)Purpose Create numeric matrix and initialize data elements to 0CSyntax<strong>Fortran</strong>SyntaxArgumentsReturns#include "matrix.h"mxArray *mxCreateNumericMatrix(mwSize m, mwSize n,mxClassID classid, mxComplexity ComplexFlag);mwPointer mxCreateNumericMatrix(m, n, classid,ComplexFlag)mwSize m, ninteger*4 classid, ComplexFlagmnThe desired number of rows.The desired number of columns.classidAn identifier for the class of the array, which determines theway the numerical data is represented in memory. For example,specifying mxINT16_CLASS in C causes each piece of numericaldata in the mxArray to be represented as a 16-bit signed integer.In <strong>Fortran</strong>, use the function mxClassIDFromClassName toderive the classid value from a MATLAB class name. See theDescription section for more information.ComplexFlagIf the data you plan to put into the mxArray has no imaginarycomponents, specify mxREAL in C (0 in <strong>Fortran</strong>). If the datahas some imaginary components, specify mxCOMPLEX in C (1 in<strong>Fortran</strong>).A pointer to the created mxArray, if successful. mxCreateNumericMatrixis unsuccessful if there is not enough free heap space to create themxArray. If mxCreateNumericMatrix is unsuccessful in a MEX-file,theMEX-fileprintsan“OutofMemory”message,terminates,andcontrol returns to the MATLAB prompt. If mxCreateNumericMatrix2-113


mxCreateNumericMatrix (C and <strong>Fortran</strong>)is unsuccessful in a stand-alone (nonMEX-file) application,mxCreateNumericMatrix returns NULL in C (0 in <strong>Fortran</strong>).DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which alldata elements have the numeric data type specified by classid. Aftercreating the mxArray, mxCreateNumericMatrix initializes all its realdata elements to 0. If ComplexFlag equals mxCOMPLEX in C (1 in<strong>Fortran</strong>), mxCreateNumericMatrix also initializes all its imaginary dataelements to 0. mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray. When you finish using the mxArray, callmxDestroyArray to destroy it.The following table shows the C classid values and the <strong>Fortran</strong> datatypes that are equivalent to MATLAB classes.MATLAB ClassName C classid Value <strong>Fortran</strong> Typeint8 mxINT8_CLASS BYTEuint8mxUINT8_CLASSint16 mxUINT16_CLASS INTEGER*2uint16mxUINT16_CLASSint32 mxINT32_CLASS INTEGER*4uint32mxUINT32_CLASSint64 mxINT64_CLASS INTEGER*8uint64mxUINT64_CLASSsingle mxSINGLE_CLASS REAL*4double mxDOUBLE_CLASS REAL*82-114


mxCreateNumericMatrix (C and <strong>Fortran</strong>)MATLAB ClassName C classid Value <strong>Fortran</strong> Typesingle, withimaginarycomponentsdouble, withimaginarycomponentsmxSINGLE_CLASSmxDOUBLE_CLASSCOMPLEX*8COMPLEX*16<strong>Fortran</strong>ExamplesTo create a 4-by-3 matrix of REAL*4 elements having no imaginarycomponents, useCCreate 4x3 mxArray of REAL*4mxCreateNumericMatrix(4, 3,+ mxClassIDFromClassName('single'), 0)See AlsomxClassId, mxClassIdFromClassName, mxComplexity,mxCreateNumericArray2-115


mxCreateSparse (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionCreate 2-D unpopulated sparse mxArray#include "matrix.h"mxArray *mxCreateSparse(mwSize m, mwSize n, mwSize nzmax,mxComplexity ComplexFlag);mwPointer mxCreateSparse(m, n, nzmax, ComplexFlag)mwSize m, n, nzmaxinteger*4 ComplexFlagmnThe desired number of rowsThe desired number of columnsnzmaxThe number of elements that mxCreateSparse should allocateto hold the pr, ir, and,ifComplexFlag is mxCOMPLEX in C (1 in<strong>Fortran</strong>), pi arrays. Set the value of nzmax to be greater than orequal to the number of nonzero elements you plan to put into themxArray, butmakesurethatnzmax is less than or equal to m*n.ComplexFlagIf the mxArray you are creating is to contain imaginary data, setComplexFlag to mxCOMPLEX in C (1 in <strong>Fortran</strong>). Otherwise, setComplexFlag to mxREAL in C (0 in <strong>Fortran</strong>).A pointer to the created sparse double mxArray if successful, and NULLin C (0 in <strong>Fortran</strong>) otherwise. The most likely reason for failure isinsufficient free heap space. If that happens, try reducing nzmax, m, orn.Call mxCreateSparse to create an unpopulated sparse double mxArray.The returned sparse mxArray contains no sparse information andcannot be passed as an argument to any MATLAB sparse functions. Tomake the returned sparse mxArray useful, you must initialize the pr,ir, jc, and (if it exists) pi arrays.2-116


mxCreateSparse (C and <strong>Fortran</strong>)mxCreateSparse allocates space for• A pr array of length nzmax.• A pi array of length nzmax, butonlyifComplexFlag is mxCOMPLEXin C (1 in <strong>Fortran</strong>).• An ir array of length nzmax.• A jc array of length n+1.When you finish using the sparse mxArray, callmxDestroyArray toreclaim all its heap space.CExamplesSee AlsoSee fulltosparse.c in the refbook subdirectory of the examplesdirectory.mxDestroyArray, mxSetNzmax, mxSetPr, mxSetPi, mxSetIr, mxSetJc,mxComplexity2-117


mxCreateSparseLogicalMatrix (C)PurposeCSyntaxArgumentsReturnsDescriptionSee AlsoCreate unpopulated 2-D, sparse, logical mxArray#include "matrix.h"mxArray *mxCreateSparseLogicalMatrix(mwSize m, mwSize n,mwSize nzmax);mnThe desired number of rowsThe desired number of columnsnzmaxThe number of elements that mxCreateSparseLogicalMatrixshould allocate to hold the data. Set the value of nzmax to begreater than or equal to the number of nonzero elements you planto put into the mxArray, butmakesurethatnzmax is less than orequal to m*n.A pointer to the created mxArray, if successful. If unsuccessful in astand-alone (nonMEX-file) application, mxCreateSparseLogicalMatrixreturns NULL. If unsuccessful in a MEX-file, the MEX-fileterminates and control returns to the MATLAB prompt.mxCreateSparseLogicalMatrix is unsuccessful when there is notenough free heap space to create the mxArray.Use mxCreateSparseLogicalMatrix to create an m-by-nmxArray of logical 1 (true) andlogical0 (false) elements.mxCreateSparseLogicalMatrix initializes each element in the arrayto logical 0.Call mxDestroyArray whenyoufinishusingthemxArray.mxDestroyArray deallocates the mxArray and its elements.mxCreateLogicalArray, mxCreateLogicalMatrix,mxCreateLogicalScalar, mxCreateSparse, mxIsLogical2-118


mxCreateString (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCreate 1-by-N string mxArray initialized to specified string#include "matrix.h"mxArray *mxCreateString(const char *str);mwPointer mxCreateString(str)character*(*) strArgumentsstrThe string that is to serve as the mxArray's initial dataReturns A pointer to the created string mxArray if successful, and NULL in C (0in <strong>Fortran</strong>) otherwise. The most likely cause of failure is insufficientfree heap space.DescriptionCExamples<strong>Fortran</strong>ExamplesSee AlsoUse mxCreateString to create a string mxArray initialized to str.Many MATLAB functions (for example, strcmp and upper) requirestring array inputs.Free the string mxArray when you are finished using it. To free a stringmxArray, callmxDestroyArray.See revord.c in the refbook subdirectory of the examples directory.For additional examples, see mxcreatestructarray.c and mxisclass.cin the mx subdirectory of the examples directory.See matdemo1.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.mxCreateCharMatrixFromStrings, mxCreateCharArray2-119


mxCreateStructArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCreate unpopulated N-D structure mxArray#include "matrix.h"mxArray *mxCreateStructArray(mwSize ndim, const mwSize *dims,int nfields, const char **fieldnames);mwPointer mxCreateStructArray(ndim, dims, nfields,fieldnames)mwSize ndim, dimsinteger*4 nfieldscharacter*(*) fieldnames(nfields)ArgumentsndimNumber of dimensions. If you set ndim to be less than 2,mxCreateNumericArray creates a two-dimensional mxArray.dimsThe dimensions array. Each element in the dimensions arraycontains the size of the array in that dimension. For example,in C, setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. In <strong>Fortran</strong>, setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray. Typically,thedims array shouldhave ndim elements.nfieldsThe desired number of fields in each elementfieldnamesThe desired list of field namesEach structure field name must begin with a letter and is casesensitive. The rest of the name may contain letters, numerals, andunderscore characters. Use the namelengthmax function to determinethe maximum length of a field name.2-120


mxCreateStructArray (C and <strong>Fortran</strong>)ReturnsDescriptionA pointer to the created structure mxArray if successful, and NULL in C(0 in <strong>Fortran</strong>) otherwise. The most likely cause of failure is insufficientheapspacetoholdthereturnedmxArray.Call mxCreateStructArray to create an unpopulated structuremxArray. Each element of a structure mxArray contains the samenumber of fields (specified in nfields). Each field has a name; the listofnamesisspecifiedinfieldnames. A structure mxArray in MATLABis conceptually identical to an array of structs in the C language.Each field holds one mxArray pointer. mxCreateStructArrayinitializes each field to NULL in C (0 in <strong>Fortran</strong>). Call mxSetField ormxSetFieldByNumber to place a non-NULL mxArray pointer in a field.When you finish using the returned structure mxArray, callmxDestroyArray to reclaim its space.Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.CExamplesSee AlsoSee mxcreatestructarray.c in the mx subdirectory of the examplesdirectory.mxDestroyArray, mxAddField, mxRemoveField, mxSetField,mxSetFieldByNumber2-121


mxCreateStructMatrix (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsCreate unpopulated 2-D structure mxArray#include "matrix.h"mxArray *mxCreateStructMatrix(mwSize m, mwSize n, int nfields,const char **fieldnames);mwPointer mxCreateStructMatrix(m, n, nfields, fieldnames)mwSize m, ninteger*4 nfieldscharacter*(*) fieldnames(nfields)mnThe desired number of rows. This must be a positive integer.The desired number of columns. This must be a positive integer.nfieldsThe desired number of fields in each element.fieldnamesThe desired list of field names.Each structure field name must begin with a letter and is casesensitive. The rest of the name may contain letters, numerals, andunderscore characters. Use the namelengthmax function to determinethe maximum length of a field name.ReturnsDescriptionA pointer to the created structure mxArray if successful, and NULL in C(0 in <strong>Fortran</strong>) otherwise. The most likely cause of failure is insufficientheapspacetoholdthereturnedmxArray.mxCreateStructMatrix and mxCreateStructArray are almostidentical. The only difference is that mxCreateStructMatrix can createonly two-dimensional mxArrays, whilemxCreateStructArray cancreate mxArrays having two or more dimensions.2-122


mxCreateStructMatrix (C and <strong>Fortran</strong>)CExamplesSee AlsoSee phonebook.c in the refbook subdirectory of the examples directory.mxCreateStructArray2-123


mxDestroyArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxFree dynamic memory allocated by mxCreate#include "matrix.h"void mxDestroyArray(mxArray *pm);subroutine mxDestroyArray(pm)mwPointer pmArgumentspmPointer to the mxArray you want to freeDescriptionCExamplesmxDestroyArray deallocates the memory occupied by the specifiedmxArray. mxDestroyArray not only deallocates the memory occupiedby the mxArray’s characteristics fields (such as m and n), but alsodeallocates all the mxArray’s associated data arrays, such as pr andpi for complex arrays, ir and jc for sparse arrays, fields of structurearrays, and cells of cell arrays. Do not call mxDestroyArray on anmxArray you are returning on the left-hand side.See sincall.c in the refbook subdirectory of the examples directory.Additional examples:• mexcallmatlab.c and mexgetarray.c in the mex subdirectory of theexamples directory• mxisclass.c in the mx subdirectory of the examples directorySee AlsomxCalloc, mxMalloc, mxFree, mexMakeArrayPersistent,mexMakeMemoryPersistent2-124


mxDuplicateArray (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxMake deep copy of array#include "matrix.h"mxArray *mxDuplicateArray(const mxArray *in);mwPointer mxDuplicateArray(in)mwPointer inArgumentsinPointer to the mxArray you want to copyReturnsDescriptionCExamplesPointer to a copy of the array.mxDuplicateArray makes a deep copy of an array, and returns a pointerto the copy. A deep copy refers to a copy in which all levels of data arecopied. For example, a deep copy of a cell array copies each cell and thecontents of each cell (if any), and so on.See• mexget.c in the mex subdirectory of the examples directory• phonebook.c in the refbook subdirectory of the examples directoryFor additional examples, see mxcreatecellmatrix.c, mxgetinf.c, andmxsetnzmax.c in the mx subdirectory of the examples directory.2-125


mxFree (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxFree dynamic memory allocated by mxCalloc, mxMalloc, ormxRealloc#include "matrix.h"void mxFree(void *ptr);subroutine mxFree(ptr)mwPointer ptrArgumentsptrPointer to the beginning of any memory parcel allocated bymxCalloc, mxMalloc, ormxRealloc.DescriptionmxFree deallocates heap space using the MATLAB memorymanagement facility. This ensures correct memory management inerror and abort (Ctrl+C) conditions.To deallocate heap space, MATLAB applications in C should always callmxFree rather than the ANSI C free function.The MATLAB memory management facility maintains a list ofall memory allocated by mxCalloc, mxMalloc, mxRealloc, andthe mxCreate* calls. The MATLAB memory management facilityautomatically deallocates all of a MEX-file’s managed parcels when theMEX-file completes and control returns to the MATLAB prompt.When mxFree appears in a stand-alone MATLAB application, mxFreesimply deallocates the contiguous heap space that begins at addressptr. InaMEX-file,mxFree also removes the memory parcel from theMATLAB memory management facility’s list of memory parcels.In a MEX-file, your use of mxFree depends on whether thespecified memory parcel is persistent or nonpersistent. By default,memory parcels created by mxCalloc, mxMalloc, andmxReallocare nonpersistent. The MATLAB memory management facilityautomatically frees all nonpersistent memory whenever a MEX-filecompletes. Thus, even if you do not call mxFree, MATLAB takes careof freeing the memory for you. Nevertheless, it is good programming2-126


mxFree (C and <strong>Fortran</strong>)practice to deallocate memory as soon as you are through using it.Doing so generally makes the entire system run more efficiently.If an application calls mexMakeMemoryPersistent, the specified memoryparcel becomes persistent. When a MEX-file completes, the MATLABmemory management facility does not free persistent memory parcels.Therefore, the only way to free a persistent memory parcel is to callmxFree. Typically, MEX-files call mexAtExit to register a cleanuphandler. The cleanup handler calls mxFree.CExamplesSee mxcalcsinglesubscript.c in the mx subdirectory of the examplesdirectory.Additional examples:• phonebook.c in the refbook subdirectory of the examples directory• explore.c and mexatexit.c in the mex subdirectory of the examplesdirectory• mxcreatecharmatrixfromstr.c, mxisfinite.c, mxmalloc.c, andmxsetdimensions.c in the mx subdirectory of the examples directorySee AlsomexAtExit, mexMakeArrayPersistent, mexMakeMemoryPersistent,mxCalloc, mxDestroyArray, mxMalloc, mxRealloc2-127


mxGetCell (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsContents of mxArray cell#include "matrix.h"mxArray *mxGetCell(const mxArray *pm, mwIndex index);mwPointer mxGetCell(pm, index)mwPointer pmmwIndex indexpmPointer to a cell mxArrayindexThe number of elements in the cell mxArray between the firstelement and the desired one. See mxCalcSingleSubscript fordetails on calculating an index in a multidimensional cell array.A pointer to the ith cell mxArray if successful, and NULL in C (0 in<strong>Fortran</strong>) otherwise. Causes of failure include• Specifying the index of a cell array element that has not beenpopulated.• Specifying a pm that does not point to a cell mxArray.• Specifying an index greater than the number of elements in the cell.• Insufficient free heap space to hold the returned cell mxArray.DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexedelement of the cell mxArray.Note Inputs to a MEX-file are constant read-only mxArrays and shouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.2-128


mxGetCell (C and <strong>Fortran</strong>)CExamplesSee AlsoSee explore.c in the mex subdirectory of the examples directory.mxCreateCellArray, mxIsCell, mxSetCell2-129


mxGetChars (C)PurposeCSyntaxArgumentsReturnsDescriptionSee AlsoPointer to character array data#include "matrix.h"mxChar *mxGetChars(const mxArray *array_ptr);array_ptrPointer to an mxArrayThe address of the first character in the mxArray. Returns NULL if thespecified array is not a character array.Call mxGetChars to determine the address of the first character in themxArray that array_ptr points to. Once you have the starting address,you can access any other element in the mxArray.mxGetString2-130


mxGetClassID (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxClass of mxArray#include "matrix.h"mxClassID mxGetClassID(const mxArray *pm);integer*4 mxGetClassID(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsA numeric identifier of the class (category) of the mxArray that pm pointsto. The C-language class identifiers aremxUNKNOWN_CLASSThe class cannot be determined. You cannot specify this categoryfor an mxArray; however, mxGetClassID can return this valueif it cannot identify the class.mxCELL_CLASSIdentifies a cell mxArray.mxSTRUCT_CLASSIdentifies a structure mxArray.mxCHAR_CLASSIdentifies a string mxArray, anmxArray whose data is representedas mxCHAR’s.mxLOGICAL_CLASSIdentifies a logical mxArray, anmxArray that stores thelogical values 1 and 0, representing the states true and falserespectively.mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored asdouble-precision, floating-point numbers.2-131


mxGetClassID (C and <strong>Fortran</strong>)example, if pm points to a logical mxArray, thenmxGetClassID returnsmxLOGICAL_CLASS (in C).mxGetClassID is similar to mxGetClassName, exceptthattheformerreturns the class as an integer identifier and the latter returns theclassasastring.CExamplesSee AlsoSee• phonebook.c in the refbook subdirectory of the examples directory• explore.c in the mex subdirectory of the examples directorymxGetClassName2-133


mxGetClassName (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxClass of mxArray as string#include "matrix.h"const char *mxGetClassName(const mxArray *pm);character*(*) mxGetClassName(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoThe class (as a string) of the mxArray pointed to by pm.Call mxGetClassName to determine the class of an mxArray. Theclassof an mxArray identifies the kind of data the mxArray is holding. Forexample, if pm points to a logical mxArray, mxGetClassName returnslogical.mxGetClassID is similar to mxGetClassName, exceptthattheformerreturns the class as an integer identifier and the latter returns theclassasastring.See mexfunction.c in the mex subdirectory of the examples directory.For an additional example, see mxisclass.c in the mx subdirectoryof the examples directory.mxGetClassID2-134


mxGetData (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxPointer to data#include "matrix.h"void *mxGetData(const mxArray *pm);mwPointer mxGetData(pm)mwPointer pmArgumentspmPointer to an mxArrayReturns The address of the first element of the real data. Returns NULL in C (0in <strong>Fortran</strong>) if there is no real data.Description Similar to mxGetPr, exceptthatinC,mxGetData returns a void *.To copy values from the returned pointer to <strong>Fortran</strong>, use one of themxCopyPtrTo* functions in the following manner:CGet the data in mxArray, pmmxCopyPtrToReal8(mxGetData(pm), data,+ mxGetNumberOfElements(pm))CExamplesSee AlsoSee phonebook.c in the refbook subdirectory of the examples directory.For additional examples, see mxcreatecharmatrixfromstr.c andmxisfinite.c in the mx subdirectory of the examples directory.mxGetImagData, mxGetPr2-135


mxGetDimensions (C and<strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxPointer to dimensions array#include "matrix.h"const mwSize *mxGetDimensions(const mxArray *pm);mwPointer mxGetDimensions(pm)mwPointer pmArgumentspmPointer to an mxArray.ReturnsDescriptionThe address of the first element in the dimensions array. Each integerin the dimensions array represents the number of elements in aparticular dimension. The array is not NULL terminated.Use mxGetDimensions to determine how many elements arein each dimension of the mxArray that pm points to. CallmxGetNumberOfDimensions to get the number of dimensions in themxArray.Tocopythevaluesto<strong>Fortran</strong>,usemxCopyPtrToInteger4 in thefollowing manner:CGet dimensions of mxArray, pmmxCopyPtrToInteger4(mxGetDimensions(pm), dims,+ mxGetNumberOfDimensions(pm))CExamplesSee mxcalcsinglesubscript.c in the mx subdirectory of the examplesdirectory.Additional examples:• findnz.c and phonebook.c in the refbook subdirectory of theexamples directory• explore.c in the mex subdirectory of the examples directory2-136


mxGetDimensions (C and<strong>Fortran</strong>)• mxgeteps.c and mxisfinite.c in the mx subdirectory of theexamples directorySee AlsomxGetNumberOfDimensions2-137


mxGetElementSize (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of bytes required to store each data element#include "matrix.h"size_t mxGetElementSize(const mxArray *pm);mwSize mxGetElementSize(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoThe number of bytes required to store one element of the specifiedmxArray, if successful. Returns 0 on failure. The primary reason forfailure is that pm points to an mxArray having an unrecognized class. Ifpm points to a cell mxArray or a structure mxArray, mxGetElementSizereturns the size of a pointer (not the size of all the elements in eachcell or structure field).Call mxGetElementSize to determine the number of bytes in eachdata element of the mxArray. For example, if the MATLAB class of anmxArray is int16, themxArray stores each data element as a 16-bit(2-byte) signed integer. Thus, mxGetElementSize returns 2.mxGetElementSize is particularly helpful when using a non-MATLABroutine to manipulate data elements. For example, the C functionmemcpy requires (for its third argument) the size of the elements youintend to copy.See doubleelement.c and phonebook.c in the refbook subdirectoryof the examples directory.mxGetM, mxGetN2-138


mxGetEps (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReturnsDescriptionCExamplesSee AlsoValue of eps#include "matrix.h"double mxGetEps(void);real*8 mxGetEpsThe value of the MATLAB eps variableCall mxGetEps to return the value of the MATLAB eps variable. Thisvariable holds the distance from 1.0 to the next largest floating-pointnumber. As such, it is a measure of floating-point accuracy. TheMATLAB PINV and RANK functions use eps as a default tolerance.See mxgeteps.c in the mx subdirectory of the examples directory.mxGetInf, mxGetNan2-139


mxGetField (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsField value, given field name and index into structure array#include "matrix.h"mxArray *mxGetField(const mxArray *pm, mwIndex index,const char *fieldname);mwPointer mxGetField(pm, index, fieldname)mwPointer pmmwIndex indexcharacter*(*) fieldnamepmPointer to a structure mxArrayindexThe desired element. In C, the first element of an mxArray hasan index of 0, the second element has an index of 1, andthelast element has an index of N-1, whereN is the total number ofelements in the structure mxArray. In <strong>Fortran</strong>, the first elementof an mxArray has an index of 1, the second element has an indexof 2, and the last element has an index of N, where N is the totalnumber of elements in the structure mxArray.fieldnameThe name of the field whose value you want to extract.A pointer to the mxArray in the specified field at the specifiedfieldname, on success. Returns NULL in C (0 in <strong>Fortran</strong>) if passed aninvalid argument or if there is no value assigned to the specified field.Common causes of failure include• Specifying an array pointer pm that does not point to a structuremxArray. To determine whether pm points to a structure mxArray,call mxIsStruct.• Specifying an index to an element outside the bounds of the mxArray.For example, given a structure mxArray that contains 10 elements,you cannot specify an index greater than 9 in C (10 in <strong>Fortran</strong>).2-140


mxGetField (C and <strong>Fortran</strong>)• Specifying a nonexistent fieldname. CallmxGetFieldNameByNumberor mxGetFieldNumber to get existing field names.• Insufficient heap space to hold the returned mxArray.DescriptionCall mxGetField to get the value held in the specified element of thespecified field. In pseudo-C terminology, mxGetField returns the valueatpm[index].fieldnamemxGetFieldByNumber is similar to mxGetField. Both functions returnthe same value. The only difference is in the way you specify the field.mxGetFieldByNumber takesafieldnumberasits third argument, andmxGetField takes a field name as its third argument.Note Inputs to a MEX-file are constant read-only mxArrays andshouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.In C, callingmxGetField(pa, index, "field_name");is equivalent to callingfield_num = mxGetFieldNumber(pa, "field_name");mxGetFieldByNumber(pa, index, field_num);where index is 0 if you have a 1-by-1 structure.In <strong>Fortran</strong>, callingmxGetField(pm, index, 'fieldname')is equivalent to calling2-141


mxGetField (C and <strong>Fortran</strong>)fieldnum = mxGetFieldNumber(pm, 'fieldname')mxGetFieldByNumber(pm, index, fieldnum)where index is 1 if you have a 1-by-1 structure.See AlsomxGetFieldByNumber, mxGetFieldNameByNumber, mxGetFieldNumber,mxGetNumberOfFields, mxIsStruct, mxSetField, mxSetFieldByNumber2-142


mxGetFieldByNumber (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsField value, given field number and index into structure array#include "matrix.h"mxArray *mxGetFieldByNumber(const mxArray *pm, mwIndex index,int fieldnumber);mwPointer mxGetFieldByNumber(pm, index, fieldnumber)mwPointer pmmwIndex indexinteger*4 fieldnumberpmPointer to a structure mxArrayindexThe desired element. In C, the first element of an mxArray hasan index of 0, the second element has an index of 1, andthelast element has an index of N-1, whereN is the total number ofelements in the structure mxArray. In <strong>Fortran</strong>, the first elementof an mxArray has an index of 1, the second element has anindex of 2, and the last element has an index of N, whereN isthe total number of elements in the structure mxArray. SeemxCalcSingleSubscript for more details on calculating an index.fieldnumberThe position of the field whose value you want to extract. In C, thefirst field within each element has a field number of 0, the secondfield has a field number of 1, and so on. The last field has a fieldnumber of N-1, whereN is the number of fields. In <strong>Fortran</strong>, thefirst field within each element has a field number of 1, the secondfield has a field number of 2, and so on. The last field has a fieldnumber of N, whereN is the number of fields.A pointer to the mxArray in the specified field for the desired element,on success. Returns NULL in C (0 in <strong>Fortran</strong>) if passed an invalidargument or if there is no value assigned to the specified field. Commoncauses of failure include2-143


mxGetFieldByNumber (C and <strong>Fortran</strong>)• Specifying an array pointer pm that does not point to a structuremxArray. Call mxIsStruct to determine whether pm points to astructure mxArray.• Specifying an index to an element outside the bounds of the mxArray.For example, given a structure mxArray that contains 10 elements,you cannot specify an index greater than 9 in C (10 in <strong>Fortran</strong>).• Specifying a nonexistent field number. Call mxGetFieldNumber todetermine the field number that corresponds to a given field name.DescriptionCall mxGetFieldByNumber to get the value held in the specifiedfieldnumber at the indexed element.Note Inputs to a MEX-file are constant read-only mxArrays and shouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.In C, callingmxGetField(pa, index, "field_name");is equivalent to callingfield_num = mxGetFieldNumber(pa, "field_name");mxGetFieldByNumber(pa, index, field_num);where index is 0 if you have a 1-by-1 structure.In <strong>Fortran</strong>, callingmxGetField(pm, index, 'fieldname')is equivalent to callingfieldnum = mxGetFieldNumber(pm, 'fieldname')mxGetFieldByNumber(pm, index, fieldnum)2-144


mxGetFieldByNumber (C and <strong>Fortran</strong>)where index is 1 if you have a 1-by-1 structure.CExamplesSee phonebook.c in the refbook subdirectory of the examples directory.Additional examples:• mxisclass.c in the mx subdirectory of the examples directory• explore.c in the mex subdirectory of the examples directorySee AlsomxGetField, mxGetFieldNameByNumber, mxGetFieldNumber,mxGetNumberOfFields, mxIsStruct, mxSetField, mxSetFieldByNumber2-145


mxGetFieldNameByNumber (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsField name, given field number in structure array#include "matrix.h"const char *mxGetFieldNameByNumber(const mxArray *pm,int fieldnumber);character*(*) mxGetFieldNameByNumber(pm, fieldnumber)mwPointer pminteger*4 fieldnumberpmPointer to a structure mxArrayfieldnumberThe position of the desired field. For instance, in C, to get thename of the first field, set fieldnumber to 0; to get the name ofthe second field, set fieldnumber to 1; and so on. In <strong>Fortran</strong>, toget the name of the first field, set fieldnumber to 1; togetthename of the second field, set fieldnumber to 2; andsoon.A pointer to the nth field name, on success. Returns NULL in C (0 in<strong>Fortran</strong>) on failure. Common causes of failure include• Specifying an array pointer pm that does not point to a structuremxArray. Call mxIsStruct to determine whether pm points to astructure mxArray.• Specifying a value of fieldnumber outside the bounds of thenumber of fields in the structure mxArray. InC, fieldnumber 0represents the first field, and fieldnumber N-1 represents the lastfield, where N is the number of fields in the structure mxArray. In<strong>Fortran</strong>, fieldnumber 1 represents the first field, and fieldnumber Nrepresents the last field.DescriptionCall mxGetFieldNameByNumber to get the name of a field in the givenstructure mxArray. AtypicaluseofmxGetFieldNameByNumber is to call2-146


mxGetFieldNameByNumber (C and <strong>Fortran</strong>)it inside a loop in order to get the names of all the fields in a givenmxArray.Consider a MATLAB structure initialized topatient.name = 'John Doe';patient.billing = 127.00;patient.test = [79 75 73; 180 178 177.5; 220 210 205];In C, the field number 0 represents the field name; field number 1represents field billing; field number 2 represents field test. Afieldnumber other than 0, 1, or2 causes mxGetFieldNameByNumber to returnNULL.In <strong>Fortran</strong>, the field number 1 represents the field name; field number2 represents field billing; field number 3 represents field test. Afield number other than 1, 2, or3 causes mxGetFieldNameByNumberto return 0.CExamplesSee phonebook.c in the refbook subdirectory of the examples directory.Additional examples:• mxisclass.c in the mx subdirectory of the examples directory• explore.c in the mex subdirectory of the examples directorySee AlsomxGetField, mxGetFieldByNumber, mxGetFieldNumber,mxGetNumberOfFields, mxIsStruct, mxSetField, mxSetFieldByNumber2-147


mxGetFieldNumber (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsField number, given field name in structure array#include "matrix.h"int mxGetFieldNumber(const mxArray *pm,const char *fieldname);integer*4 mxGetFieldNumber(pm, fieldname)mwPointer pmcharacter*(*) fieldnamepmPointer to a structure mxArray.fieldnameThenameofafieldinthestructuremxArray.The field number of the specified fieldname, on success. In C, the firstfield has a field number of 0, the second field has a field number of 1,and so on. In <strong>Fortran</strong>, the first field has a field number of 1, the secondfield has a field number of 2, and so on. Returns -1 in C (0 in <strong>Fortran</strong>)on failure. Common causes of failure include• Specifying an array pointer pm that does not point to a structuremxArray. Call mxIsStruct to determine whether pm points to astructure mxArray.• Specifying the fieldname of a nonexistent field.DescriptionIf you know the name of a field but do not know its field number, callmxGetFieldNumber. Conversely, if you know the field number but donot know its field name, call mxGetFieldNameByNumber.Forexample,consideraMATLABstructureinitializedtopatient.name = 'John Doe';patient.billing = 127.00;patient.test = [79 75 73; 180 178 177.5; 220 210 205];2-148


mxGetFieldNumber (C and <strong>Fortran</strong>)In C, the field name has a field number of 0; thefieldbilling has a fieldnumber of 1; andthefieldtest has a field number of 2. IfyoucallmxGetFieldNumber and specify a field name of anything other thanname, billing, ortest, mxGetFieldNumber returns -1.CallingmxGetField(pa, index, "field_name");is equivalent to callingfield_num = mxGetFieldNumber(pa, "field_name");mxGetFieldByNumber(pa, index, field_num);where index is 0 if you have a 1-by-1 structure.In <strong>Fortran</strong>, the field name has a field number of 1; thefieldbilling hasa field number of 2; and the field test has a field number of 3. Ifyoucall mxGetFieldNumber and specify a field name of anything other than'name', ’billing', or’test', mxGetFieldNumber returns 0.CallingmxGetField(pm, index, 'fieldname');is equivalent to callingfieldnum = mxGetFieldNumber(pm, 'fieldname');mxGetFieldByNumber(pm, index, fieldnum);where index is 1 if you have a 1-by-1 structure.CExamplesSee AlsoSee mxcreatestructarray.c in the mx subdirectory of the examplesdirectory.mxGetField, mxGetFieldByNumber, mxGetFieldNameByNumber,mxGetNumberOfFields, mxIsStruct, mxSetField, mxSetFieldByNumber2-149


mxGetImagData (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxPointer to imaginary data of mxArray#include "matrix.h"void *mxGetImagData(const mxArray *pm);mwPointer mxGetImagData(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsThe address of the first element of the imaginary data, on success.Returns NULL in C (0 in <strong>Fortran</strong>) if there is no imaginary data or if thereis an error.Description This function is similar to mxGetPi, except that in C it returns a void *.CExamplesSee AlsoSee mxisfinite.c in the mx subdirectory of the examples directory.mxGetData, mxGetPi2-150


mxGetInf (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReturnsDescriptionValue of infinity#include "matrix.h"double mxGetInf(void);real*8 mxGetInfThe value of infinity on your system.Call mxGetInf to return the value of the MATLAB internal inf variable.inf is a permanent variable representing IEEE arithmetic positiveinfinity. The value of inf is built into the system; you cannot modify it.Operations that return infinity include• Division by 0. For example, 5/0 returns infinity.• Operations resulting in overflow. For example, exp(10000) returnsinfinity because the result is too large to be represented on yourmachine.CExamplesSee AlsoSee mxgetinf.c in the mx subdirectory of the examples directory.mxGetEps, mxGetNaN2-151


mxGetIr (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>Syntaxir array of sparse matrix#include "matrix.h"mwIndex *mxGetIr(const mxArray *pm);mwPointer mxGetIr(pm)mwPointer pmArgumentspmPointer to a sparse mxArrayReturnsA pointer to the first element in the ir array, if successful, and NULL inC(0 in <strong>Fortran</strong>) otherwise. Possible causes of failure include• Specifying a full (nonsparse) mxArray.• Specifying a value for pm that is NULL in C (0 in <strong>Fortran</strong>). This usuallymeans that an earlier call to mxCreateSparse failed.DescriptionCExamplesUse mxGetIr to obtain the starting address of the ir array. The irarray is an array of integers; the length of the ir array is typicallynzmax values. For example, if nzmax equals 100, their array shouldcontain 100 integers.Each value in an ir array indicates a row (offset by 1) at which anonzero element can be found. (The jc array is an index that indirectlyspecifies a column where nonzero elements can be found.)For details on the ir and jc arrays, see mxSetIr and mxSetJc.See fulltosparse.c in the refbook subdirectory of the examplesdirectory.Additional examples:• explore.c in the mex subdirectory of the examples directory2-152


mxGetIr (C and <strong>Fortran</strong>)• mxsetdimensions.c and mxsetnzmax.c in the mx subdirectory of theexamples directorySee AlsomxGetJc, mxGetNzmax, mxSetIr, mxSetJc, mxSetNzmax2-153


mxGetJc (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>Syntaxjc array of sparse matrix#include "matrix.h"mwIndex *mxGetJc(const mxArray *pm);mwPointer mxGetJc(pm)mwPointer pmArgumentspmPointer to a sparse mxArrayReturnsA pointer to the first element in the jc array, if successful, and NULL inC(0 in <strong>Fortran</strong>) otherwise. Possible causes of failure include• Specifying a full (nonsparse) mxArray.• Specifying a value for pm that is NULL in C (0 in <strong>Fortran</strong>). This usuallymeans that an earlier call to mxCreateSparse failed.DescriptionCExamplesUse mxGetJc to obtain the starting address of the jc array. Thejc array is an integer array having n+1 elements, where n is thenumber of columns in the sparse mxArray. Thevaluesinthejc arrayindirectly indicate columns containing nonzero elements. For a detailedexplanation of the jc array, see mxSetJc.See fulltosparse.c in the refbook subdirectory of the examplesdirectory.Additional examples:• explore.c in the mex subdirectory of the examples directory• mxgetnzmax.c, mxsetdimensions.c, andmxsetnzmax.c in the mxsubdirectory of the examples directorySee AlsomxGetIr, mxGetNzmax, mxSetIr, mxSetJc, mxSetNzmax2-154


mxGetLogicals (C)PurposeCSyntaxArgumentsReturnsDescriptionSee AlsoPointer to logical array data#include "matrix.h"mxLogical *mxGetLogicals(const mxArray *array_ptr);array_ptrPointer to an mxArrayThe address of the first logical element in the mxArray. Theresultisunspecified if the mxArray is not a logical array.Call mxGetLogicals to determine the address of the first logical elementin the mxArray that array_ptr points to. Once you have the startingaddress, you can access any other element in the mxArray.mxCreateLogicalArray, mxCreateLogicalMatrix,mxCreateLogicalScalar, mxIsLogical, mxIsLogicalScalar,mxIsLogicalScalarTrue2-155


mxGetM (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of rows in mxArray#include "matrix.h"size_t mxGetM(const mxArray *pm);mwSize mxGetM(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesThe number of rows in the mxArray to which pm points.mxGetM returns the number of rows in the specified array. The termrows always means the first dimension of the array, no matter howmany dimensions the array has. For example, if pm points to afour-dimensional array having dimensions 8-by-9-by-5-by-3, mxGetMreturns 8.See convec.c in the refbook subdirectory of the examples directory.Additional examples:• fulltosparse.c, revord.c, timestwo.c, andxtimesy.c in therefbook subdirectory of the examples directory• explore.c, mexget.c, mexlock.c, mexsettrapflag.c and yprime.cin the mex subdirectory of the examples directory• mxmalloc.c, mxsetdimensions.c, mxgetnzmax.c, andmxsetnzmax.cin the mx subdirectory of the examples directory<strong>Fortran</strong>ExamplesSee AlsoSee matdemo2.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.mxGetN, mxSetM, mxSetN2-156


mxGetN (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of columns in mxArray#include "matrix.h"size_t mxGetN(const mxArray *pm);mwSize mxGetN(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesThe number of columns in the mxArray.Call mxGetN to determine the number of columns in the specifiedmxArray.If pm is an N-dimensional mxArray, mxGetN is the product of dimensions2 through N. For example, if pm points to a four-dimensional mxArrayhaving dimensions 13-by-5-by-4-by-6, mxGetN returns the value 120 (5 ×4 × 6). If the specified mxArray has more than two dimensions and youneed to know exactly how many elements are in each dimension, callmxGetDimensions.If pm points to a sparse mxArray, mxGetN still returns the number ofcolumns, not the number of occupied columns.See convec.c in the refbook subdirectory of the examples directory.Additional examples:• fulltosparse.c, revord.c, timestwo.c, andxtimesy.c in therefbook subdirectory of the examples directory• explore.c, mexget.c, mexlock.c, mexsettrapflag.c and yprime.cin the mex subdirectory of the examples directory• mxmalloc.c, mxsetdimensions.c, mxgetnzmax.c, andmxsetnzmax.cin the mx subdirectory of the examples directory2-157


mxGetN (C and <strong>Fortran</strong>)<strong>Fortran</strong>ExamplesSee AlsoSee matdemo2.F in the eng_mat subdirectory of the examples directoryfor a sample program that illustrates how to use this routine in a<strong>Fortran</strong> program.mxGetM, mxGetDimensions, mxSetM, mxSetN2-158


mxGetNaN (C and <strong>Fortran</strong>)PurposeCSyntaxValue of NaN (Not-a-Number)#include "matrix.h"double mxGetNaN(void);<strong>Fortran</strong>SyntaxReturnsDescriptionreal*8 mxGetNaNThe value of NaN (Not-a-Number) on your systemCall mxGetNaN to return the value of NaN for your system. NaN isthe IEEE arithmetic representation for Not-a-Number. Certainmathematical operations return NaN as a result, for example,• 0.0/0.0• Inf-InfThe value of Not-a-Number is built in to the system. You cannot modifyit.CExamplesSee AlsoSee mxgetinf.c in the mx subdirectory of the examples directory.mxGetEps, mxGetInf2-159


mxGetNumberOfDimensions (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of dimensions in mxArray#include "matrix.h"mwSize mxGetNumberOfDimensions(const mxArray *pm);mwSize mxGetNumberOfDimensions(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesThe number of dimensions in the specified mxArray. The returned valueis always 2 or greater.Use mxGetNumberOfDimensions to determine how many dimensions arein the specified array. To determine how many elements are in eachdimension, call mxGetDimensions.See explore.c in the mex subdirectory of the examples directory.Additional examples:• findnz.c, fulltosparse.c, andphonebook.c in the refbooksubdirectory of the examples directory• mxcalcsinglesubscript.c, mxgeteps.c, andmxisfinite.c in themx subdirectory of the examples directory.See AlsomxSetM, mxSetN, mxGetDimensions2-160


mxGetNumberOfElements (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of elements in mxArray#include "matrix.h"size_t mxGetNumberOfElements(const mxArray *pm);mwSize mxGetNumberOfElements(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesNumber of elements in the specified mxArraymxGetNumberOfElements tells you how many elements an arrayhas. For example, if the dimensions of an array are 3-by-5-by-10,mxGetNumberOfElements returns the number 150.See findnz.c and phonebook.c in the refbook subdirectory of theexamples directory.Additional examples:• explore.c in the mex subdirectory of the examples directory• mxcalcsinglesubscript.c, mxgeteps.c, mxgetinf.c,mxisfinite.c, andmxsetdimensions.c in the mx subdirectory of theexamples directorySee AlsomxGetDimensions, mxGetM, mxGetN, mxGetClassID, mxGetClassName2-161


mxGetNumberOfFields (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of fields in structure mxArray#include "matrix.h"int mxGetNumberOfFields(const mxArray *pm);integer*4 mxGetNumberOfFields(pm)mwPointer pmArgumentspmPointer to a structure mxArrayReturnsDescriptionCExamplesThe number of fields, on success. Returns 0 on failure. The mostcommon cause of failure is that pm is not a structure mxArray. CallmxIsStruct to determine whether pm is a structure.Call mxGetNumberOfFields to determine how many fields are in thespecified structure mxArray.Once you know the number of fields in a structure, you can loop throughevery field in order to set or to get field values.See phonebook.c in the refbook subdirectory of the examples directory.Additional examples:• mxisclass.c in the mx subdirectory of the examples directory• explore.c in the mex subdirectory of the examples directory.See AlsomxGetField, mxIsStruct, mxSetField2-162


mxGetNzmax (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxNumber of elements in ir, pr, andpi arrays#include "matrix.h"mwSize mxGetNzmax(const mxArray *pm);mwSize mxGetNzmax(pm)mwPointer pmArgumentspmPointer to a sparse mxArrayReturnsDescriptionCExamplesSee AlsoThe number of elements allocated to hold nonzero entries in thespecified sparse mxArray, on success. Returns an indeterminate valueon error. The most likely cause of failure is that pm points to a full(nonsparse) mxArray.Use mxGetNzmax to get the value of the nzmax field. The nzmax fieldholds an integer value that signifies the number of elements in their, pr, and,ifitexists,thepi arrays. The value of nzmax is alwaysgreater than or equal to the number of nonzero elements in a sparsemxArray. In addition, the value of nzmax is always less than or equal tothe number of rows times the number of columns.As you adjust the number of nonzero elements in a sparse mxArray,MATLAB often adjusts the value of the nzmax field. MATLAB adjustsnzmax in order to reduce the number of costly reallocations and in orderto optimize its use of heap space.See mxgetnzmax.c and mxsetnzmax.c in the mx subdirectory of theexamples directory.mxSetNzmax2-163


mxGetPi (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxImaginary data elements in mxArray#include "matrix.h"double *mxGetPi(const mxArray *pm);mwPointer mxGetPi(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesThe imaginary data elements of the specified mxArray, on success.Returns NULL in C (0 in <strong>Fortran</strong>) if there is no imaginary data or if thereis an error.The pi field points to an array containing the imaginary data of themxArray. CallmxGetPi to get the contents of the pi field, that is, to getthe starting address of this imaginary data.The best way to determine whether an mxArray is purely real is to callmxIsComplex.The imaginary parts of all input matrices to a MATLAB function areallocated if any of the input matrices are complex.See convec.c, findnz.c, andfulltosparse.c in the refbooksubdirectory of the examples directory.Additional examples:• explore.c and mexcallmatlab.c in the mex subdirectory of theexamples directory• mxcalcsinglesubscript.c, mxgetinf.c, mxisfinite.c, andmxsetnzmax.c in the mx subdirectory of the examples directorySee AlsomxGetPr, mxSetPi, mxSetPr2-164


mxGetPr (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReal data elements in mxArray#include "matrix.h"double *mxGetPr(const mxArray *pm);mwPointer mxGetPr(pm)mwPointer pmArgumentspmPointer to an mxArrayReturns The address of the first element of the real data. Returns NULL in C (0in <strong>Fortran</strong>) if there is no real data.DescriptionCExamplesSee AlsoCall mxGetPr to determine the starting address of the real data in themxArray that pm points to. Once you have the starting address, you canaccess any other element in the mxArray.See convec.c, doubleelement.c, findnz.c, fulltosparse.c,sincall.c, timestwo.c, timestwoalt.c, andxtimesy.c in therefbook subdirectory of the examples directory.mxGetPi, mxSetPi, mxSetPr2-165


mxGetScalar (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReal component of first data element in mxArray#include "matrix.h"double mxGetScalar(const mxArray *pm);real*8 mxGetScalar(pm)mwPointer pmArgumentspmPointer to an mxArray; cannotbeacellmxArray, a structuremxArray, oranemptymxArrayReturnsDescriptionThe value of the first real (nonimaginary) element of the mxArray.Notice that in C, mxGetScalar returns a double. Therefore, if realelements in the mxArray are stored as something other than doubles,mxGetScalar automatically converts the scalar value into a double. Topreserve the original data representation of the scalar, you must castthe return value to the desired data type.mxGetScalar should only be called when pm points to a non-emptynumeric, logical, or char mxArray. Usemx functions such as mxIsEmpty,mxIsLogical, mxIsNumeric, ormxIsChar to test for this condition beforecalling mxGetScalar.If pm points to a sparse mxArray, mxGetScalar returns the value of thefirst nonzero real element in the mxArray.Call mxGetScalar to get the value of the first real (nonimaginary)element of the mxArray.In most cases, you call mxGetScalar when pm points to an mxArraycontaining only one element (a scalar). However, pm can point toan mxArray containing many elements. If pm points to an mxArraycontaining multiple elements, mxGetScalar returns the value ofthe first real element. If pm points to a two-dimensional mxArray,mxGetScalar returns the value of the (1,1) element; if pm points to2-166


mxGetScalar (C and <strong>Fortran</strong>)a three-dimensional mxArray, mxGetScalar returns the value of the(1,1,1) element; and so on.CExamplesSee timestwoalt.c and xtimesy.c in the refbook subdirectory of theexamples directory.Additional examples:• mxsetdimensions.c in the mx subdirectory of the examples directory• mexlock.c and mexsettrapflag.c in the mex subdirectory of theexamples directorySee AlsomxGetM, mxGetN2-167


mxGetString (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxCopy string mxArray to C-style string#include "matrix.h"int mxGetString(const mxArray *pm, char *str, mwSize strlen);integer*4 mxGetString(pm, str, strlen)mwPointer pmcharacter*(*) strmwSize strlenArgumentspmPointer to a string mxArray; thatis,apointertoanmxArrayhaving the mxCHAR_CLASS class.strThe starting location into which the string should be written.mxGetString writes the character data into str and then, in C,terminates the string with a NULL character (in the manner of Cstrings). str can point to either dynamic or static memory.strlenMaximum number of characters to read into str. Typically,inC,you set strlen to 1 plus the number of elements in the stringmxArray to which pm points. See the mxGetM and mxGetN referencepages to find out how to get the number of elements.Returns0 on success, and 1 on failure. Possible reasons for failure include• Specifying an mxArray that is not a string mxArray.• Specifying strlen with less than the number of characters neededto store the entire mxArray pointed to by pm. If this is the case, 1 isreturned and the string is truncated.DescriptionCall mxGetString to copy the character data of a string mxArray into aC-style string in C or a character array in <strong>Fortran</strong>. The copied stringstarts at str andcontainsnomorethanstrlen-1 characters in C (no2-168


mxGetString (C and <strong>Fortran</strong>)more than strlen characters in <strong>Fortran</strong>). In C, the C-style string isalways terminated with a NULL character.If the string array contains several rows, they are copied—one columnat a time—into one long string array.Note This function is for use only with strings that representsingle-byte character sets. For strings that represent multibytecharacter sets, use mxArrayToString.CExamplesSee AlsoExamples:• explore.c in the mex subdirectory of the examples directory• mxmalloc.c in the mx subdirectory of the examples directorymxArrayToString, mxCreateCharArray,mxCreateCharMatrixFromStrings, mxCreateString2-169


mxIsCell (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether input is cell mxArray#include "matrix.h"bool mxIsCell(const mxArray *pm);integer*4 mxIsCell(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifpm points to an array having the class mxCELL_CLASS,and logical 0 (false) otherwise.Use mxIsCell to determine whether the specified array is a cell array.In C, calling mxIsCell is equivalent to callingmxGetClassID(pm) == mxCELL_CLASSIn <strong>Fortran</strong>, calling mxIsCell is equivalent to callingmxGetClassName(pm) .eq. 'cell'Note mxIsCell does not answer the question “Is this mxArray acellofacell array?” An individual cell of a cell array can be of any type.See AlsomxIsClass2-170


mxIsChar (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether input is string mxArray#include "matrix.h"bool mxIsChar(const mxArray *pm);integer*4 mxIsChar(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifpm points to an array having the class mxCHAR_CLASS,and logical 0 (false) otherwise.Use mxIsChar to determine whether pm points to string mxArray.In C, calling mxIsChar is equivalent to callingmxGetClassID(pm) == mxCHAR_CLASSIn <strong>Fortran</strong>, calling mxIsChar is equivalent to callingmxGetClassName(pm) .eq. 'char'CExamplesSee AlsoSee phonebook.c and revord.c in the refbook subdirectory of theexamples directory.For additional examples, see mxcreatecharmatrixfromstr.c,mxislogical.c, andmxmalloc.c in the mx subdirectory of the examplesdirectory.mxIsClass, mxGetClassID2-171


mxIsClass (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDetermine whether mxArray is member of specified class#include "matrix.h"bool mxIsClass(const mxArray *pm, const char *classname);integer*4 mxIsClass(pm, classname)mwPointer pmcharacter*(*) classnamepmPointer to an mxArrayclassnameThe array category that you are testing. Specify classname as astring (not as an integer identifier). You can specify any one of thefollowing predefined constants:Value ofclassnamecellchardoublefunction_handleint8int16int32int64logicalsinglestructuint8Corresponding ClassmxCELL_CLASSmxCHAR_CLASSmxDOUBLE_CLASSmxFUNCTION_CLASSmxINT8_CLASSmxINT16_CLASSmxINT32_CLASSmxINT64_CLASSmxLOGICAL_CLASSmxSINGLE_CLASSmxSTRUCT_CLASSmxUINT8_CLASS2-172


mxIsClass (C and <strong>Fortran</strong>)Value ofclassnameuint16uint32uint64unknownCorresponding ClassmxUINT16_CLASSmxUINT32_CLASSmxUINT64_CLASSmxUNKNOWN_CLASSIn the table, represents the name of a specific MATLABcustom object. You can also specify one of your own class names.ReturnsDescriptionLogical 1 (true) ifpm points to an array having category classname,and logical 0 (false) otherwise.Each mxArray is tagged as being a certain type. Call mxIsClass todetermine whether the specified mxArray has this type.In C,mxIsClass("double");is equivalent to calling either of these forms:mxIsDouble(pm);strcmp(mxGetClassName(pm), "double");In <strong>Fortran</strong>,mxIsClass(pm, 'double')is equivalent to calling either one of the followingmxIsDouble(pm)mxGetClassName(pm) .eq. 'double'2-173


mxIsClass (C and <strong>Fortran</strong>)It is most efficient to use the mxIsDouble form.CExamplesSee AlsoSee mxisclass.c in the mx subdirectory of the examples directory.mxClassID, mxGetClassID, mxIsEmpty2-174


mxIsComplex (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether data is complex#include "matrix.h"bool mxIsComplex(const mxArray *pm);integer*4 mxIsComplex(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesLogical 1 (true) ifpm is a numeric array containing complex data, andlogical 0 (false) otherwise. Ifpm points to a cell array or a structurearray, mxIsComplex returns false.Use mxIsComplex to determine whether or not an imaginary part isallocated for an mxArray. The imaginary pointer pi is NULL in C (0L in<strong>Fortran</strong>) if an mxArray is purely real and does not have any imaginarydata. If an mxArray is complex, pi points to an array of numbers.See mxisfinite.c in the mx subdirectory of the examples directory.Additional examples:• convec.c, phonebook.c, timestwo.c, andxtimesy.c in the refbooksubdirectory of the examples directory• explore.c, yprime.c, mexlock.c, andmexsettrapflag.c in the mexsubdirectory of the examples directory• mxcalcsinglesubscript.c, mxgeteps.c, andmxgetinf.c in the mxsubdirectory of the examples directorySee AlsomxIsNumeric2-175


mxIsDouble (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as double-precision,floating-point numbers#include "matrix.h"bool mxIsDouble(const mxArray *pm);integer*4 mxIsDouble(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifthemxArray stores its data as double-precision,floating-point numbers, and logical 0 (false) otherwise.Call mxIsDouble to determine whether or not the specified mxArrayrepresents its real and imaginary data as double-precision,floating-point numbers.Older versions of MATLAB store all mxArray data as double-precision,floating-point numbers. However, starting with MATLAB Version 5,MATLAB can store real and imaginary data in a variety of numericalformats.In C, calling mxIsDouble is equivalent to callingmxGetClassID(pm) == mxDOUBLE_CLASSIn <strong>Fortran</strong>, calling mxIsDouble is equivalent to callingmxGetClassName(pm) .eq. 'double'CExamplesSee findnz.c, fulltosparse.c, timestwo.c, andxtimesy.c in therefbook subdirectory of the examples directory.Additional examples:2-176


mxIsDouble (C and <strong>Fortran</strong>)• mexget.c, mexlock.c, mexsettrapflag.c, andyprime.c in the mexsubdirectory of the examples directory• mxcalcsinglesubscript.c, mxgeteps.c, mxgetinf.c, andmxisfinite.c in the mx subdirectory of the examples directorySee AlsomxIsClass, mxGetClassID2-177


mxIsEmpty (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray is empty#include "matrix.h"bool mxIsEmpty(const mxArray *pm);integer*4 mxIsEmpty(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) ifthemxArray is empty, and logical 0 (false) otherwise.Use mxIsEmpty to determine whether an mxArray contains no data. AnmxArray is empty if the size of any of its dimensions is 0.See mxisfinite.c in the mx subdirectory of the examples directory.mxIsClass2-178


mxIsFinite (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionCExamplesSee AlsoDetermine whether input is finite#include "matrix.h"bool mxIsFinite(double value);integer*4 mxIsFinite(value)real*8 valuevalueThe double-precision, floating-point number that you are testingLogical 1 (true) ifvalue is finite, and logical 0 (false) otherwise.Call mxIsFinite to determine whether or not value is finite. A numberis finite if it is greater than -Inf and less than Inf.See mxisfinite.c in the mx subdirectory of the examples directory.mxIsInf, mxIsNan2-179


mxIsFromGlobalWS (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray was copied from MATLAB globalworkspace#include "matrix.h"bool mxIsFromGlobalWS(const mxArray *pm);integer*4 mxIsFromGlobalWS(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) if the array was copied out of the global workspace,and logical 0 (false) otherwise.mxIsFromGlobalWS is useful for stand-alone MAT programs.mexIsGlobal tells you whether the pointer you pass actually pointsinto the global workspace.See matdgns.c and matcreat.c in the eng_mat subdirectory of theexamples directory.mexIsGlobal2-180


mxIsInf (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionDetermine whether input is infinite#include "matrix.h"bool mxIsInf(double value);integer*4 mxIsInf(value)real*8 valuevalueThe double-precision, floating-point number that you are testingLogical 1 (true) if value is infinite, and logical 0 (false) otherwise.Call mxIsInf to determine whether or not value is equal to infinity orminus infinity. MATLAB stores the value of infinity in a permanentvariable named Inf, which represents IEEE arithmetic positive infinity.The value of the variable Inf is built into the system; you cannot modifyit.Operations that return infinity include• Division by 0. For example, 5/0 returns infinity.• Operations resulting in overflow. For example, exp(10000) returnsinfinity because the result is too large to be represented on yourmachine.If value equals NaN (Not-a-Number), mxIsInf returns false. Inotherwords, NaN is not equal to infinity.CExamplesSee AlsoSee mxisfinite.c in the mx subdirectory of the examples directory.mxIsFinite, mxIsNaN2-181


mxIsInt16 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as signed 16-bit integers#include "matrix.h"bool mxIsInt16(const mxArray *pm);integer*4 mxIsInt16(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) if the array stores its data as signed 16-bit integers,and logical 0 (false) otherwise.Use mxIsInt16 to determine whether or not the specified arrayrepresents its real and imaginary data as 16-bit signed integers.In C, calling mxIsInt16 is equivalent to callingmxGetClassID(pm) == mxINT16_CLASSIn <strong>Fortran</strong>, calling mxIsInt16 is equivalent to callingmxGetClassName(pm) == 'int16'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt32, mxIsInt64,mxIsUint8, mxIsUint16, mxIsUint32, mxIsUint642-182


mxIsInt32 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as signed 32-bit integers#include "matrix.h"bool mxIsInt32(const mxArray *pm);integer*4 mxIsInt32(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) if the array stores its data as signed 32-bit integers,and logical 0 (false) otherwise.Use mxIsInt32 to determine whether or not the specified arrayrepresents its real and imaginary data as 32-bit signed integers.In C, calling mxIsInt32 is equivalent to callingmxGetClassID(pm) == mxINT32_CLASSIn <strong>Fortran</strong>, calling mxIsInt32 is equivalent to callingmxGetClassName(pm) == 'int32'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt64,mxIsUint8, mxIsUint16, mxIsUint32, mxIsUint642-183


mxIsInt64 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as signed 64-bit integers#include "matrix.h"bool mxIsInt64(const mxArray *pm);integer*4 mxIsInt64(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) if the array stores its data as signed 64-bit integers,and logical 0 (false) otherwise.Use mxIsInt64 to determine whether or not the specified arrayrepresents its real and imaginary data as 64-bit signed integers.In C, calling mxIsInt64 is equivalent to callingmxGetClassID(pm) == mxINT64_CLASSIn <strong>Fortran</strong>, calling mxIsInt64 is equivalent to callingmxGetClassName(pm) == 'int64'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt32,mxIsUint8, mxIsUint16, mxIsUint32, mxIsUint642-184


mxIsInt8 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as signed 8-bit integers#include "matrix.h"bool mxIsInt8(const mxArray *pm);integer*4 mxIsInt8(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) if the array stores its data as signed 8-bit integers,and logical 0 (false) otherwise.Use mxIsInt8 to determine whether or not the specified arrayrepresents its real and imaginary dataas8-bitsignedintegers.In C, calling mxIsInt8 is equivalent to callingmxGetClassID(pm) == mxINT8_CLASSIn <strong>Fortran</strong>, calling mxIsInt8 is equivalent to callingmxGetClassName(pm) .eq. 'int8'See AlsomxIsClass, mxGetClassID, mxIsInt16, mxIsInt32, mxIsInt64,mxIsUint8, mxIsUint16, mxIsUint32, mxIsUint642-185


mxIsLogical (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray is of class mxLogical#include "matrix.h"bool mxIsLogical(const mxArray *pm);integer*4 mxIsLogical(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) ifpm points to a logical mxArray, andlogical0 (false)otherwise.Use mxIsLogical to determine whether MATLAB treats the data in themxArray as Boolean (logical). If an mxArray is logical, MATLAB treatsall zeros as meaning false and all nonzero values as meaning true.For additional information on the use of logical variables in MATLAB,type help logical at the MATLAB prompt.See mxislogical.c in the mx subdirectory of the examples directory.mxIsClass2-186


mxIsLogicalScalar (C)PurposeCSyntaxArgumentsReturnsDescriptionDetermine whether scalar mxArray is of class mxLogical#include "matrix.h"bool mxIsLogicalScalar(const mxArray *array_ptr);array_ptrPointer to an mxArrayLogical 1 (true) ifthemxArray is of class mxLogical and has 1-by-1dimensions, and logical 0 (false) otherwise.Use mxIsLogicalScalar to determine whether MATLAB treats thescalar data in the mxArray as logical or numerical. For additionalinformation on the use of logical variables in MATLAB, type helplogical at the MATLAB prompt.mxIsLogicalScalar(pa) is equivalent tomxIsLogical(pa) && mxGetNumberOfElements(pa) == 1See AlsomxIsLogical, mxIsLogicalScalarTrue, mxGetLogicals, mxGetScalar2-187


mxIsLogicalScalarTrue (C)PurposeCSyntaxArgumentsReturnsDescriptionDetermine whether scalar mxArray of class mxLogical is true#include "matrix.h"bool mxIsLogicalScalarTrue(const mxArray *array_ptr);array_ptrPointer to an mxArrayLogical 1 (true) ifthevalueofthemxArray’s logical, scalar element istrue, andlogical0 (false) otherwise.Use mxIsLogicalScalarTrue to determine whether the value of a scalarmxArray is true or false. For additional information on the use of logicalvariables in MATLAB, type help logical at the MATLAB prompt.mxIsLogicalScalarTrue(pa) is equivalent tomxIsLogical(pa) && mxGetNumberOfElements(pa) == 1 &&mxGetLogicals(pa)[0] == trueSee AlsomxIsLogical, mxIsLogicalScalar, mxGetLogicals, mxGetScalar2-188


mxIsNaN (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsReturnsDescriptionDetermine whether input is NaN (Not-a-Number)#include "matrix.h"bool mxIsNaN(double value);integer*4 mxIsNaN(value)real*8 valuevalueThe double-precision, floating-point number that you are testingLogical 1 (true) ifvalue is NaN (Not-a-Number), and logical 0 (false)otherwise.Call mxIsNaN to determine whether or not value is NaN. NaN is the IEEEarithmetic representation for Not-a-Number. A NaN is obtained as aresult of mathematically undefined operations such as• 0.0/0.0• Inf-InfThe system understands a family of bitpatternsasrepresentingNaN. Inother words, NaN is not a single value; rather, it is a family of numbersthat MATLAB (and other IEEE-compliant applications) use to representan error condition or missing data.CExamplesSee AlsoSee mxisfinite.c in the mx subdirectory of the examples directory.For additional examples, see findnz.c and fulltosparse.c in therefbook subdirectory of the examples directory.mxIsFinite, mxIsInf2-189


mxIsNumeric (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray is numeric#include "matrix.h"bool mxIsNumeric(const mxArray *pm);integer*4 mxIsNumeric(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsLogical 1 (true) if the array can contain numeric data. The followingclass IDs represent storage types for arrays that can contain numericdata:• mxDOUBLE_CLASS• mxSINGLE_CLASS• mxINT8_CLASS• mxUINT8_CLASS• mxINT16_CLASS• mxUINT16_CLASS• mxINT32_CLASS• mxUINT32_CLASS• mxINT64_CLASS• mxUINT64_CLASSLogical 0 (false) if the array cannot contain numeric data.DescriptionCall mxIsNumeric to determine whether the specified array containsnumeric data. If the specified array has a storage type that represents2-190


mxIsNumeric (C and <strong>Fortran</strong>)numeric data, mxIsNumeric returns logical 1 (true). Otherwise,mxIsNumeric returns logical 0 (false).Call mxGetClassID to determine the exact storage type.CExamples<strong>Fortran</strong>ExamplesSee AlsoSee phonebook.c in the refbook subdirectory of the examples directory.See matdemo1.F in the eng_mat subdirectory of the examples directory.mxGetClassID2-191


mxIsSingle (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as single-precision,floating-point numbers#include "matrix.h"bool mxIsSingle(const mxArray *pm);integer*4 mxIsSingle(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) if the array stores its data as single-precision,floating-point numbers, and logical 0 (false) otherwise.Use mxIsSingle to determine whether or not the specified arrayrepresents its real and imaginary data as single-precision, floating-pointnumbers.In C, calling mxIsSingle is equivalent to callingmxGetClassID(pm) == mxSINGLE_CLASSIn <strong>Fortran</strong>, calling mxIsSingle is equivalent to callingmxGetClassName(pm) .eq. 'single'See AlsomxIsClass, mxGetClassID2-192


mxIsSparse (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether input is sparse mxArray#include "matrix.h"bool mxIsSparse(const mxArray *pm);integer*4 mxIsSparse(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) ifpm points to a sparse mxArray, andlogical0 (false)otherwise. A false return value means that pm points to a full mxArrayor that pm does not point to a legal mxArray.Use mxIsSparse to determine whether pm points to a sparse mxArray.Many routines (for example, mxGetIr and mxGetJc) require a sparsemxArray as input.See phonebook.c in the refbook subdirectory of the examples directory.For additional examples, see mxgetnzmax.c, mxsetdimensions.c, andmxsetnzmax.c in the mx subdirectory of the examples directory.mxGetIr, mxGetJc, mxCreateSparse2-193


mxIsStruct (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether input is structure mxArray#include "matrix.h"bool mxIsStruct(const mxArray *pm);integer*4 mxIsStruct(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionCExamplesSee AlsoLogical 1 (true) ifpm points to a structure mxArray, andlogical0(false) otherwise.Use mxIsStruct to determine whether pm points to a structure mxArray.Many routines (for example, mxGetFieldName and mxSetField) requireastructuremxArray as an argument.See phonebook.c in the refbook subdirectory of the examples directory.mxCreateStructArray, mxCreateStructMatrix,mxGetNumberOfFields, mxGetField, mxSetField2-194


mxIsUint16 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as unsigned 16-bit integers#include "matrix.h"bool mxIsUint16(const mxArray *pm);integer*4 mxIsUint16(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifthemxArray stores its data as unsigned 16-bitintegers, and logical 0 (false) otherwise.Use mxIsUint16 to determine whether or not the specified mxArrayrepresents its real and imaginary data as 16-bit unsigned integers.In C, calling mxIsUint16 is equivalent to callingmxGetClassID(pm) == mxUINT16_CLASSIn <strong>Fortran</strong>, calling mxIsUint16 is equivalent to callingmxGetClassName(pm) .eq. 'uint16'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt32,mxIsInt64, mxIsUint8, mxIsUint32, mxIsUint642-195


mxIsUint32 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as unsigned 32-bit integers#include "matrix.h"bool mxIsUint32(const mxArray *pm);integer*4 mxIsUint32(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifthemxArray stores its data as unsigned 32-bitintegers, and logical 0 (false) otherwise.Use mxIsUint32 to determine whether or not the specified mxArrayrepresents its real and imaginary data as 32-bit unsigned integers.In C, calling mxIsUint32 is equivalent to callingmxGetClassID(pm) == mxUINT32_CLASSIn <strong>Fortran</strong>, calling mxIsUint32 is equivalent to callingmxGetClassName(pm) .eq. 'uint32'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt32,mxIsInt64, mxIsUint8, mxIsUint16, mxIsUint642-196


mxIsUint64 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as unsigned 64-bit integers#include "matrix.h"bool mxIsUint64(const mxArray *pm);integer*4 mxIsUint64(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifthemxArray stores its data as unsigned 64-bitintegers, and logical 0 (false) otherwise.Use mxIsUint64 to determine whether or not the specified mxArrayrepresents its real and imaginary data as 64-bit unsigned integers.In C, calling mxIsUint64 is equivalent to callingmxGetClassID(pm) == mxUINT64_CLASSIn <strong>Fortran</strong>, calling mxIsUint64 is equivalent to callingmxGetClassName(pm) .eq. 'uint64'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt32,mxIsInt64, mxIsUint8, mxIsUint16, mxIsUint322-197


mxIsUint8 (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxDetermine whether mxArray represents data as unsigned 8-bit integers#include "matrix.h"bool mxIsUint8(const mxArray *pm);integer*4 mxIsUint8(pm)mwPointer pmArgumentspmPointer to an mxArrayReturnsDescriptionLogical 1 (true) ifthemxArray stores its data as unsigned 8-bit integers,and logical 0 (false) otherwise.Use mxIsUint8 to determine whether or not the specified mxArrayrepresents its real and imaginary data as 8-bit unsigned integers.In C, calling mxIsUint8 is equivalent to callingmxGetClassID(pm) == mxUINT8_CLASSIn <strong>Fortran</strong>, calling mxIsUint8 is equivalent to callingmxGetClassName(pm) .eq. 'uint8'See AlsomxIsClass, mxGetClassID, mxIsInt8, mxIsInt16, mxIsInt32,mxIsInt64, mxIsUint16, mxIsUint32, mxIsUint642-198


mxMalloc (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxAllocate dynamic memory using MATLAB memory manager#include "matrix.h"#include void *mxMalloc(size_t n);mwPointer mxMalloc(n)mwSize nArgumentsnNumber of bytes to allocateReturnsDescriptionA pointer to the start of the allocated dynamic memory, if successful.If unsuccessful in a stand-alone (nonMEX-file) application, mxMallocreturns NULL in C (0 in <strong>Fortran</strong>). If unsuccessful in a MEX-file, theMEX-file terminates and control returns to the MATLAB prompt.mxMalloc is unsuccessful when there is insufficient free heap space.MATLAB applications should always call mxMalloc rather than mallocto allocate memory.mxMalloc works differently in MEX-files than in stand-alone MATLABapplications. In MEX-files, mxMalloc automatically• Allocates enough contiguous heap space to hold n bytes.• Registers the returned heap space with the MATLAB memorymanagement facility.The MATLAB memory management facility maintains a list of allmemory allocated by mxMalloc. The MATLAB memory managementfacility automatically frees (deallocates) all of a MEX-file’s parcels whencontrol returns to the MATLAB prompt.In stand-alone MATLAB C applications, mxMalloc calls the ANSI Cmalloc function.2-199


mxMalloc (C and <strong>Fortran</strong>)By default, in a MEX-file, mxMalloc generates nonpersistentmxMalloc data. In other words, the memory management facilityautomatically deallocates the memoryassoonastheMEX-fileends.If you want the memory to persist after the MEX-file completes, callmexMakeMemoryPersistent after calling mxMalloc. If you write aMEX-file with persistent memory, be sure to register a mexAtExitfunction to free allocated memory in the event your MEX-file is cleared.When you finish using the memory allocated by mxMalloc, callmxFree.mxFree deallocates the memory.CExamplesSee AlsoSee mxmalloc.c in the mx subdirectory of the examples directory. Foran additional example, see mxsetdimensions.c in the mx subdirectoryof the examples directory.mexAtExit, mexMakeArrayPersistent, mexMakeMemoryPersistent,mxCalloc, mxDestroyArray, mxFree, mxRealloc2-200


mxRealloc (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxReallocate memory#include "matrix.h"#include void *mxRealloc(void *ptr, size_t size);mwPointer mxRealloc(ptr, size)mwPointer ptrmwSize sizeArgumentsptrsizePointer to a block of memory allocated by mxCalloc, mxMalloc,or mxReallocNew size of allocated memory, in bytesReturnsDescriptionA pointer to the reallocated block of memory, or NULL in C (0 in <strong>Fortran</strong>)if size is 0. Inastand-alone(non-MEX-file) application, if not enoughmemory is available to expand the block to the given size, mxReallocreturns NULL in C (0 in <strong>Fortran</strong>). In a MEX-file, if not enough memory isavailabletoexpandtheblocktothegivensize,theMEX-fileterminatesand control returns to the MATLAB prompt.mxRealloc changes the size of a memory block that has been allocatedwith mxCalloc, mxMalloc, ormxRealloc.If size is 0 and ptr is not NULL in C (0 in <strong>Fortran</strong>), mxRealloc frees thememory pointed to by ptr and returns NULL in C (0 in <strong>Fortran</strong>).If size is greater than 0 and ptr is NULL in C (0 in <strong>Fortran</strong>), mxReallocbehaves like mxMalloc, allocating a new block of memory of size bytesand returning a pointer to the new block.Otherwise, mxRealloc changes the size of the memory block pointedto by ptr to size bytes. The contents of the reallocated memory areunchanged up to the smaller of the new and old sizes. The reallocatedmemory may be in a different location from the original memory, so2-201


mxRealloc (C and <strong>Fortran</strong>)the returned pointer can be different from ptr. If the memory locationchanges, mxRealloc frees the original memory block pointed to by ptr.In a stand-alone (non-MEX-file) application, if not enough memory isavailable to expand the block to the given size, mxRealloc returns NULLin C (0 in <strong>Fortran</strong>) and leaves the original memory block unchanged.You must use mxFree to free the original memory block.MATLAB maintains a list of all memory allocated by mxRealloc. Bydefault, in a MEX-file, mxRealloc generates nonpersistent mxReallocdata. The memory management facility automatically deallocates thememory as soon as the MEX-file ends.If you want the memory to persist after a MEX-file completes, callmexMakeMemoryPersistent after calling mxRealloc. IfyouwriteaMEX-file with persistent memory, be sure to register a mexAtExitfunction to free allocated memory when your MEX-file is cleared.When you finish using the memory allocated by mxRealloc, callmxFree.mxFree deallocates the memory.CExamplesSee AlsoSee mxsetnzmax.c in the mx subdirectory of the examples directory.mexAtExit, mexMakeArrayPersistent, mexMakeMemoryPersistent,mxCalloc, mxDestroyArray, mxFree, mxMalloc2-202


mxRemoveField (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionRemove field from structure array#include "matrix.h"extern void mxRemoveField(mxArray pm, int fieldnumber);subroutine mxRemoveField(pm, fieldnumber)mwPointer pminteger*4 fieldnumberpmPointer to a structure mxArrayfieldnumberThe number of the field you want to remove. In C, to remove thefirst field, set fieldnumber to 0; toremovethesecondfield,setfieldnumber to 1; and so on. In <strong>Fortran</strong>, to remove the first field,set fieldnumber to 1; toremovethesecondfield,setfieldnumberto 2; andsoon.Call mxRemoveField to remove a field from a structure array. If the fielddoes not exist, nothing happens. This function does not destroy the fieldvalues. Use mxDestroyArray to destroy the actual field values.Consider a MATLAB structure initialized topatient.name = 'John Doe';patient.billing = 127.00;patient.test = [79 75 73; 180 178 177.5; 220 210 205];In C, the field number 0 represents the field name; field number 1represents field billing; field number 2 represents field test. In<strong>Fortran</strong>, the field number 1 represents the field name; field number 2represents field billing; field number 3 represents field test.See AlsomxAddField, mxDestroyArray, mxGetFieldByNumber2-203


mxSetCell (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionSet value of one cell of mxArray#include "matrix.h"void mxSetCell(mxArray *pm, mwIndex index, mxArray *value);subroutine mxSetCell(pm, index, value)mwPointer pm, valuemwIndex indexpmPointer to a cell mxArrayindexIndex from the beginning of the mxArray. Specify the numberof elements between the first cell of the mxArray and thecell you want to set. The easiest way to calculate index in amultidimensional cell array is to call mxCalcSingleSubscript.valueThe new value of the cell. You can put any kind of mxArray into acell. In fact, you can even put another cell mxArray into a cell.Call mxSetCell to put the designated value into a particular cell ofacellmxArray.Note Inputs to a MEX-file are constant read-only mxArrays and shouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetCell before you call mxSetCell.2-204


mxSetCell (C and <strong>Fortran</strong>)CExamplesSee AlsoSee phonebook.c in the refbook subdirectory of the examples directory.For an additional example, see mxcreatecellmatrix.c in the mxsubdirectory of the examples directory.mxCreateCellArray, mxCreateCellMatrix, mxGetCell, mxIsCell,mxFree2-205


mxSetClassName (C)PurposeCSyntaxArgumentsReturnsDescriptionSee AlsoConvert structure array to MATLAB object array#include "matrix.h"int mxSetClassName(mxArray *array_ptr, const char *classname);array_ptrPointer to an mxArray of class mxSTRUCT_CLASSclassnameTheobjectclasstowhichtoconvertarray_ptr0 if successful, and nonzero otherwise.mxSetClassName converts a structure array to an object array, to besaved subsequently to a MAT-file. The object is not registered orvalidated by MATLAB until it is loaded via the LOAD command. Ifthe specified classname is an undefined class within MATLAB, LOADconverts the object back to a simple structure array.mxIsClass, mxGetClassID2-206


mxSetData (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet pointer to data#include "matrix.h"void mxSetData(mxArray *pm, void *pr);subroutine mxSetData(pm, pr)mwPointer pm, prArgumentspmprPointer to an mxArrayPointer to an array. Each element in the array contains the realcomponent of a value. The array must be in dynamic memory; callmxCalloc to allocate this memory.DescriptionSee AlsomxSetData is similar to mxSetPr, exceptthatinC,itssecondargumentis a void *. Use this on numeric arrays with contents other thandouble.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetData before you call mxSetData.mxCalloc, mxFree, mxGetData, mxSetPr2-207


mxSetDimensions (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsModify number of dimensions and size of each dimension#include "matrix.h"int mxSetDimensions(mxArray *pm, const mwSize *dims,mwSize ndim);integer*4 mxSetDimensions(pm, dims, ndim)mwPointer pmmwSize dims, ndimpmdimsPointer to an mxArrayThe dimensions array. Each element in the dimensions arraycontains the size of the array in that dimension. For example,in C, setting dims[0] to 5 and dims[1] to 7 establishes a 5-by-7mxArray. In <strong>Fortran</strong>, setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray. In most cases, there should be ndimelements in the dims array.ndimThe desired number of dimensionsReturnsDescription0 on success, and 1 on failure. mxSetDimensions allocates heap space tohold the input size array. So it is possible (though extremely unlikely)that increasing the number of dimensions can cause the system to runout of heap space.Call mxSetDimensions to reshape an existing mxArray.mxSetDimensions is similar to mxSetM and mxSetN; however,mxSetDimensions provides greater control for reshaping mxArrays thathave more than two dimensions.mxSetDimensions does not allocate or deallocate any space for the pror pi arrays. Consequently, if your call to mxSetDimensions increasesthe number of elements in the mxArray, youmustenlargethepr (andpi, if it exists) arrays accordingly.2-208


mxSetDimensions (C and <strong>Fortran</strong>)If your call to mxSetDimensions reduces the number of elements in themxArray, you can optionally reduce the size of the pr and pi arraysusing mxRealloc.Any trailing singleton dimensions specified in the dims argument areautomatically removed from the resulting array. For example, if ndimequals 5 and dims equals [4 1 7 1 1], the resulting array is giventhe dimensions 4-by-1-by-7.CExamplesSee AlsoSee mxsetdimensions.c in the mx subdirectory of the examplesdirectory.mxGetNumberOfDimensions, mxSetM, mxSetN, mxRealloc2-209


mxSetField (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionSet structure array field, given field name and index#include "matrix.h"void mxSetField(mxArray *pm, mwIndex index,const char *fieldname, mxArray *value);subroutine mxSetField(pm, index, fieldname, value)mwPointer pm, valuemwIndex indexcharacter*(*) fieldnamepmPointer to a structure mxArray. Call mxIsStruct to determinewhether pm points to a structure mxArray.indexIndex of the desired element. In C, the first element of anmxArray has an index of 0, the second element has an index of 1,and the last element has an index of N-1, whereN is the totalnumber of elements in the structure mxArray. In<strong>Fortran</strong>,thefirst element of an mxArray has an index of 1, the second elementhas an index of 2, and the last element has an index of N. SeemxCalcSingleSubscript for details on calculating an index.fieldnameThenameofthefieldwhosevalueyouareassigning. CallmxGetFieldNameByNumber or mxGetFieldNumber to determineexisting field names.valuePointer to the mxArray you are assigning.Use mxSetField to assign a value to the specified element of thespecified field. In pseudo-C terminology, mxSetField performs theassignmentpm[index].fieldname = value;2-210


mxSetField (C and <strong>Fortran</strong>)Note Inputs to a MEX-file are constant read-only mxArrays and shouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.In C, callingmxSetField(pa, index, "fieldname", new_value_pa);is equivalent to callingfield_num = mxGetFieldNumber(pa, "fieldname");mxSetFieldByNumber(pa, index, field_num, new_value_pa);In <strong>Fortran</strong>, callingmxSetField(pm, index, 'fieldname', newvalue)is equivalent to callingfieldnum = mxGetFieldNumber(pm, 'fieldname')mxSetFieldByNumber(pm, index, fieldnum, newvalue)This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetField before you call mxSetField.CExamplesSee AlsoSee mxcreatestructarray.c in the mx subdirectory of the examplesdirectory.mxCreateStructArray, mxCreateStructMatrix, mxGetField,mxGetFieldByNumber, mxGetFieldNameByNumber, mxGetFieldNumber,mxGetNumberOfFields, mxIsStruct, mxSetFieldByNumber, mxFree2-211


mxSetFieldByNumber (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionSet structure array field, given field number and index#include "matrix.h"void mxSetFieldByNumber(mxArray *pm, mwIndex index,int fieldnumber, mxArray *value);subroutine mxSetFieldByNumber(pm, index, fieldnumber, value)mwPointer pm, valuemwIndex indexinteger*4 fieldnumberpmPointer to a structure mxArray. Call mxIsStruct to determinewhetherpm points to a structure mxArray.indexThe desired element. In C, the first element of an mxArray hasan index of 0, the second element has an index of 1, andthelast element has an index of N-1, whereN is the total numberof elements in the structure mxArray. In <strong>Fortran</strong>, the firstelement of an mxArray has an index of 1, the second elementhas an index of 2, and the last element has an index of N. SeemxCalcSingleSubscript for details on calculating an index.fieldnumberThe position of the field whose value you want to extract. In C,the first field within each element has a fieldnumber of 0, thesecond field has a fieldnumber of 1, and so on. The last fieldhas a fieldnumber of N-1, whereN is the number of fields. In<strong>Fortran</strong>, the first field within each element has a fieldnumber of1, thesecondfieldhasafieldnumber of 2, and so on. The lastfield has a fieldnumber of N.valueThe value you are assigning.Use mxSetFieldByNumber to assign a value to the specified elementof the specified field. mxSetFieldByNumber is almost identical to2-212


mxSetFieldByNumber (C and <strong>Fortran</strong>)mxSetField; however, the former takes a field number as its thirdargument and the latter takes a field name as its third argument.Note Inputs to a MEX-file are constant read-only mxArrays andshouldnot be modified. Using mxSetCell* or mxSetField* to modify the cellsor fields of an argument passed from MATLAB causes unpredictableresults.In C, callingmxSetField(pa, index, "field_name", new_value_pa);is equivalent to callingfield_num = mxGetFieldNumber(pa, "field_name");mxSetFieldByNumber(pa, index, field_num, new_value_pa);In <strong>Fortran</strong>, callingmxSetField(pm, index, 'fieldname', newvalue)is equivalent to callingfieldnum = mxGetFieldNumber(pm, 'fieldname')mxSetFieldByNumber(pm, index, fieldnum, newvalue)This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetFieldByNumber before you call mxSetFieldByNumber.CExamplesSee mxcreatestructarray.c in the mx subdirectory of the examplesdirectory. For an additional example, see phonebook.c in the refbooksubdirectory of the examples directory.2-213


mxSetFieldByNumber (C and <strong>Fortran</strong>)See AlsomxCreateStructArray, mxCreateStructMatrix, mxGetField,mxGetFieldByNumber, mxGetFieldNameByNumber, mxGetFieldNumber,mxGetNumberOfFields, mxIsStruct, mxSetField, mxFree2-214


mxSetImagData (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet imaginary data pointer for mxArray#include "matrix.h"void mxSetImagData(mxArray *pm, void *pi);subroutine mxSetImagData(pm, pi)mwPointer pm, piArgumentspmpiPointer to an mxArrayPointer to the first element of an array. Each element in the arraycontains the imaginary component of a value. The array mustbe in dynamic memory; call mxCalloc to allocate this dynamicmemory. If pi points to static memory, memory errors will resultwhen the array is destroyed.DescriptionCExamplesSee AlsomxSetImagData is similar to mxSetPi, exceptthatinC,itspi argumentis a void *. Use this on numeric arrays with contents other thandouble.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetImagData before you call mxSetImagData.See mxisfinite.c in the mx subdirectory of the examples directory.mxCalloc, mxFree, mxGetImagData, mxSetPi2-215


mxSetIr (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet ir array of sparse mxArray#include "matrix.h"void mxSetIr(mxArray *pm, mwIndex *ir);subroutine mxSetIr(pm, ir)mwPointer pm, irArgumentspmirPointer to a sparse mxArrayPointer to the ir array. The ir array must be sorted incolumn-major order.DescriptionUse mxSetIr to specify the ir array of a sparse mxArray. Their arrayis an array of integers; the length of the ir array should equal thevalue of nzmax.Each element in the ir array indicates a row (offset by 1) at which anonzero element can be found. (The jc array is an index that indirectlyspecifies a column where nonzero elements can be found. See mxSetJcfor more details on jc.)For example, suppose you create a 7-by-3 sparse mxArray namedSparrow containing six nonzero elements by typingSparrow = zeros(7,3);Sparrow(2,1) = 1;Sparrow(5,1) = 1;Sparrow(3,2) = 1;Sparrow(2,3) = 2;Sparrow(5,3) = 1;Sparrow(6,3) = 1;Sparrow = sparse(Sparrow);2-216


mxSetIr (C and <strong>Fortran</strong>)The pr array holds the real data for the sparse matrix, which in Sparrowis the five 1s and the one 2. If there is any nonzero imaginary data, itis in a pi array.Subscript ir pr jc Comments(2,1) 1 1 0 Column 1; ir is 1 because row is 2.(5,1) 4 1 2 Column 1; ir is 4 because row is 5.(3,2) 2 1 3 Column 2; ir is 2 because row is 3.(2,3) 1 2 6 Column 3; ir is 1 because row is 2.(5,3) 4 1 Column 3; ir is 4 because row is 5.(6,3) 5 1 Column 3; ir is 5 because row is 6.Notice how each element of the ir arrayisalways1lessthantherowof the corresponding nonzero element. For instance, the first nonzeroelement is in row 2; therefore, the first element in ir is 1 (that is, 2– 1). The second nonzero element is in row 5; therefore, the secondelement in ir is4(5–1).The ir array must be in column-major order. That means that the irarray must define the row positions in column 1 (if any) first, then therow positions in column 2 (if any) second, and so on through column N.Within each column, row position 1 must appear prior to row position2, and so on.mxSetIr doesnotsorttheir array for you; you must specify an ir arraythat is already sorted.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetIr before you call mxSetIr.CExamplesSee mxsetnzmax.c in the mx subdirectory of the examples directory. Foran additional example, see explore.c in the mex subdirectory of theexamples directory.2-217


mxSetIr (C and <strong>Fortran</strong>)See AlsomxCreateSparse, mxGetIr, mxGetJc, mxSetJc, mxFree2-218


mxSetJc (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet jc array of sparse mxArray#include "matrix.h"void mxSetJc(mxArray *pm, mwIndex *jc);subroutine mxSetJc(pm, jc)mwPointer pm, jcArgumentspmjcPointer to a sparse mxArrayPointer to the jc arrayDescriptionUse mxSetJc to specify a new jc array for a sparse mxArray. Thejcarray is an integer array having n+1 elements, where n is the number ofcolumns in the sparse mxArray.If the jth column of the sparse mxArray has any nonzero elements:• jc[j] is the index in ir, pr, andpi (if it exists) of the first nonzeroelement in the jth column.• jc[j+1]-1 is the index of the last nonzero element in the jth column.The number of nonzero elements in the jth column of the sparsemxArray isjc[j+1] - jc[j];For the jth column of the sparse mxArray, jc[j] is the total number ofnonzero elements in all preceding columns. The last element of the jcarray, jc[number of columns], isequaltonnz, which is the number ofnonzero elements in the entire sparse mxArray.Forexample,considera7-by-3sparsemxArray named Sparrowcontaining six nonzero elements, created by typingSparrow = zeros(7,3);2-219


mxSetJc (C and <strong>Fortran</strong>)Sparrow(2,1) = 1;Sparrow(5,1) = 1;Sparrow(3,2) = 1;Sparrow(2,3) = 2;Sparrow(5,3) = 1;Sparrow(6,3) = 1;Sparrow = sparse(Sparrow);The contents of the ir, jc, andpr arrays are listed in this table.Subscript ir pr jc Comment(2,1) 1 1 0 Column 1 contains twononzero elements, with rowsdesignated by ir[0] and ir[1](5,1) 4 1 2 Column 2 contains one nonzeroelement, with row designatedby ir[2](3,2) 2 1 3 Column 3 contains threenonzero elements, with rowsdesignated by ir[3],ir[4],and ir[5](2,3) 1 2 6 There are six nonzero elementsin all.(5,3) 4 1(6,3) 5 1As an example of a much sparser mxArray, consider a 1,000-by-8 sparsemxArray named Spacious containing only three nonzero elements. Their, pr, andjc arrays contain the values listed in this table.2-220


mxSetJc (C and <strong>Fortran</strong>)Subscript ir pr jc Comment(73,2) 72 1 0 Column 1 contains no nonzeroelements.(50,3) 49 1 0 Column 2 contains one nonzeroelement, with row designatedby ir[0].(64,5) 63 1 1 Column 3 contains one nonzeroelement, with row designatedby ir[1].2 Column 4 contains no nonzeroelements.2 Column 5 contains one nonzeroelement, with row designatedby ir[2].3 Column 6 contains no nonzeroelements.3 Column 7 contains no nonzeroelements.3 Column 8 contains no nonzeroelements.3 There are three nonzeroelements in all.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetJc before you call mxSetJc.CExamplesSee AlsoSee mxsetdimensions.c in the mx subdirectory of the examplesdirectory. For an additional example, see explore.c in the mexsubdirectory of the examples directory.mxCreateSparse, mxGetIr, mxGetJc, mxSetIr, mxFree2-221


mxSetM (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet number of rows in mxArray#include "matrix.h"void mxSetM(mxArray *pm, mwSize m);subroutine mxSetM(pm, m)mwPointer pmmwSize mArgumentspmmPointer to an mxArrayThe desired number of rowsDescriptionCExamplesSee AlsoCall mxSetM to set the number of rows in the specified mxArray. Theterm “rows” means the first dimension of an mxArray, regardless of thenumber of dimensions. Call mxSetN to set the number of columns.You typically use mxSetM to change the shape of an existing mxArray.Note that mxSetM does not allocate or deallocate any space for the pr,pi, ir, orjc arrays. Consequently, if your calls to mxSetM and mxSetNincrease the number of elements in the mxArray, you must enlarge thepr, pi, ir, and/orjc arrays. Call mxRealloc to enlarge them.If your calls to mxSetM and mxSetN end up reducing the number ofelements in the mxArray, you may want to reduce the sizes of the pr,pi, ir, and/orjc arraysinordertouseheapspacemoreefficiently.However, reducing the size is not mandatory.See mxsetdimensions.c in the mx subdirectory of the examplesdirectory. For an additional example, see sincall.c in the refbooksubdirectory of the examples directory.mxGetM, mxGetN, mxSetN2-222


mxSetN (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet number of columns in mxArray#include "matrix.h"void mxSetN(mxArray *pm, mwSize n);subroutine mxSetN(pm, n)mwPointer pmmwSize nArgumentspmnPointer to an mxArrayThe desired number of columnsDescriptionCExamplesSee AlsoCall mxSetN to set the number of columns in the specified mxArray.The term “columns” always means the second dimension of a matrix.Calling mxSetN forces an mxArray to have two dimensions. For example,if pm points to an mxArray having three dimensions, calling mxSetNreduces the mxArray to two dimensions.You typically use mxSetN to change the shape of an existing mxArray.Note that mxSetN does not allocate or deallocate any space for the pr,pi, ir, orjc arrays. Consequently, if your calls to mxSetN and mxSetMincrease the number of elements in the mxArray, you must enlarge thepr, pi, ir, and/orjc arrays.If your calls to mxSetM and mxSetN end up reducing the number ofelements in the mxArray, you may want to reduce the sizes of the pr,pi, ir, and/orjc arraysinordertouseheapspacemoreefficiently.However, reducing the size is not mandatory.See mxsetdimensions.c in the mx subdirectory of the examplesdirectory. For an additional example, see sincall.c in the refbooksubdirectory of the examples directory.mxGetM, mxGetN, mxSetM2-223


mxSetNzmax (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxArgumentsDescriptionSet storage space for nonzero elements#include "matrix.h"void mxSetNzmax(mxArray *pm, mwSize nzmax);subroutine mxSetNzmax(pm, nzmax)mwPointer pmmwSize nzmaxpmPointer to a sparse mxArray.nzmaxThe number of elements that mxCreateSparse should allocate tohold the arrays pointed to by ir, pr, andpi (if it exists). Set nzmaxgreaterthanorequaltothenumberofnonzeroelementsinthemxArray, but set it to be less than or equal to the number of rowstimes the number of columns. If you specify an nzmax value of 0,mxSetNzmax sets the value of nzmax to 1.Use mxSetNzmax to assign a new value to the nzmax field of the specifiedsparse mxArray. Thenzmax field holds the maximum possible numberof nonzero elements in the sparse mxArray.The number of elements in the ir, pr, andpi (if it exists) arrays mustbe equal to nzmax. Therefore, after calling mxSetNzmax, youmustchangethesizeoftheir, pr, andpi arrays. To change the size of oneof these arrays:1 Call mxRealloc with a pointer to the array, setting the size to thenew value of nzmax.2 Call the appropriate mxSet routine (mxSetIr, mxSetPr, ormxSetPi)to establish the new memory area as the current one.Two ways of determining how big you should make nzmax are2-224


mxSetNzmax (C and <strong>Fortran</strong>)• Set nzmax equal to or slightly greater than the number of nonzeroelements in a sparse mxArray. This approach conserves preciousheap space.• Make nzmax equal to the total number of elements in anmxArray. This approach eliminates (or, at least reduces) expensivereallocations.CExamplesSee AlsoSee mxsetnzmax.c in the mx subdirectory of the examples directory.mxGetNzmax, mxRealloc2-225


mxSetPi (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet new imaginary data for mxArray#include "matrix.h"void mxSetPi(mxArray *pm, double *pi);subroutine mxSetPi(pm, pi)mwPointer pm, piArgumentspmpiPointer to a full (nonsparse) mxArrayPointer to the first element of an array. Each element in the arraycontains the imaginary component of a value. The array mustbe in dynamic memory; call mxCalloc to allocate this dynamicmemory. If pi points to static memory, memory leaks and othermemory errors may result.DescriptionCExamplesSee AlsoUse mxSetPi to set the imaginary data of the specified mxArray.Most mxCreate functions optionally allocate heap space to holdimaginary data. If you tell an mxCreate function to allocate heapspace—for example, by setting the ComplexFlag to mxCOMPLEX in C (1 in<strong>Fortran</strong>) or by setting pi to a non-NULL valueinC(anonzerovaluein<strong>Fortran</strong>)—you do not ordinarily use mxSetPi to initialize the createdmxArray’s imaginary elements. Rather, you call mxSetPi to replace theinitial imaginary values with new ones.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetPi before you call mxSetPi.See mxisfinite.c and mxsetnzmax.c in the mx subdirectory of theexamples directory.mxGetPi, mxGetPr, mxSetImagData, mxSetPr, mxFree2-226


mxSetPr (C and <strong>Fortran</strong>)PurposeCSyntax<strong>Fortran</strong>SyntaxSet new real data for mxArray#include "matrix.h"void mxSetPr(mxArray *pm, double *pr);subroutine mxSetPr(pm, pr)mwPointer pm, prArgumentspmprPointer to a full (nonsparse) mxArrayPointer to the first element of an array. Each element in the arraycontains the real component of a value. The array must be indynamic memory; call mxCalloc to allocate this dynamic memory.If pr points to static memory, memory leaks and other memoryerrors can result.DescriptionCExamplesSee AlsoUse mxSetPr to set the real data of the specified mxArray.All mxCreate calls allocate heap space to hold real data. Therefore,you do not ordinarily use mxSetPr to initialize the real elements of afreshly created mxArray. Rather, you call mxSetPr to replace the initialreal values with new ones.This function does not free any memory allocated for existing datathat it displaces. To free existing memory, call mxFree on the pointerreturned by mxGetPr before you call mxSetPr.See mxsetnzmax.c in the mx subdirectory of the examples directory.mxGetPi, mxGetPr, mxSetData, mxSetPi, mxFree2-227


IndexIndexAallocating memory 2-67Bbufferdefining output 2-10Ddeletingnamed matrix from MAT-file 2-16directorygetting 2-17EengClose 2-2engEvalString 2-3engGetVariable 2-5engGetVisible 2-6enginesgetting and putting matrices into 2-5 2-12starting 2-2engOpen 2-7engPutVariable 2-12engSetVisible 2-14errorscontrol response to 2-55issuing messages 2-34 2-36Ggettingdirectory 2-17MMAT-filesdeleting named matrix from 2-16getting and putting matrices into 2-23 2-28to 2-29getting next matrix from 2-20getting pointer to 2-19opening and closing 2-15 2-26matClose 2-26matDeleteMatrix 2-16matGetDir 2-17matGetFp 2-19matGetNextVariable 2-20matGetNextVariableInfo 2-21matGetVariable 2-23matGetVariableInfo 2-24MATLAB enginesstarting 2-2matOpen 2-15matPutVariable 2-28matPutVariableAsGlobal 2-29matricesputting into engine’s workspace 2-12putting into MAT-files 2-29MEX-filesentry point to 2-38mexCallMATLAB 2-32mexErrMsgIdAndTxt 2-34 2-58mexErrMsgTxt 2-36 2-59mexEvalString 2-37mexFunction 2-38mexGetVariable 2-42mexPrintf 2-50mexSetTrapFlag 2-55mwIndex 2-60mwpointer 2-61mwSize 2-62mxaddfield 2-63mxarraytostring 2-64mxassert 2-65mxasserts 2-66mxcalcsinglesubscript 2-67mxcalloc 2-70Index-1


Indexmxchar 2-72mxclassid 2-73mxclassidfromclassname 2-76mxcomplexity 2-77mxcopycharactertoptr 2-78mxcopycomplex16toptr 2-79mxcopycomplex8toptr 2-80mxcopyinteger1toptr 2-81mxcopyinteger2toptr 2-82mxcopyinteger4toptr 2-83mxcopyptrtocharacter 2-84mxcopyptrtocomplex16 2-85mxcopyptrtocomplex8 2-86mxcopyptrtointeger1 2-87mxcopyptrtointeger2 2-88mxcopyptrtointeger4 2-89mxcopyptrtoptrarray 2-90mxCopyPtrToReal4 2-91mxcopyptrtoreal8 2-92mxcopyreal4toptr 2-93mxcopyreal8toptr 2-94mxcreatecellarray 2-95mxcreatecellmatrix 2-97mxcreatechararray 2-98mxcreatecharmatrixfromstrings 2-100mxcreatedoublematrix 2-102mxcreatedoublescalar 2-104mxcreatelogicalarray 2-105mxcreatelogicalmatrix 2-107mxcreatelogicalscalar 2-108mxcreatenumericarray 2-109mxcreatenumericmatrix 2-113mxcreatesparse 2-116mxcreatesparselogicalmatrix 2-118mxcreatestring 2-119mxcreatestructarray 2-120mxcreatestructmatrix 2-122mxdestroyarray 2-124mxduplicatearray 2-125mxfree 2-126mxgetcell 2-128mxgetchars 2-130mxgetclassid 2-131mxgetclassname 2-134mxgetdata 2-135mxgetdimensions 2-136mxgetelementsize 2-138mxgeteps 2-139mxgetfield 2-140mxgetfieldbynumber 2-143mxgetfieldnamebynumber 2-146mxgetfieldnumber 2-148mxgetimagdata 2-150mxgetinf 2-151mxgetir 2-152mxgetjc 2-154mxgetlogicals 2-155mxgetm 2-156mxgetn 2-157mxgetnan 2-159mxgetnumberofdimensions 2-160mxgetnumberofelements 2-161mxgetnumberoffields 2-162mxgetnzmax 2-163mxgetpi 2-164mxgetpr 2-165mxgetscalar 2-166mxgetstring 2-168mxiscell 2-170mxischar 2-171mxisclass 2-172mxiscomplex 2-175mxisdouble 2-176mxisempty 2-178mxisfinite 2-179mxisfromglobalws 2-180mxisinf 2-181mxisint16 2-182mxisint32 2-183mxisint8 2-185Index-2


Indexmxislogical 2-186mxislogicalscalar 2-187mxislogicalscalartrue 2-188mxisnan 2-189mxisnumeric 2-190mxissingle 2-192mxissparse 2-193mxisstruct 2-194mxisuint16 2-195mxisuint32 2-196mxisuint64 2-197mxisuint8 2-198mxmalloc 2-199mxrealloc 2-201mxremovefield 2-203mxsetcell 2-204mxsetclassname 2-206mxsetdata 2-207mxsetdimensions 2-208mxsetfield 2-210mxsetfieldbynumber 2-212mxsetimagdata 2-215mxsetir 2-216mxsetjc 2-219mxsetm 2-222mxsetn 2-223mxsetnzmax 2-224mxsetpi 2-226mxsetpr 2-227Oopening MAT-files 2-15 2-26Ppointerto MAT-file 2-19printing 2-47 2-49SstartingMATLAB engines 2-2stringexecuting statement 2-3Index-3

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!