External Interfaces Reference
Version 7
M ATLAB
®The Language of Technical Computing
How to Contact The MathWorks:
www.mathworks.com Web comp.soft-sys.matlab Newsgroup [email protected] Technical support
[email protected] Product enhancement suggestions [email protected] Bug reports
[email protected] Documentation error reports
[email protected] Order status, license renewals, passcodes [email protected] Sales, pricing, and general information
508-647-7000 Phone
508-647-7001 Fax
The MathWorks, Inc. Mail 3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
MATLAB External Interfaces Reference
© COPYRIGHT 1984 - 2005 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or repro- duced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this 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 Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, and xPC TargetBox are registered trademarks of The MathWorks, Inc.
Other product or brand names are trademarks or registered trademarks of their respective holders.
Revision History
December 1996 First printing
May 1997 Online only Revised for 5.1 (Release 9) January 1998 Online only Revised for 5.2 (Release 10) January 1999 Online only Revised for 5.3 (Release 11) September 2000 Online only Revised for 6.0 (Release 12) June 2001 Online only Revised for 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)
i
Contents 1
Generic DLL Interface Functions
2
C MAT-File Functions
3
C MX-Functions
4
C MEX-Functions
5
C Engine Functions
6
Fortran MAT-File Functions
7
Fortran MX-Functions
8
Fortran MEX-Functions
9
Fortran Engine Functions
10
Java Interface Functions
11
COM Functions
COM Client Functions . . . 11-2 COM Server Functions . . . 11-50
12
DDE Functions
13
Web Services Functions
14
Serial Port I/O Functions
1
Generic DLL Interface Functions
calllib Call function in external library
libfunctions Return information on functions in external library libfunctionsview Create window displaying information on functions in
external library
libisloaded Determine if external library is loaded
libpointer Create pointer object for use with external libraries libstruct Construct structure as defined in external library loadlibrary Load external library into MATLAB®
unloadlibrary Unload external library from memory
calllib
1calllib
Purpose
Call function in external librarySyntax
[x1, ..., xN] = calllib('libname', 'funcname', arg1, ..., argN)Description
[x1, ..., xN] = calllib('libname', 'funcname', arg1, ..., argN) calls the function funcname in library libname, passing input arguments arg1 through argN. calllib returns output values obtained from function funcname in x1 through XN.If you used an alias when initially loading the library, then you must use that alias for the libname argument.
Examples
This example calls functions from the libmx library to test the value stored in y:hfile = [matlabroot '\extern\include\matrix.h'];
loadlibrary('libmx', hfile) y = rand(4, 7, 2);
calllib('libmx', 'mxGetNumberOfElements', y) ans =
56
calllib('libmx', 'mxGetClassID', y) ans =
mxDOUBLE_CLASS unloadlibrary libmx
See Also
loadlibrary, libfunctions, libfunctionsview, libpointer, libstruct, libisloaded, unloadlibrarylibfunctions
1-3
1libfunctions
Purpose
Return information on functions in external librarySyntax
m = libfunctions('libname')m = libfunctions('libname', '-full') libfunctions libname -full
Description
m = libfunctions('libname')returns the names of all functions defined in the external shared library, libname, that has been loaded into MATLAB with the loadlibrary function. The return value, m, is a cell array of strings.If you used an alias when initially loading the library, then you must use that alias for the libname argument.
m = libfunctions('libname', '-full')returns a full description of the functions in the library, including function signatures. This includes duplicate function names with different signatures. The return value, m, is a cell array of strings.
libfunctions libname -fullis the command format for this function.
Examples
List the functions in the MATLAB libmx library:hfile = [matlabroot '\extern\include\matrix.h'];
loadlibrary('libmx', hfile) libfunctions libmx
Methods for class lib.libmx:
mxAddField mxGetFieldNumber mxIsLogicalScalarTrue mxArrayToString mxGetImagData mxIsNaN
mxCalcSingleSubscript mxGetInf mxIsNumeric mxCalloc mxGetIr mxIsObject mxClearScalarDoubleFlag mxGetJc mxIsOpaque
mxCreateCellArray mxGetLogicals mxIsScalarDoubleFlagSet . . .
. . .
libfunctions
To list the functions along with their signatures, use the -full switch with libfunctions:
libfunctions libmx -full Methods for class lib.libmx:
[mxClassID, MATLAB array] mxGetClassID(MATLAB array) [lib.pointer, MATLAB array] mxGetData(MATLAB array) [MATLAB array, voidPtr] mxSetData(MATLAB array, voidPtr) [uint8, MATLAB array] mxIsNumeric(MATLAB array)
[uint8, MATLAB array] mxIsCell(MATLAB array) [lib.pointer, MATLAB array] mxGetPr(MATLAB array)
[MATLAB array, doublePtr] mxSetPr(MATLAB array, doublePtr) .
.
unloadlibrary libmx
See Also
loadlibrary, libfunctionsview, libpointer, libstruct, calllib, libisloaded, unloadlibrarylibfunctionsview
1-5
1libfunctionsview
Purpose
Create window displaying information on functions in external librarySyntax
libfunctionsview('libname')libfunctionsview libname
Description
libfunctionsview libnamedisplays the names of the functions in the external shared library, libname, that has been loaded into MATLAB with the loadlibrary function.If you used an alias when initially loading the library, then you must use that alias for the libname argument.
MATLAB creates a new window in response to the libfunctionsview command. This window displays all of the functions defined in the specified library. For each of these functions, the following information is supplied:
•Data type returned by the function
•Name of the function
•Arguments passed to the function
An additional column entitled “Inherited From” is displayed at the far right of the window. The information in this column is not useful for external libraries.
libfunctionsview libnameis the command format for this function.
libfunctionsview
Examples
The following command opens the window shown below for the libmx library:libfunctionsview libmx
See Also
loadlibrary, libfunctions, libpointer, libstruct, calllib, libisloaded, unloadlibrarylibisloaded
1-7
1libisloaded
Purpose
Determine if external library is loadedSyntax
libisloaded('libname')libisloaded libname
Description
libisloaded('libname')returns logical 1 (true) if the shared library libname is loaded and logical 0 (false) otherwise.libisloaded libnameis the command format for this function.
If you used an alias when initially loading the library, then you must use that alias for the libname argument.
Examples
Example 1Load the shrlibsample library and check to see if the load was successful before calling one of its functions:
addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample.dll shrlibsample.h if libisloaded('shrlibsample')
x = calllib('shrlibsample', 'addDoubleRef', 1.78, 5.42, 13.3) end
Since the library is successfully loaded, the call to addDoubleRef works as expected and returns
x =
20.5000
unloadlibrary shrlibsample
Example 2
Load the same library, this time giving it an alias. If you use libisloaded with the library name, shrlibsample, it now returns false. Since you loaded the library using an alias, all further references to the library must also use that alias:
addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample.dll shrlibsample.h alias lib
libisloaded
libisloaded shrlibsample ans =
0
libisloaded lib ans =
1
unloadlibrary lib
See Also
loadlibrary, libfunctions, libfunctionsview, libpointer, libstruct, calllib, unloadlibrarylibpointer
1-9
1libpointer
Purpose
Create pointer object for use with external librariesSyntax
p = libpointerp = libpointer('type')
p = libpointer('type', value)
Description
p = libpointerreturns an empty (void) pointer.p = libpointer('type')returns an empty pointer that contains a reference to the specified data type. This type can be any MATLAB numeric type, or a structure or enumerated type defined in an external library that has been loaded into MATLAB with the loadlibrary function. For valid types, see the table under “Primitive Types” in the MATLAB documentation.
p = libpointer('type', value)returns a pointer to the specified data type and initialized to the value supplied.
Examples
This example passes an int16 pointer to a function that multiplies each value in a matrix by its index. The function multiplyShort is defined in theMATLAB sample shared library, shrlibsample. Here is the C function:
void multiplyShort(short *x, int size) {
int i;
for (i = 0; i < size; i++) *x++ *= i;
}
Load the shrlibsample library. Create the matrix, v, and also a pointer to it, pv:
addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample shrlibsample.h
v = [4 6 8; 7 5 3];
pv = libpointer('int16Ptr', v);
libpointer
get(pv, 'Value') ans =
4 6 8 7 5 3
Now call the C function in the library, passing the pointer to v. If you were to pass a copy of v, the results would be lost once the function terminates. Passing a pointer to v enables you to get back the results:
calllib('shrlibsample', 'multiplyShort', pv, 6);
get(pv, 'Value') ans =
0 12 32 7 15 15
unloadlibrary shrlibsample
Note In most cases, you can pass by value and MATLAB will automatically convert the argument to a pointer for you. See “Creating References”, in the MATLAB documentation for more information.
See Also
loadlibrary, libfunctions, libfunctionsview, libstruct, calllib, libisloaded, unloadlibrarylibstruct
1-11
1libstruct
Purpose
Construct structure as defined in external librarySyntax
s = libstruct('structtype')s = libstruct('structtype', mlstruct)
Description
s = libstruct('type')returns a libstruct object s that is a MATLAB object designed to resemble a C structure of type structtype. The structure type, structtype, is defined in an external library that must be loaded into MATLAB using the loadlibrary function. All fields of s are set to zero.s = libstruct('structtype', mlstruct)returns a libstruct object s with its fields initialized from MATLAB structure, mlstruct.
The libstruct function essentially creates a C-like structure that you can pass to functions in an external library. You can handle this structure in MATLAB as you would a true MATLAB structure.
Examples
This example performs a simple addition of the fields of a structure. The function addStructFields is defined in the MATLAB sample shared library, shrlibsample.Here is the C function:
double addStructFields(struct c_struct st) {
double t = st.p1 + st.p2 + st.p3;
return t;
}
Start by loading the shrlibsample library and creating MATLAB structure, sm:
addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample.dll shrlibsample.h sm.p1 = 476; sm.p2 = -299; sm.p3 = 1000;
libstruct
Construct a libstruct object sc that uses the c_struct template:
sc = libstruct('c_struct', sm);
get(sc) p1: 476 p2: -299 p3: 1000
Now call the function, passing the libstruct object, sc: calllib('shrlibsample', 'addStructFields', sc) ans =
1177
unloadlibrary shrlibsample
Note In most cases, you can pass a MATLAB structure and MATLAB will automatically convert the argument to a C structure. See “Structures”, in the MATLAB documentation for more information.
See Also
loadlibrary, libfunctions, libfunctionsview, libpointer, calllib, libisloaded, unloadlibraryloadlibrary
1-13
1loadlibrary
Purpose
Load external library into MATLABSyntax
loadlibrary('shrlib', 'hfile')loadlibrary('shrlib', @protofile) loadlibrary('shrlib', ..., 'options') loadlibrary shrlib hfile options
Description
loadlibrary('shrlib', 'hfile')loads the functions defined in header file hfile and found in shared library shrlib into MATLAB. On Windows systems, shrlib refers to the name of a dynamic link library (.dll) file. On UNIX systems, it refers to the name of a shared object (.so) file.loadlibrary('shrlib', @protofile)uses the prototype M-file protofile in place of a header file in loading the library shrlib. The string @protofile specifies a function handle to the prototype M-file. (See the description of
“Prototype M-Files” below).
If you do not include a file extension with the shrlib argument, loadlibrary uses .dll or .so, depending on the platform you are using. If you do not include a file extension with the second argument, and this argument is not a function handle, loadlibrary uses .h for the extension.
loadlibrary
loadlibrary('shrlib', ..., 'options')loads the library shrlib with one or more of the following options.
Only the alias option is available when loading using a prototype M-file.
If you have more than one library file of the same name, load the first using the library filename, and load the additional libraries using the alias option.
loadlibrary shrlib hfile optionsis the command format for this function.
Option Description
addheader hfileN Loads the functions defined in the additional header file, hfileN. Specify the string hfileN as a filename without a file extension. MATLAB does not verify the existence of the header files and ignores any that are not needed.
You can specify as many additional header files as you need using the syntax
loadlibrary shrlib hfile ...
addheader hfile1 ...
addheader hfile2 ... % and so on alias name Associates the specified alias name with the library.
All subsequent calls to MATLAB functions that reference this library must use this alias until the library is unloaded.
includepath path Specifies an additional path in which to look for included header files.
mfilename mfile Generates a prototype M-file mfile in the current directory. You can use this file in place of a header file when loading the library. (See the description of
“Prototype M-Files” below).
loadlibrary
1-15
Remarks
Prototype M-FilesWhen you use the mfilename option with loadlibrary, MATLAB generates an M-file called a prototype file. This file can then be used on subsequent calls to loadlibrary in place of a header file.
Like a header file, the prototype file supplies MATLAB with function prototype information for the library. You can make changes to the prototypes by editing this file and reloading the library.
Here are some reasons for using a prototype file, along with the changes you would need to make to the file:
•You want to make temporary changes to signatures of the library functions.
Edit the prototype file, changing the fcns.LHS or fcns.RHS field for that function. This changes the types of arguments on the left hand side or right hand side, respectively.
•You want to rename some of the library functions.
Edit the prototype file, defining the fcns.alias field for that function.
•You expect to use only a small percentage of the functions in the library you are loading.
Edit the prototype file, commenting out the unused functions. This reduces the amount of memory required for the library.
•You need to specify a number of include files when loading a particular library.
Specify the full list of include files (plus the mfilename option) in the first call to loadlibrary. This puts all the information from the include files into the prototype file. After that, specify just the prototype file.
Examples
Example 1Use loadlibrary to load the MATLAB sample shared library, shrlibsample: addpath([matlabroot '\extern\examples\shrlib'])
loadlibrary shrlibsample shrlibsample.h
loadlibrary
Example 2
Load sample library shrlibsample, giving it an alias name of lib. Once you have set an alias, you need to use this name in all further interactions with the library for this session:
addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample shrlibsample.h alias lib libfunctionsview lib
str = 'This was a Mixed Case string';
calllib('lib', 'stringToUpper', str) ans =
THIS WAS A MIXED CASE STRING unloadlibrary lib
Example 3
Load the library, specifying an additional path in which to search for included header files:
addpath([matlabroot '\extern\examples\shrlib'])
loadlibrary('shrlibsample','shrlibsample.h','includepath', ...
fullfile(matlabroot , 'extern', 'include'));
Example 4
Load the libmx library and generate a prototype M-file containing the prototypes defined in header file matrix.h:
hfile = [matlabroot '\extern\include\matrix.h'];
loadlibrary('libmx.dll', hfile, 'mfilename', 'mxproto') dir mxproto.m
mxproto.m
Edit the generated file mxproto.m and locate the function
'mxGetNumberOfDimensions'. Give it an alias of 'mxGetDims' by adding this text to the line before fcnNum is incremented:
fcns.alias{fcnNum}='mxGetDims';
loadlibrary
1-17 Here is the new function prototype. The change is shown in bold:
fcns.name{fcnNum}='mxGetNumberOfDimensions';
fcns.calltype{fcnNum}='cdecl';
fcns.LHS{fcnNum}='int32';
fcns.RHS{fcnNum}={'MATLAB array'};
fcns.alias{fcnNum}='mxGetDims'; % Alias defined fcnNum=fcnNum+1; % Increment fcnNum
Unload the library and then reload it using the prototype M-file.
unloadlibrary libmx
loadlibrary('libmx.dll', @mxproto)
Now call mxGetNumberOfDimensions using the alias function name:
y = rand(4, 7, 2);
calllib('libmx', 'mxGetDims', y) ans =
3
unloadlibrary libmx
See Also
libisloaded, unloadlibrary, libfunctions, libfunctionsview, libpointer, libstruct, calllibunloadlibrary
1unloadlibrary
Purpose
Unload external library from memorySyntax
unloadlibrary('libname')unloadlibrary libname
Description
unloadlibrary('libname')unloads the functions defined in shared library shrlib from memory. If you need to use these functions again, you must first load them back into memory using loadlibrary.unloadlibrary libnameis the command format for this function.
If you used an alias when initially loading the library, then you must use that alias for the libname argument.
Examples
Load the MATLAB sample shared library, shrlibsample. Call one of its functions, and then unload the library:addpath([matlabroot '\extern\examples\shrlib']) loadlibrary shrlibsample shrlibsample.h
s.p1 = 476; s.p2 = -299; s.p3 = 1000;
calllib('shrlibsample', 'addStructFields', s) ans =
1177
unloadlibrary shrlibsample
See Also
loadlibrary, libisloaded, libfunctions, libfunctionsview, libpointer, libstruct, calllib2
C MAT-File Functions
matClose Close MAT-file
matDeleteArray (Obsolete) Use matDeleteVariable matDeleteMatrix (Obsolete) Use matDeleteVariable
matDeleteVariable Delete named mxArray from MAT-file matGetArray (Obsolete) Use matGetVariable
matGetArrayHeader (Obsolete) Use matGetVariableInfo
matGetDir Get directory of mxArrays in MAT-file
matGetFp Get file pointer to MAT-file
matGetFull (Obsolete) Use matGetVariable followed by appropriate mxGet routines matGetMatrix (Obsolete) Use matGetVariable
matGetNextArray (Obsolete) Use matGetNextVariable
matGetNextArrayHeader (Obsolete) Use matGetNextArrayHeaderFromMATfile matGetNextMatrix (Obsolete) Use matGetNextVariable
matGetNextVariable Read next mxArray from MAT-file matGetNextVariableInfo Load array header information only matGetString (Obsolete) Use matGetVariable and mxGetString matGetVariable Read mxArray from MAT-file
matGetVariableInfo Load header array information only
matOpen Open MAT-file
matPutArray (Obsolete) Use matPutVariable
matPutArrayAsGlobal (Obsolete) Use matPutVariableAsGlobal
matPutFull (Obsolete) Use mxCreateDoubleMatrix and matPutVariable matPutMatrix (Obsolete) Use matPutVariable
matPutString (Obsolete) Use mxCreateString and matPutVariable
matPutVariable Write mxArrays into MAT-files matPutVariableAsGlobal Put mxArrays into MAT-files
matClose
2-3
2matClose
Purpose
Close MAT-fileC Syntax
#include "mat.h"int matClose(MATFile *mfp);
Arguments
mfpPointer to MAT-file information.
Description
matClose closes the MAT-file associated with mfp. It returns EOF for a write error, and zero if successful.Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matDeleteArray (Obsolete)
2matDeleteArray (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
matDeleteVariable(mfp, name) instead of
matDeleteArray(mfp, name)
See Also
matDeleteVariablematDeleteMatrix (Obsolete)
2-5
2matDeleteMatrix (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
matDeleteVariable(mfp, name) instead of
matDeleteMatrix(mfp, name)
See Also
matDeleteVariablematDeleteVariable
2matDeleteVariable
Purpose
Delete named mxArray from MAT-fileC Syntax
#include "mat.h"int matDeleteVariable(MATFile *mfp, const char *name);
Arguments
mfpPointer to MAT-file information.
name
Name of mxArray to delete.
Description
matDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp. matDeleteVariable returns 0 if successful, and nonzero otherwise.Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matGetArray (Obsolete)
2-7
2matGetArray (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
mp = matGetVariable(mfp, name);
instead of
mp = matGetArray(mfp, name);
See Also
matGetVariablematGetArrayHeader (Obsolete)
2matGetArrayHeader (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
mp = matGetVariableInfo(mfp, name);
instead of
mp = matGetArrayHeader(mfp, name);
See Also
matGetVariableInfomatGetDir
2-9
2matGetDir
Purpose
Get directory of mxArrays in MAT-fileC Syntax
#include "mat.h"char **matGetDir(MATFile *mfp, int *num);
Arguments
mfpPointer to MAT-file information.
num
Address of the variable to contain the number of mxArrays in the MAT-file.
Description
This routine allows you to get a list of the names of the mxArrays contained within a MAT-file.matGetDir returns a pointer to an internal array containing pointers to the NULL-terminated names of the mxArrays in the MAT-file pointed to by mfp. The length of the internal array (number of mxArrays in the MAT-file) is placed into num. The internal array is allocated using a single mxCalloc and must be freed using mxFree when you are finished with it.
matGetDir returns NULL and sets num to a negative number if it fails. If num is zero, mfp contains no arrays.
MATLAB variable names can be up to length mxMAXNAM, where mxMAXNAM is defined in the file matrix.h.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matGetFp
2matGetFp
Purpose
Get file pointer to MAT-fileC Syntax
#include "mat.h"FILE *matGetFp(MATFile *mfp);
Arguments
mfpPointer to MAT-file information.
Description
matGetFp returns the C file handle to the MAT-file with handle mfp. This can be useful for using standard C library routines like ferror() and feof() to investigate error situations.Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matGetFull (Obsolete)
2-11
2matGetFull (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
matGetVariable followed by the appropriate mxGet routines instead of
matGetFull For example,
int matGetFull(MATFile *fp, char *name, int *m, int *n, double **pr, double **pi)
{
mxArray *parr;
/* Get the matrix. */
parr = matGetVariable(fp, name);
if (parr == NULL) return(1);
if (!mxIsDouble(parr)) { mxDestroyArray(parr);
return(1);
}
/* Set up return args. */
*m = mxGetM(parr);
*n = mxGetN(parr);
*pr = mxGetPr(parr);
*pi = mxGetPi(parr);
/* Zero out pr & pi in array struct so the mxArray can be destroyed. */
mxSetPr(parr, (void *)0);
mxSetPi(parr, (void *)0);
mxDestroyArray(parr);
return(0);
}
matGetFull (Obsolete)
See Also
matGetVariablematGetMatrix (Obsolete)
2-13
2matGetMatrix (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
mp = matGetVariable(mfp, name) instead of
mp = matGetMatrix(mfp, name);
See Also
matGetVariablematGetNextArray (Obsolete)
2matGetNextArray (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
mp = matGetNextVariable(mfp, name);
instead of
mp = matGetNextArray(mfp);
See Also
matGetNextVariablematGetNextArrayHeader (Obsolete)
2-15
2matGetNextArrayHeader (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
matGetNextVariableInfo instead of
matGetNextArrayHeader
See Also
matGetNextVariableInfomatGetNextMatrix (Obsolete)
2matGetNextMatrix (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
matGetNextVariable instead of
matGetNextMatrix
See Also
matGetNextVariablematGetNextVariable
2-17
2matGetNextVariable
Purpose
Read next mxArray from MAT-fileC Syntax
#include "mat.h"mxArray *matGetNextVariable(MATFile *mfp, const char *name);
Arguments
mfpPointer to MAT-file information.
name
Address of the variable to contain the mxArray name.
Description
matGetNextVariable allows you to step sequentially through a MAT-file and read all the mxArrays in a single pass. The function reads the next mxArray from the MAT-file pointed to by mfp and returns a pointer to a newly allocated mxArray structure. MATLAB returns the name of the mxArray in name.Use matGetNextVariable immediately after opening the MAT-file with matOpen and not in conjunction with other MAT-file routines. Otherwise, the concept of the next mxArray is undefined.
matGetNextVariable returns NULL when the end-of-file is reached or if there is an error condition. Use feof and ferror from the Standard C Library to determine status.
Be careful in your code to free the mxArray created by this routine when you are finished with it.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matGetNextVariableInfo
2matGetNextVariableInfo
Purpose
Load array header information onlyC Syntax
#include "mat.h"mxArray *matGetNextVariableInfo(MATFile *mfp, const char *name);
Arguments
mfpPointer to MAT-file information.
name
Address of the variable to contain the mxArray name.
Description
matGetNextVariableInfo loads only the array header information, including everything except pr, pi, ir, and jc, from the file’s current file offset. MATLAB returns the name of the mxArray in name.If pr, pi, ir, and jc are set to nonzero values when loaded with
matGetVariable, matGetNextVariableInfo sets them to -1 instead. These headers are for informational use only and should never be passed back to MATLAB or saved to MAT-files.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.See Also
matGetNextVariable, matGetVariableInfomatGetString (Obsolete)
2-19
2matGetString (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
#include "mat.h"
#include "matrix.h"
mxArray *matGetVariable(MATFile *mfp, const char *name);
int mxGetString(const mxArray *array_ptr, char *buf, int buflen) instead of
matGetString
See Also
matGetVariable, mxGetStringmatGetVariable
2matGetVariable
Purpose
Read mxArrays from MAT-filesC Syntax
#include "mat.h"mxArray *matGetVariable(MATFile *mfp, const char *name);
Arguments
mfpPointer to MAT-file information.
name
Name of mxArray to get from MAT-file.
Description
This routine allows you to copy an mxArray out of a MAT-file.matGetVariable reads the named mxArray from the MAT-file pointed to by mfp and returns a pointer to a newly allocated mxArray structure, or NULL if the attempt fails.
Be careful in your code to free the mxArray created by this routine when you are finished with it.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matGetVariableInfo
2-21
2matGetVariableInfo
Purpose
Load array header information onlyC Syntax
#include "mat.h"mxArray *matGetVariableInfo(MATFile *mfp, const char *name);
Arguments
mfpPointer to MAT-file information.
name
Name of mxArray.
Description
matGetVariableInfo loads only the array header information, including everything except pr, pi, ir, and jc. It recursively creates the cells and structures through their leaf elements, but does not include pr, pi, ir, and jc. If pr, pi, ir, and jc are set to nonNULL when loaded with matGetVariable, then matGetVariableInfo sets them to -1 instead. These headers are forinformational use only and should never be passed back to MATLAB or saved to MAT-files.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matOpen
2matOpen
Purpose
Open MAT-fileC Syntax
#include "mat.h"MATFile *matOpen(const char *filename, const char *mode);
Arguments
filenameName of file to open.
mode
File opening mode. Valid values for mode are:
Description
This routine allows you to open MAT-files for reading and writing.matOpen opens the named file and returns a file handle, or NULL if the open fails.
See “Writing Character Data” in the External Interfaces documentation for more information on how MATLAB uses character data encoding.
r Open file for reading only; determines the current version of the MAT-file by inspecting the files and preserves the current version.
u Open file for update, both reading and writing, but does not create the file if the file does not exist (equivalent to the r+
mode of fopen); determines the current version of the MAT-file by inspecting the files and preserves the current version.
w Open file for writing only; deletes previous contents, if any.
w4 Create a Level 4 MAT-file, compatible with MATLAB Versions 4 and earlier.
wL Open file for writing character data using the default character set for your system. The resulting MAT-file can be read with MATLAB version 6 or 6.5.
If you do not use the wL mode switch, MATLAB writes character data to the MAT-file using Unicode encoding by default.
wz Open file for writing compressed data.
matOpen
2-23
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examplesdirectory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.
matPutArray (Obsolete)
2matPutArray (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
matPutVariable(mfp, name, mp);
instead of
mxSetName(mp, name);
matPutArray(mfp, mp);
See Also
matPutVariablematPutArrayAsGlobal (Obsolete)
2-25
2matPutArrayAsGlobal (Obsolete)
V5 Compatible
This API function is obsolete and should not be used in a program that interfaces with MATLAB 6.5 or later. This function may not be available in a future version of MATLAB. If you need to use this function in existing code, use the -V5 option of the mex script.Use
matPutVariableAsGlobal instead of
matPutArrayAsGlobal
See Also
matPutVariableAsGlobalmatPutFull (Obsolete)
2matPutFull (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
mxCreateDoubleMatrix and matPutVariable instead of
matPutFull For example,
int matPutFull(MATFile*ph, char *name, int m, int n, double *pr, double *pi)
{
int retval;
mxArray *parr;
/* Get empty array struct to place inputs into. */
parr = mxCreateDoubleMatrix(0, 0, 0);
if (parr == NULL) return(1);
/* Place inputs into array struct. */
mxSetM(parr, m);
mxSetN(parr, n);
mxSetPr(parr, pr);
mxSetPi(parr, pi);
/* Use put to place array on file. */
retval = matPutVariable(ph, name, parr);
/* Zero out pr & pi in array struct so the mxArray can be destroyed. */
mxSetPr(parr, (void *)0);
mxSetPi(parr, (void *)0);
mxDestroyArray(parr);
return(retval);
}
matPutFull (Obsolete)
2-27
See Also
mxCreateDoubleMatrix, matPutVariablematPutMatrix (Obsolete)
2matPutMatrix (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
matPutVariable instead of
matPutMatrix
See Also
matPutVariablematPutString (Obsolete)
2-29
2matPutString (Obsolete)
This API function is obsolete and should not be used in a program that interfaces with MATLAB 5 or later.
Use
#include "matrix.h"
#include "mat.h"
mp = mxCreateString(str);
matPutVariable(mfp, name, mp);
mxDestroyArray(mp);
instead of
matPutString(mfp, name, str);
See Also
matPutVariablematPutVariable
2matPutVariable
Purpose
Write mxArrays to MAT-filesC Syntax
#include "mat.h"int matPutVariable(MATFile *mfp, const char *name, const mxArray
*mp);
Arguments
mfpPointer to MAT-file information.
name
Name of mxArray to put into MAT-file.
mp
mxArray pointer.
Description
This routine allows you to put an mxArray into a MAT-file.matPutVariable writes mxArray mp to the MAT-file mfp. If the mxArray does not exist in the MAT-file, it is appended to the end. If an mxArray with the same name already exists in the file, the existing mxArray is replaced with the new mxArray by rewriting the file. The size of the new mxArray can be different than the existing mxArray.
matPutVariable returns 0 if successful and nonzero if an error occurs. Use feof and ferror from the Standard C Library along with matGetFp to determine status.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matPutVariableAsGlobal
2-31
2matPutVariableAsGlobal
Purpose
Put mxArrays into MAT-files as originating from global workspaceC Syntax
#include "mat.h"int matPutVariableAsGlobal(MATFile *mfp, const char *name, const mxArray *mp);
Arguments
mfpPointer to MAT-file information.
name
Name of mxArray to put into MAT-file.
mp
mxArray pointer.
Description
This routine allows you to put an mxArray into a MAT-file.matPutVariableAsGlobal is similar to matPutVariable, except the array, when loaded by MATLAB, is placed into the global workspace and a reference to it is set in the local workspace. If you write to a MATLAB 4 format file, matPutVariableAsGlobal will not load it as global, and will act the same as matPutVariable.
matPutVariableAsGlobal writes mxArray mp to the MAT-file mfp. If the mxArray does not exist in the MAT-file, it is appended to the end. If an mxArray with the same name already exists in the file, the existing mxArray is replaced with the new mxArray by rewriting the file. The size of the new mxArray can be different than the existing mxArray.
matPutVariableAsGlobal returns 0 if successful and nonzero if an error occurs.
Use feof and ferror from the Standard C Library with matGetFp to determine status.
Examples
See matcreat.c and matdgns.c in the eng_mat subdirectory of the examples directory for sample programs that illustrate how to use the MATLAB MAT-file routines in a C program.matPutVariableAsGlobal
3
C MX-Functions
mxAddField Add field to structure array mxArrayToString Convert array to string
mxAssert Check assertion value
mxAssertS Check assertion value without printing assertion text mxCalcSingleSubscript Return offset from first element to desired element
mxCalloc Allocate dynamic memory
mxChar Data type for string mxArray
mxClassID Integer value that identifies class of mxArray mxClearLogical (Obsolete) Clear logical flag
mxComplexity Specifies if mxArray has imaginary components mxCreateCellArray Create unpopulated N-dimensional cell mxArray mxCreateCellMatrix Create unpopulated two-dimensional cell mxArray mxCreateCharArray Create unpopulated N-dimensional string mxArray mxCreateCharMatrixFromStrings Create populated two-dimensional string mxArray mxCreateDoubleMatrix Create unpopulated two-dimensional, double-precision,
floating-point mxArray
mxCreateDoubleScalar Create scalar, double-precision array initialized to specified value
mxCreateLogicalArray Create N-dimensional, logical mxArray initialized to false mxCreateLogicalMatrix Create two-dimensional, logical mxArray initialized to false mxCreateLogicalScalar Create scalar, logical mxArray initialized to false
mxCreateFull (Obsolete) Use mxCreateDoubleMatrix
mxCreateNumericArray Create unpopulated N-dimensional numeric mxArray mxCreateNumericMatrix Create numeric matrix and initialize data elements to 0 mxCreateScalarDouble Create scalar, double-precision array initialized to specified
value
mxCreateSparse Create two-dimensional unpopulated sparse mxArray mxCreateSparseLogicalMatrix Create unpopulated, two-dimensional, sparse, logical
mxArray
mxCreateString Create 1-by-n string mxArray initialized to specified string mxCreateStructArray Create unpopulated N-dimensional structure mxArray mxCreateStructMatrix Create unpopulated two-dimensional structure mxArray mxDestroyArray Free dynamic memory allocated by an mxCreate routine mxDuplicateArray Make deep copy of array
mxFree Free dynamic memory allocated by mxCalloc mxFreeMatrix (Obsolete) Use mxDestroyArray
mxGetCell Get cell’s contents
mxGetChars Get pointer to character array data mxGetClassID Get class of mxArray
mxGetClassName Get class of mxArray as string
mxGetData Get pointer to data
mxGetDimensions Get pointer to dimensions array
mxGetElementSize Get number of bytes required to store each data element
mxGetEps Get value of eps
mxGetField Get field value, given field name and index in structure array mxGetFieldByNumber Get field value, given field number and index in structure
array
mxGetFieldNameByNumber Get field name, given field number in structure array mxGetFieldNumber Get field number, given field name in structure array mxGetImagData Get pointer to imaginary data of mxArray
mxGetInf Get value of infinity
mxGetIr Get ir array of sparse matrix mxGetJc Get jc array of sparse matrix
3-3 mxGetLogicals Get pointer to logical array data
mxGetM Get number of rows
mxGetN Get number of columns or number of elements mxGetName (Obsolete) Get name of specified mxArray
mxGetNaN Get the value of NaN
mxGetNumberOfDimensions Get number of dimensions mxGetNumberOfElements Get number of elements in array
mxGetNumberOfFields Get number of fields in structure mxArray mxGetNzmax Get number of elements in ir, pr, and pi arrays mxGetPi Get imaginary data elements of mxArray mxGetPr Get real data elements of mxArray
mxGetScalar Get real component of first data element in mxArray mxGetString Copy string mxArray to C-style string
mxIsCell Determine if input is cell mxArray mxIsChar Determine if input is string mxArray
mxIsClass Determine if mxArray is member of specified class mxIsComplex Determine if data is complex
mxIsDouble Determine if mxArray represents its data as double-precision, floating-point numbers
mxIsEmpty Determine if mxArray is empty mxIsFinite Determine if input is finite
mxIsFromGlobalWS Determine if mxArray was copied from the MATLAB global workspace
mxIsFull (Obsolete) Use mxIsSparse
mxIsInf Determine if input is infinite
mxIsInt8 Determine if mxArray represents data as signed 8-bit integers
mxIsInt16 Determine if mxArray represents data as signed 16-bit integers
mxIsInt32 Determine if mxArray represents data as signed 32-bit integers
mxIsInt64 Determine if mxArray represents data as signed 64-bit integers
mxIsLogical Determine if mxArray is Boolean
mxIsLogicalScalar Determine if input is scalar mxArray of class mxLogical mxIsLogicalScalarTrue Determine if scalar mxArray of class mxLogical is true
mxIsNaN Determine if input is NaN
mxIsNumeric Determine if mxArray is numeric
mxIsSingle Determine if mxArray represents data as single-precision, floating-point numbers
mxIsSparse Determine if input is sparse mxArray mxIsString (Obsolete) Use mxIsChar
mxIsStruct Determine if input is structure mxArray
mxIsUint8 Determine if mxArray represents data as unsigned 8-bit integers
mxIsUint16 Determine if mxArray represents data as unsigned 16-bit integers
mxIsUint32 Determine if mxArray represents data as unsigned 32-bit integers
mxIsUint64 Determine if mxArray represents data as unsigned 64-bit integers
mxMalloc Allocate dynamic memory using the MATLAB memory manager
mxRealloc Reallocate memory
mxRemoveField Remove field from structure array
mxSetCell Set value of one cell
3-5 mxSetClassName Convert MATLAB structure array to MATLAB object array
mxSetData Set pointer to data
mxSetDimensions Modify number/size of dimensions
mxSetField Set field value of structure array, given field name/index mxSetFieldByNumber Set field value in structure array, given field number/index mxSetImagData Set imaginary data pointer for mxArray
mxSetIr Set ir array of sparse mxArray mxSetJc Set jc array of sparse mxArray mxSetLogical (Obsolete) Set logical flag
mxSetM Set number of rows
mxSetN Set number of columns
mxSetName (Obsolete) Set name of mxArray
mxSetNzmax Set storage space for nonzero elements mxSetPi Set new imaginary data for mxArray
mxSetPr Set new real data for mxArray
mxAddField
3mxAddField
Purpose
Add field to structure arrayC Syntax
#include "matrix.h"extern int mxAddField(mxArray array_ptr, const char *field_name);
Arguments
array_ptrPointer to a structure mxArray. field_name
The name of the field you want to add.
Returns
Field number on success or -1 if inputs are invalid or an out of memory condition occurs.Description
Call mxAddField to add a field to a structure array. You must then create the values with the mxCreate* functions and use mxSetFieldByNumber to set the individual values for the field.See Also
mxRemoveField, mxSetFieldByNumbermxArrayToString
3-7
3mxArrayToString
Purpose
Convert array to stringC Syntax
#include "matrix.h"char *mxArrayToString(const mxArray *array_ptr);
Arguments
array_ptrPointer to a string mxArray; that is, a pointer to an mxArray having the mxCHAR_CLASS class.
Returns
A C-style string. Returns NULL on out of memory.Description
Call mxArrayToString to copy the character data of a string mxArray into a C-style string. The C-style string is always terminated with a NULL character.If the string array contains several rows, they are copied, one column at a time, into one long string array. This function is similar to mxGetString, except that:
•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 char pointer points to. Consequently, you should typically free the string (using mxFree) immediately after you have finished using it.
Examples
See mexatexit.c in the mex subdirectory of the examples directory.For additional examples, see mxcreatecharmatrixfromstr.c and mxislogical.c in the mx subdirectory of the examples directory.
See Also
mxCreateCharArray, mxCreateCharMatrixFromStrings, mxCreateString, mxGetStringmxAssert
3mxAssert
Purpose
Check assertion value for debugging purposesC Syntax
#include "matrix.h"void mxAssert(int expr, char *error_message);
Arguments
exprValue of assertion.
error_message
Description of why assertion failed.
Description
Similar to the ANSI C assert() macro, mxAssert checks the value of an assertion, and continues execution only if the assertion holds. If expr evaluates to logical 1 (true), mxAssert does nothing. If expr evaluates to logical 0 (false), mxAssert prints an error to the MATLAB command window consisting of the failed assertion’s expression, the filename and line number where the failed assertion occurred, and the error_message string. The error_message string allows you to specify a better description of why the assertion failed. Use an empty string if you 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 building optimized MEX-functions, so you should use this for debugging purposes only. Build the mex file using the syntax, mex -g filename, in order to use mxAssert.
Assertions are a way of maintaining internal consistency of logic. Use them to keep yourself from misusing your own code and to prevent logical errors from propagating before they are caught; do not use assertions to prevent users of your code from misusing it.
Assertions can be taken out of your code by the C preprocessor. You can use these checks during development and then remove them when the code works properly, letting you use them for troubleshooting during development without slowing down the final product.
mxAssertS
3-9
3mxAssertS
Purpose
Check assertion value without printing assertion textC Syntax
#include "matrix.h"void mxAssertS(int expr, char *error_message);
Arguments
exprValue of assertion.
error_message
Description of why assertion failed.
Description
Similar to mxAssert, except mxAssertS does not print the text of the failed assertion. mxAssertS checks the value of an assertion, and continues execution only if the assertion holds. If expr evaluates to logical 1 (true), mxAssertS does nothing. If expr evaluates to logical 0 (false), mxAssertS prints an error to the MATLAB command window consisting of the filename and line number where the assertion failed and the error_message string. The error_message string allows you to specify a better description of why the assertion failed. Use an empty string if you 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 building optimized MEX-functions, so you should use this for debugging purposes only. Build the mex file using the syntax, mex -g filename, in order to use mxAssert.
mxCalcSingleSubscript
3mxCalcSingleSubscript
Purpose
Return offset from first element to desired elementC Syntax
#include <matrix.h>int mxCalcSingleSubscript(const mxArray *array_ptr, int nsubs, int *subs);
Arguments
array_ptrPointer to an mxArray. nsubs
The number of elements in the subs array. Typically, you set nsubs equal to the number of dimensions in the mxArray that array_ptr points to.
subs
An array of integers. Each value in the array should specify that dimension’s subscript. The value in subs[0] specifies the row subscript, and the value in subs[1] specifies the column subscript. Note that mxCalcSingleSubscript views 0 as the first element of an mxArray, but MATLAB sees 1 as the first element of an mxArray. For example, in MATLAB, (1,1) denotes the starting element of a two-dimensional mxArray; however, to express the starting element of a two-dimensional mxArray in subs, you must set subs[0] to 0 and subs[1] to 0.
Returns
The number of elements between the start of the mxArray and the specified subscript. This returned number is called an “index”; many mx routines (for example, mxGetField) require an index as an argument.If subs describes the starting element of an mxArray, mxCalcSingleSubscript returns 0. If subs describes the final element of an mxArray, then
mxCalcSingleSubscript returns N-1 (where N is the total number of elements).
Description
Call mxCalcSingleSubscript to determine how many elements there are between the beginning of the mxArray and a given element of that mxArray. For example, given a subscript like (5,7), mxCalcSingleSubscript returns the distance from the (0,0) element of the array to the (5,7) element. Remember that the mxArray data type internally represents all data elements in a one-dimensional array no matter how many dimensions the MATLAB mxArray appears to have.mxCalcSingleSubscript
3-11 MATLAB uses a column-major numbering scheme to represent data elements internally. That means that MATLAB internally stores data elements from the first column first, then data elements from the second 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 data as shown below.
Although in fact, MATLAB internally represents the data as the following:
If an mxArray is N-dimensional, then MATLAB represents the data in N-major order. For example, consider a three-dimensional array having dimensions 4-by-2-by-3. Although you can visualize the data as
A E
B F
C G
D H
A B C D E F G H
Index 0
Index 1
Index 2
Index 3
Index 4
Index 5
Index 6
Index 7
mxCalcSingleSubscript
MATLAB internally represents the data for this three-dimensional array in the order shown below:
Avoid using mxCalcSingleSubscript to traverse the elements of an array. It is more efficient to do this by finding the array’s starting address and then using pointer auto-incrementing to access successive elements. For example, to find the starting address of a numerical array, call mxGetPr or mxGetPi.
Examples
See mxcalcsinglesubscript.c in the mx subdirectory of the examples directory.A B C D E F G H I J K L M N O P Q R S T U V W X
0 1 2 3 4 5 6 7 8 9 1
0 1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 0
2 1
2 2
2 3 A
B C D
E F G H
I J K L
M N O P
Q R S T
U V W X
Page 1
Page 2
Page 3
mxCalloc
3-13
3mxCalloc
Purpose
Allocate dynamic memory using MATLAB memory managerC Syntax
#include "matrix.h"#include <stdlib.h>
void *mxCalloc(size_t n, size_t size);
Arguments
nNumber of elements to allocate. This must be a nonnegative number.
size
Number of bytes per element. (The C sizeof operator calculates the number of bytes per element.)
Returns
A pointer to the start of the allocated dynamic memory, if successful. If unsuccessful in a stand-alone (nonMEX-file) application, mxCalloc returns NULL. If unsuccessful in a MEX-file, the MEX-file terminates and control returns to the MATLAB prompt.mxCalloc is unsuccessful when there is insufficient free heap space.
Description
MATLAB applications should always call mxCalloc rather than calloc to allocate memory. Note that mxCalloc works differently in MEX-files than 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 memory management facility.
The MATLAB memory management facility maintains a list of all memory allocated by mxCalloc. The MATLAB memory management facility
automatically frees (deallocates) all of a MEX-file’s parcels when control returns to the MATLAB prompt.
In stand-alone MATLAB applications, mxCalloc calls the ANSI C calloc function.
By default, in a MEX-file, mxCalloc generates nonpersistent mxCalloc data. In other words, the memory management facility automatically deallocates the
mxCalloc
memory as soon as the MEX-file ends. If you want the memory to persist after the MEX-file completes, call mexMakeMemoryPersistent after calling mxCalloc. If you write a MEX-file with persistent memory, be sure to register a mexAtExit function to free allocated memory in the event your MEX-file is cleared.
When you finish using the memory allocated by mxCalloc, call mxFree. mxFreedeallocates the memory.
Examples
See explore.c in the mex subdirectory of the examples directory, and phonebook.c and revord.c in the refbook subdirectory of the examples directory.For additional examples, see mxcalcsinglesubscript.c and
mxsetdimensions.c in the mx subdirectory of the examples directory.
See Also
mxFree, mxDestroyArray, mexMakeArrayPersistent, mexMakeMemoryPersistent, mxMallocmxChar
3-15
3mxChar
Purpose
Data type for string mxArrayC Syntax
typedef Uint16 mxChar;Description
All string mxArrays store their data elements as mxChar rather than as char. The MATLAB API defines an mxChar as a 16-bit unsigned integer.Examples
See mxmalloc.c in the mx subdirectory of the examples directory.For additional examples, see explore.c in the mex subdirectory of the
examples directory and mxcreatecharmatrixfromstr.c in the mx subdirectory of the examples directory.
See Also
mxCreateCharArraymxClassID
3mxClassID
Purpose
Integer value that identifies class of mxArrayC Syntax
typedef enum {mxUNKNOWN_CLASS = 0, mxCELL_CLASS,
mxSTRUCT_CLASS, mxLOGICAL_CLASS, mxCHAR_CLASS, <unused>, mxDOUBLE_CLASS, mxSINGLE_CLASS, mxINT8_CLASS, mxUINT8_CLASS, mxINT16_CLASS, mxUINT16_CLASS, mxINT32_CLASS, mxUINT32_CLASS, mxINT64_CLASS, mxUINT64_CLASS, mxFUNCTION_CLASS } mxClassID;
Constants
mxUNKNOWN_CLASSThe class cannot be determined. You cannot specify this category for an mxArray; however, mxGetClassID can return this value if it cannot identify the class.
mxCELL_CLASS
Identifies a cell mxArray. mxSTRUCT_CLASS
Identifies a structure mxArray. mxLOGICAL_CLASS
Identifies a logical mxArray; that is, an mxArray that stores Boolean elements logical 1 (true) and logical 0 (false).
mxCHAR_CLASS
Identifies a string mxArray; that is an mxArray whose data is represented as mxCHAR’s.
mxClassID
3-17 mxDOUBLE_CLASS
Identifies a numeric mxArray whose data is stored as double-precision, floating-point numbers.
mxSINGLE_CLASS
Identifies a numeric mxArray whose data is stored as single-precision, floating-point numbers.
mxINT8_CLASS
Identifies a numeric mxArray whose data is stored as signed 8-bit integers.
mxUINT8_CLASS
Identifies a numeric mxArray whose data is stored as unsigned 8-bit integers.
mxINT16_CLASS
Identifies a numeric mxArray whose data is stored as signed 16-bit integers.
mxUINT16_CLASS
Identifies a numeric mxArray whose data is stored as unsigned 16-bit integers.
mxINT32_CLASS
Identifies a numeric mxArray whose data is stored as signed 32-bit integers.
mxUINT32_CLASS
Identifies a numeric mxArray whose data is stored as unsigned 32-bit integers.
mxINT64_CLASS
Identifies a numeric mxArray whose data is stored as signed 64-bit integers.
mxUINT64_CLASS
Identifies a numeric mxArray whose data is stored as unsigned 64-bit integers.
mxFUNCTION_CLASS
Identifies a function handle mxArray.