c and fortran api reference

602
MATLAB ® C/C++, Fortran, Java, and Python API Reference R2017b

Upload: others

Post on 11-Sep-2021

25 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C and Fortran API Reference

MATLABreg

CC++ Fortran Java and Python APIReference

R2017b

How to Contact MathWorks

Latest news wwwmathworkscom

Sales and services wwwmathworkscomsales_and_services

User community wwwmathworkscommatlabcentral

Technical support wwwmathworkscomsupportcontact_us

Phone 508-647-7000

The MathWorks Inc3 Apple Hill DriveNatick MA 01760-2098

MATLABreg CC++ Fortran Javareg and Pythonreg API Referencecopy COPYRIGHT 1984ndash2017 by The MathWorks IncThe software described in this document is furnished under a license agreement The software may beused or copied only under the terms of the license agreement No part of this manual may be photocopiedor reproduced in any form without prior written consent from The MathWorks IncFEDERAL 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 ascommercial computer software or commercial computer software documentation as such terms are used ordefined in FAR 12212 DFARS Part 22772 and DFARS 252227-7014 Accordingly the terms andconditions of this Agreement and only those rights specified in this Agreement shall pertain to and governthe use modification reproduction release performance display and disclosure of the Program andDocumentation by the federal government (or other entity acquiring for or through the federalgovernment) and shall supersede any conflicting contractual terms or conditions If this License fails tomeet the governments needs or is inconsistent in any respect with federal procurement law thegovernment agrees to return the Program and Documentation unused to The MathWorks IncTrademarks

MATLAB and Simulink are registered trademarks of The MathWorks Inc Seewwwmathworkscomtrademarks for a list of additional trademarks Other product or brandnames may be trademarks or registered trademarks of their respective holdersPatents

MathWorks products are protected by one or more US patents Please seewwwmathworkscompatents for more information

Revision HistoryDecember 1996 First Printing New for MATLAB 5 (Release 8)May 1997 Online only Revised for MATLAB 51 (Release 9)January 1998 Online Only Revised for MATLAB 52 (Release 10)January 1999 Online Only Revised for MATLAB 53 (Release 11)September 2000 Online Only Revised for MATLAB 60 (Release 12)June 2001 Online only Revised for MATLAB 61 (Release 121)July 2002 Online only Revised for MATLAB 65 (Release 13)January 2003 Online only Revised for MATLAB 651 (Release 13SP1)June 2004 Online only Revised for MATLAB 70 (Release 14)October 2004 Online only Revised for MATLAB 701 (Release 14SP1)March 2005 Online only Revised for MATLAB 704 (Release 14SP2)September 2005 Online only Revised for MATLAB 71 (Release 14SP3)March 2006 Online only Revised for MATLAB 72 (Release 2006a)September 2006 Online only Revised for MATLAB 73 (Release 2006b)March 2007 Online only Revised and renamed for MATLAB 74

(Release 2007a)September 2007 Online only Revised and renamed for MATLAB 75

(Release 2007b)March 2008 Online only Revised and renamed for MATLAB 76

(Release 2008a)October 2008 Online only Revised and renamed for MATLAB 77

(Release 2008b)March 2009 Online only Revised for MATLAB 78 (Release 2009a)September 2009 Online only Revised for MATLAB 79 (Release 2009b)March 2010 Online only Revised and renamed for MATLAB 710

(Release 2010a)September 2010 Online only Revised for MATLAB 711 (Release 2010b)April 2011 Online only Revised for MATLAB 712 (Release 2011a)September 2011 Online only Revised for MATLAB 713 (Release 2011b)March 2012 Online only Revised for MATLAB 714 (Release 2012a)September 2012 Online only Revised for MATLAB 80 (Release 2012b)March 2013 Online only Revised for MATLAB 81 (Release 2013a)September 2013 Online only Revised for MATLAB 82 (Release 2013b)March 2014 Online only Revised for MATLAB 83 (Release 2014a)October 2014 Online only Revised for MATLAB 84 (Release 2014b)March 2015 Online only Revised for MATLAB 85 (Release 2015a)September 2015 Online only Revised for MATLAB 86 (Release 2015b)March 2016 Online only Revised for MATLAB 90 (Release 2016a)September 2016 Online only Revised for MATLAB 91 (Release 2016b)March 2017 Online only Revised for MATLAB 92 (Release 2017a)September 2017 Online only Revised for MATLAB 93 (Release 2017b)

API Reference1

v

Contents

API Reference

1

matlabdataArrayDimensionsType specifying array dimensions

DescriptionUse the ArrayDimensions type to specify the size of an array ArrayDimensions isspecified as

using ArrayDimensions = stdvectorltsize_tgt

Free Function

getNumElementsinline size_t getNumElements(const ArrayDimensionsamp dims)

Determine the number of elements based on the ArrayDimensions

const ArrayDimensionsampdims

Array dimensions

inline size_t Number of elements

None

See Also

TopicsldquoMATLAB Data API Typesrdquo

1 API Reference

1-2

Introduced in R2017b

matlabdataArrayDimensions

1-3

matlabdataArrayElementRefC++ class representing element of Array or ReferenceltArraygt object

DescriptionAn ArrayElementRef object is created when using operator[] into an Array or aReferenceltArraygt It is untyped since Array and ReferenceltArraygt do not havetype information It collects up the indexes specified by the user and can be cast to anelement if the array holds primitive data or can be used to create a ReferenceltTgtinstance

Indexing is zero-based

Class DetailsNamespace matlabdataInclude ArrayElementRefhpp

Template Parametersbool is_const_ref Indicates if this reference is const The non-const

version of this class supports assignment

Other Operatorsbull ldquooperator[]rdquo on page 1-4bull ldquooperator Trdquo on page 1-5bull ldquooperator=rdquo on page 1-6

operator[]ArrayElementRefltis_const_refgt operator[](size_t idx)

ArrayElementRefltis_const_refgt operator[](stdstring idx)

1 API Reference

1-4

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indices in anindexing operation

stdstring idx Index to add Array must support string indexing

TooManyIndicesProvidedException

Too many indices provided The number of size_tindices is more than the number of dimensions in thearray

StringIndexMustBeLastException

String index is not the last index A size_t index isprovided after a string index

StringIndexNotValidException

An stdstring index is not valid for this array

CanOnlyUseOneStringIndexException

More than one stdstring index provided

double val = arr[2][7][f1]

operator Ttemplate lttypename Tgtoperator T() const

Cast a value Throws an error if not arithmetic complex or stdstring

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain the type specifiedby T

Array dblArray_const = factorycreateArrayltdoublegt(22)double val = dblArray_const[1][2]

matlabdataArrayElementRef

1-5

operator=template lttypename TgtArrayElementRefltis_const_refgtamp operator= (T rhs)

Assign a primitive or complex type to an element of an Array The Array must be non-const

If the Array contains other Arrays then operator= can assign an Array into theelement

T rhs The value to assign to an element in the Array specifiedas a primitive or complex type or as an Array

ArrayElementRefltis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain a primitive orcomplex type or does not contain other Arrays

Assign numeric types to Array arr

Array arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55arr[1][2] = stdcomplexltdoublegt(54 31)

Assign an Array to cell_arr then create a ReferenceltArraygt ref to the element

Array cell_arr = factorycreateArrayltArraygt(13)cell_arr[2] = factorycreateScalar(true)ReferenceltArraygt ref = cell_arr[2]

See AlsoArray | ArrayElementTypedRef | Reference | TypedArrayRef

1 API Reference

1-6

Introduced in R2017b

matlabdataArrayElementRef

1-7

matlabdataArrayElementTypedRefC++ class representing element of TypedArray or TypedArrayRef object

DescriptionAn ArrayElementTypedRef object is created when using operator[] into aTypedArrayltTgt or a TypedArrayRefltTgt It collects up the indexes specified by theuser and can be cast to ltTgt without the added cost of type checking that exists whenusing ArrayElementRef Primitive types can be cast to Tamp which is not supported withArrayElementRef The non-const version of this class supports assignment

Class DetailsNamespace matlabdataInclude ArrayElementTypedRefhpp

Template ParametersT Element typesbool is_const_ref TBD

Other Operatorsbull ldquooperator[]rdquo on page 1-8bull ldquooperator referencerdquo on page 1-9bull ldquooperator=rdquo on page 1-10

operator[]ArrayElementTypedRefltT is_const_refgt operator[](size_t idx)

ArrayElementTypedRefltArray is_const_refgt operator[](stdstringidx)

1 API Reference

1-8

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indicesin an indexing operation

stdstring idx Index to add Array must support string indexing

ArrayElementTypedRefltArray is_const_refgt

New instance with the additional index

TooManyIndicesProvidedException

Too many indices provided

StringIndexMustBeLastException

String index is not the last index

double val = arr[2][7][3]

operator referenceoperator reference() const

operator stdstring() const

Cast to reference to its primitive value

T

stdstring

The value

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

double val = dblArray[1][2]

stdstring val = strArray[1][2]

matlabdataArrayElementTypedRef

1-9

operator=ArrayElementTypedRefltT is_const_refgtamp operator= (T rhs)

ArrayElementTypedRefltT is_const_refgtamp operator= (stdstring rhs)

Assign a value into an Array The Array must be non-const

T rhs

stdstring rhs

Value to assign to an element in the Array

ArrayElementTypedRefltTis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

arr[1][2] = stdcomplexltdoublegt(54 31)

arr[1][2] = MyString

ExamplesTBD

TypedArrayltdoublegt arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55doubleamp val = arr[0][0]CellArray cell_arr = factorycreateArrayltArraygt(12)cell_arr[0] = factorycreateScalar(105)cell_arr[1] = factorycreateScalar(false)ArrayRef ref_to_element = cell_arr[0]TypedArrayRefltdoublegt typed_ref_to_element = cell_arr[0]

1 API Reference

1-10

Array const shared_copy_of_element = cell_arr[1]TypedArrayltboolgt const typed_shared_copy_of_element = cell_arr[1]

See AlsoArray | ArrayElementRef | ArrayElementTypedRef | Reference |TypedArrayRef | TypedIterator

Introduced in R2017b

matlabdataArrayElementTypedRef

1-11

matlabdataArrayFactoryC++ class to create arrays

DescriptionUse ArrayFactory to create matlabdataArray objects

Class DetailsNamespace matlabdataInclude ArrayFactoryhpp

Constructors

Default Constructor

ArrayFactory()

FailedToLoadLibMatlabDataArrayException

Concrete implementation has not been loaded

Destructor~ArrayFactory()

Member Functionsbull ldquocreateArrayrdquo on page 1-13bull ldquocreateScalarrdquo on page 1-14bull ldquocreateCellArrayrdquo on page 1-15

1 API Reference

1-12

bull ldquocreateCharArrayrdquo on page 1-16bull ldquocreateStructArrayrdquo on page 1-17bull ldquocreateEnumArrayrdquo on page 1-18bull ldquocreateSparseArrayrdquo on page 1-19bull ldquocreateEmptyArrayrdquo on page 1-20bull ldquocreateBufferrdquo on page 1-21bull ldquocreateArrayFromBufferrdquo on page 1-21

createArraytemplate lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims)

template lttypename ItType typename TgtTypedArrayltTgt createArray(ArrayDimensions dims ItType begin ItType end)

template lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims const T const begin const T const end)

template lttypename Tgt TypedArrayltTgt createArray(ArrayDimensions dims stdinitializer_listltTgt data)

Creates a TypedArrayltTgt with the given dimensions Fills the array with data ifspecified Data is copied and must be in column major order

bull ItType - Iterator types specified as stditeratorbull T - Element types specified as one of the following C++ data types

bool int8_t int16_t int32_t int64_t uint8_tuint16_t uint32_t uint64_t float double char16_t

matlabdataArrayFactory

1-13

matlabdataString

stdcomplexltdoublegt

stdcomplexltfloatgt

stdcomplexltint8_tgt

stdcomplexltuint8_tgt

stdcomplexltint16_tgt

stdcomplexltuint16_tgt

stdcomplexltint32_tgt

stdcomplexltuint32_tgt

stdcomplexltint64_tgt

stdcomplexltuint64_tgt

matlabdataMATLABString

ArrayDimensionsdims

Dimensions for the array

ItType begin

ItType end

Start and end of the user supplied data The data type isdetermined by the value_type of the iterator

const T constbegin

const T const end

Start and end of the user supplied data specified as C-stylepointer Supports all primitive types complex types andstring types

stdinitializer_listltTgt

Initializer list containing the data

matlabOutOfMemoryException

The array could not be allocated

createScalartemplate lttypename TgtTypedArrayltTgt createScalar(const T val)

TypedArrayltStringgt createScalar(const String val)

TypedArrayltStringgt createScalar(const stdstring val)

Creates a scalar TypedArrayltTgt with the given value This method supports arithmetictypes complex types and string types

const T val Value to be inserted into the scalar If valis 7-bit ASCII data then the methodconverts it to UTF16

const String valconst stdstring val

1 API Reference

1-14

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory

Create a vector containing 2 scalar values stdvectorltmatlabdataArraygt args( factorycreateScalarltint16_tgt(100) factorycreateScalarltint16_tgt(60)) return 0

ldquoCall Function with Single Returned Argumentrdquo

createCellArrayCellArrayltArraygt createCellArray(ArrayDimensions dims)

template lttypename TargsgtCellArrayltArraygt createCellArray(ArrayDimensions dims Targs data)

Creates a CellArray with the specified data Data is specified in column major order

Targs Variadic template of

bull arithmetic typebull complex typebull matlabdataStringbull stdstringbull matlabdataArray

matlabdataArrayFactory

1-15

ArrayDimensionsdims

Dimensions of the cell array

Targs data Elements to be inserted into the cell array specified as aprimitive complex type string or Array

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f CellArray myArray = fcreateCellArray( 12 fcreateCharArray(MATLAB Cell Array) fcreateArrayltdoublegt( 22 12 22 32 42 ))

return 0

createCharArrayCharArray createCharArray(String str)

CharArray createCharArray(stdstring str)

Creates a 1xn CharArray from the specified input where n is the string length

matlabdataString str

Data to be filled into the array

stdstring str

matlabOutOfMemoryException

The array could not be allocated

1 API Reference

1-16

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) return 0

createStructArrayStructArray createStructArray(ArrayDimensions dims stdvectorltstdstringgt fieldNames)

Creates a StructArray with the given dimensions and field names

ArrayDimensions dims Dimensions for the arraystdvectorltstdstringgtfieldNames

Vector of the field names for the structure

matlabOutOfMemoryException

The array could not be allocated

DuplicateFieldNameInStructArrayException

Duplicate field names specified

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f

Create StructArray equivalent to MATLAB structure s s = struct(loc east west data [1 2 3] [4 5 6 7 8]) StructArray S = fcreateStructArray( 12 loc data ) S[0][loc] = fcreateCharArray(east) S[0][data] = fcreateArrayltuint8_tgt( 1 3 1 2 3 )

matlabdataArrayFactory

1-17

S[1][loc] = fcreateCharArray(west) S[1][data] = fcreateArrayltdoublegt( 1 5 4 5 6 7 8 )

Access the value defined by the MATLAB statement s(1)data ReferenceltArraygt val = S[0][data] return 0

createEnumArrayEnumArray createEnumArray(ArrayDimensions dims stdstring className stdvectorltstdstringgt enums)

EnumArray createEnumArray(ArrayDimensions dims stdstring className)

Creates an EnumArray of type className If specified the array is initialized with thelist of enumeration names

ArrayDimensionsdims

Dimensions for the array

stdstringclassName

Class name of the enumeration array

stdvectorltstdstringgt enums

List of the enumeration names

matlabOutOfMemoryException

The array could not be allocated

MustSpecifyClassNameException

Class name not specified

WrongNumberOfEnumsSuppliedException

The wrong number of enumerations provided

include MatlabDataArrayhppinclude ltvectorgt

1 API Reference

1-18

int main() using namespace matlabdata ArrayFactory f auto blue = fcreateEnumArray( 11 TextColor Blue )

Create an argument vector stdvectorltArraygt args( fcreateCharArray(My text) stdmove(blue) )

return 0

createSparseArraytemplate lttypename TgtSparseArrayltTgt createSparseArray(ArrayDimensions dims size_t nnz buffer_ptr_tltTgt data buffer_ptr_tltsize_tgt rows buffer_ptr_tltsize_tgt cols)

Creates a SparseArrayltTgt with rows-by-cols dimensions Only two dimensions areallowed for sparse arrays The buffer is not copied and the array takes ownership

T Element types specified as double bool orstdcomplexltdoublegt

ArrayDimensionsdims

Dimensions for the array

size_t nnz Number of nonzero elementsbuffer_ptr_tltTgtdata

Buffer containing the nonzero elements

buffer_ptr_tltsize_tgt rows

Buffer containing the row value for each element

buffer_ptr_tltsize_tgt cols

Buffer containing the column value for each element

matlabdataArrayFactory

1-19

matlabOutOfMemoryException

The array could not be allocated

InvalidDimensionsInSparseArrayException

More than two dimensions are specified

include MatlabDataArrayhpp

int main() stdvectorltdoublegt data = 35 1298 2176 stdvectorltsize_tgt rows = 001 stdvectorltsize_tgt cols = 048 size_t nnz = 3

matlabdataArrayFactory factory auto data_p = factorycreateBufferltdoublegt(nnz) auto rows_p = factorycreateBufferltsize_tgt(nnz) auto cols_p = factorycreateBufferltsize_tgt(nnz)

double dataPtr = data_pget() size_t rowsPtr = rows_pget() size_t colsPtr = cols_pget() stdfor_each(databegin() dataend() [amp](const doubleamp e) (dataPtr++) = e ) stdfor_each(rowsbegin() rowsend() [amp](const size_tamp e) (rowsPtr++) = e ) stdfor_each(colsbegin() colsend() [amp](const size_tamp e) (colsPtr++) = e )

matlabdataSparseArrayltdoublegt arr = factorycreateSparseArrayltdoublegt( 29 nnz stdmove(data_p) stdmove(rows_p) stdmove(cols_p)) return 0

createEmptyArrayArray createEmptyArray()

Creates an empty Array containing no elements

Array Empty array

1 API Reference

1-20

matlabOutOfMemoryException

The array could not be allocated

createBuffertemplate lttypename Tgtbuffer_ptr_tltTgt createBuffer(size_t numberOfElements)

Creates a buffer which can be passed into createArrayFromBuffer No data copies aremade when creating an array from a buffer Data must be in column major order

T Primitive types

size_t numberOfElements Number of elements not the actualbuffer size

buffer_ptr_tltTgt Unique_ptr containing the buffer

matlabOutOfMemoryException

The array could not be allocated

createArrayFromBuffertemplate lttypename TgtTypedArrayltTgt createArrayFromBuffer(ArrayDimensions dims buffer_ptr_tltTgt buffer)

Creates a TypedArrayltTgt using the given buffer

T Primitive types

ArrayDimensions dims Dimensions for the arraybuffer_ptr_tltTgt buffer Buffer containing the data The buffer is not

copied The TypedArrayltTgt object takesownership of the buffer Data must be in columnmajor order

matlabdataArrayFactory

1-21

matlabOutOfMemoryException

The array could not be allocated

See Also

Introduced in R2017b

1 API Reference

1-22

matlabdataReferenceltArraygtC++ class to get reference to Array

DescriptionUse the ReferenceltArraygt class to get a reference to an Array element of a containerobject such as a MATLAB structure or cell array The class is a base class for allreference types that refer to arrays and provides basic array information ArrayRef isdefined as

using ArrayRef = ReferenceltArraygt

Class DetailsNamespace matlabdataInclude ArrayReferenceExthpp

Member Functionsbull ldquogetTyperdquo on page 1-23bull ldquogetDimensionsrdquo on page 1-24bull ldquogetNumberOfElementsrdquo on page 1-24bull ldquoisEmptyrdquo on page 1-24

getTypeArrayType getType() const

ArrayType Type of the array

NotEnoughIndicesProvidedException

Not enough indices provided

matlabdataReferenceltArraygt

1-23

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

InvalidArrayTypeException

Array type not recognized

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Array dimensions vector

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

getNumberOfElementssize_t getNumberOfElements() const

size_t Number of elements in array

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

isEmptybool isEmpty() const

bool Returns true if array is empty otherwise returns false

NotEnoughIndicesProvidedException

Not enough indices provided

1 API Reference

1-24

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-25bull ldquogetWritableElementsrdquo on page 1-25

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are const

const ReferenceltArraygtampref

ReferenceltArraygt

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are non-const

ReferenceltArraygtamp ref ReferenceltArraygt

matlabdataReferenceltArraygt

1-25

RangeltTypedIterator Tgt Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayType

Introduced in R2017b

1 API Reference

1-26

matlabdataArrayTypeC++ array type enumeration class

DescriptionUse ArrayType objects to identify the data type and other attributes of a MATLABarray

Class DetailsNamespace matlabdataInclude ArrayTypehpp

Enumerationenum class ArrayType UNKNOWN LOGICAL CHAR DOUBLE SINGLE INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 COMPLEX_DOUBLE COMPLEX_SINGLE COMPLEX_INT8 COMPLEX_UINT8 COMPLEX_INT16 COMPLEX_UINT16 COMPLEX_INT32 COMPLEX_UINT32

matlabdataArrayType

1-27

COMPLEX_INT64 COMPLEX_UINT64 CELL STRUCT OBJECT VALUE_OBJECT HANDLE_OBJECT_REF ENUM SPARSE_LOGICAL SPARSE_DOUBLE SPARSE_COMPLEX_DOUBLE MATLAB_STRING

C++ Data Type ConversionMATLAB ArrayType Value C++ Type DescriptionDOUBLE double double-precision (64-bit)

floating-point numberSINGLE float single-precision (32-bit)

floating-point numberINT8 int8_t signed 8-bit integerUINT8 uint8_t unsigned 8-bit integerINT16 int16_t signed 16-bit integerUINT16 uint16_t unsigned 16-bit integerINT32 int32_t signed 32-bit integerUINT32 uint32_t unsigned 32-bit integerINT64 int64_t signed 64-bit integerUINT64 uint64_t unsigned 64-bit integerCHAR char16_t 16-bit characterLOGICAL bool logicalCOMPLEX_DOUBLE stdcomplexltdoublegt complex double-precision

(64-bit) floating-pointnumber

1 API Reference

1-28

MATLAB ArrayType Value C++ Type DescriptionCOMPLEX_SINGLE stdcomplexltfloatgt complex single precision

(32-bit) floating-pointnumber

COMPLEX_INT8 stdcomplexltint8_tgt complex signed 8-bitinteger

COMPLEX_UINT8 stdcomplexltuint8_tgt complex unsigned 8-bitinteger

COMPLEX_INT16 stdcomplexltint16_tgt complex signed 16-bitinteger

COMPLEX_UINT16 stdcomplexltuint16_tgt complex unsigned 16-bitinteger

COMPLEX_INT32 stdcomplexltint32_tgt complex signed 32-bitinteger

COMPLEX_UINT32 stdcomplexltuint32_tgt complex unsigned 32-bitinteger

COMPLEX_INT64 stdcomplexltint64_tgt complex signed 64-bitinteger

COMPLEX_UINT64 stdcomplexltuint64_tgt complex unsigned 64-bitinteger

CELL matlabdataArray Array containing otherArrays

STRUCT matlabdataStruct Array with named fieldsthat can contain data ofvarying types and sizes

OBJECT matlabdataObject MATLAB objectVALUE_OBJECT matlabdataObject MATLAB value objectHANDLE_OBJECT_REF matlabdataObject Reference to an existing

handle object in MATLABENUM matlabdataEnumerat

ionArray of enumerationvalues

SPARSE_LOGICAL bool Sparse array of logicalSPARSE_DOUBLE double Sparse array of double

matlabdataArrayType

1-29

MATLAB ArrayType Value C++ Type DescriptionSPARSE_COMPLEX_DOUBLE stdcomplexltdoublegt Sparse array of complex

doubleMATLAB_STRING matlabdataMATLABSt

ringMATLAB string

See AlsoArrayVisitors

Introduced in R2017b

1 API Reference

1-30

matlabdataArrayVisitorsFunctions for defining visitor pattern

DetailsNamespace matlabdataInclude ArrayVisitorshpp

Functionsbull ldquoapply_visitorrdquo on page 1-31bull ldquoapply_visitor_refrdquo on page 1-31

apply_visitorauto apply_visitor(Array a V visitor)

TBD

TBD

InvalidArrayTypeException

apply_visitor_refauto apply_visitor_ref(const ArrayRefamp a V visitor)

Apply functor V to Array a

Result of V

matlabdataArrayVisitors

1-31

InvalidArrayTypeException

See Also

Introduced in R2017b

1 API Reference

1-32

matlabdataCellArrayC++ class to access MATLAB cell arrays

DescriptionA CellArray is a TypedArray with Array as the element type Use CellArray objectsto access MATLAB cell arrays To create a CellArray call createCellArrayCellArray is defined as

using CellArray = TypedArrayltArraygt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

ExamplesCreate Cell Array

Create a cell array with two elements

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CellArray cellArray1 = factorycreateCellArray( 12 factorycreateCharArray(MATLAB Cell Array) factorycreateArrayltdoublegt( 22 12 22 32 42 ))

matlabdataCellArray

1-33

return 0

See AlsocreateCellArray

Introduced in R2017b

1 API Reference

1-34

matlabdataCharArrayC++ class to access MATLAB character arrays

DescriptionUse CharArray objects to work with MATLAB character arrays To create a CharArraycall createCharArray

Class DetailsNamespace matlabdataBase class TypedArrayltchar16_tgtInclude CharArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-35bull ldquoCopy Assignment Operatorsrdquo on page 1-36bull ldquoMove Constructorsrdquo on page 1-37bull ldquoMove Assignment Operatorsrdquo on page 1-37

Copy Constructors

CharArray(const CharArrayamp rhs)

CharArray(const Arrayamp rhs)

Creates a shared data copy of a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

matlabdataCharArray

1-35

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray B(A) return 0

createCharArray on page 1-16

Copy Assignment OperatorsCharArrayamp operator=(const CharArrayamp rhs)

CharArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray C = factorycreateCharArray()

1 API Reference

1-36

Arrays A and C refer to the same data C = A

return 0

Move Constructors

CharArray(CharArrayampamp rhs)

CharArray(Arrayampamp rhs)

Moves contents of a CharArray object to a new instance

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move constructor - Creates B copies data from A A not valid CharArray B(stdmove(A))

return 0

Move Assignment Operators

CharArrayamp operator=(CharArrayampamp rhs)

CharArrayamp operator=(Arrayampamp rhs)

matlabdataCharArray

1-37

Assigns the input to this CharArray object

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move assignment - Data from A moved to C A no longer valid CharArray C = factorycreateCharArray() C = stdmove(A)

return 0

Member Functionsbull ldquotoUTF16rdquo on page 1-38bull ldquotoAsciirdquo on page 1-39

toUTF16String toUTF16() const

matlabdataString Contents of CharArray as matlabdataString

None

1 API Reference

1-38

toAsciistdstring toAscii() const

stdstring Contents of CharArray as ASCII string

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f auto arr = fcreateCharArray(helloworld) stdstring s = arrtoAscii()

return 0

ldquoEvaluate Mathematical Function in MATLABrdquo

See AlsoldquocreateCharArrayrdquo on page 1-16 | TypedArray | matlabdataString

Introduced in R2017b

matlabdataCharArray

1-39

matlabdataReferenceltCharArraygtC++ class to get reference to CharArray

DescriptionThe CharArrayExt class extends the APIs available to a reference to a CharArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquotoUTF16rdquo on page 1-40bull ldquotoAsciirdquo on page 1-40

toUTF16String toUTF16() const

matlabdataString Contents of reference to CharArray as a utf16 string

None

toAsciistdstring toAscii() const

stdstring Contents of reference to CharArray asmatlabdataString

1 API Reference

1-40

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

See AlsoCharArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltCharArraygt

1-41

matlabdataEnumArrayC++ class to access MATLAB enumeration arrays

DescriptionUse EnumArray objects to access enumeration arrays To create an EnumArray callcreateEnumArray

Class DetailsNamespace matlabdataBase class TypedArrayltEnumerationgtInclude EnumArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-42bull ldquoCopy Assignment Operatorsrdquo on page 1-43bull ldquoMove Constructorsrdquo on page 1-43bull ldquoMove Assignment Operatorsrdquo on page 1-43

Copy Constructors

EnumArray(const EnumArrayamp rhs)

EnumArray(const Arrayamp rhs)

Creates a shared data copy of an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as EnumArray object

1 API Reference

1-42

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Copy Assignment OperatorsEnumArrayamp operator=(const EnumArrayamp rhs)

EnumArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move ConstructorsEnumArray(EnumArrayampamp rhs)

EnumArray(Arrayampamp rhs)

Moves contents of an EnumArray object to a new instance

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move Assignment OperatorsEnumArrayamp operator=(EnumArrayampamp rhs)

matlabdataEnumArray

1-43

EnumArrayamp operator=(Arrayampamp rhs)

Assigns the input to this EnumArray object

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Member Functions

getClassNamestdstring getClassName() const

Return class name for this EnumArray

stdstring The class name

None

See AlsoldquocreateEnumArrayrdquo on page 1-18 | TypedArray

Introduced in R2017b

1 API Reference

1-44

matlabdataReferenceltEnumArraygtC++ class to get reference to EnumArray

DescriptionThe EnumArrayExt class extends the APIs available to a reference to an EnumArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functions

getClassNamestdstring getClassName() const

Return class name for this reference to an EnumArray object

stdstring Class name

None

See AlsoEnumArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltEnumArraygt

1-45

matlabdataEnumerationElement type for MATLAB enumeration arrays

DescriptionEnumeration is the element type for an EnumArray object

Class DetailsNamespace matlabdataInclude Enumerationhpp

See AlsoEnumArray

TopicsldquoMATLAB Data API Typesrdquo

Introduced in R2017b

1 API Reference

1-46

matlabExceptionC++ base class for exceptions

DescriptionAll MATLAB C++ exceptions can be caught as matlabException

Class DetailsNamespace matlabInclude Exceptionhpp

See Also

TopicsldquoMATLAB Data API Exceptionsrdquo

Introduced in R2017b

matlabException

1-47

matlabdataForwardIteratorltTgtTemplated C++ class to provide forward iterator support for StructArray field names

DescriptionUse ForwardIterator objects to access a range of field name elements in aStructArray

Class DetailsNamespace matlabdataInclude ForwardIteratorhpp

Template ParametersT matlabdataMATLABFieldIdentifier

Constructorsbull ldquoCopy Constructorsrdquo on page 1-48bull ldquoCopy Assignment Operatorsrdquo on page 1-49

Copy Constructors

ForwardIterator(const ForwardIteratorltTgtamp rhs)

Creates a shared data copy of a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to copy

ForwardIterator New instance

1 API Reference

1-48

None

Copy Assignment Operators

ForwardIteratorltTgtamp operator=(const ForwardIteratorltTgtamp rhs)

Assigns a shared data copy to a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to assign

ForwardIteratorltTgt Updated instance

None

Other Operatorsbull ldquooperator++rdquo on page 1-49bull ldquooperator--rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperatorrdquo on page 1-51bull ldquooperator-gtrdquo on page 1-51bull ldquooperator[]rdquo on page 1-51

operator++ForwardIteratorltTgtamp operator++()

Pre-increment operator

ForwardIteratorltTgtamp Reference to updated value

matlabdataForwardIteratorltTgt

1-49

None

operator--ForwardIteratorltTgt operator--(int)

Post-increment operator

ForwardIteratorltTgt New object

None

operator=bool operator==(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if the iterators point to the same elementOtherwise returns false

None

operator=bool operator=(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if this iterator points to a differentelement Otherwise returns false

None

1 API Reference

1-50

operatorreference operator() const

reference Shared copy of element that iterator points to specifiedas

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataForwardIteratorltTgt

1-51

See AlsoMATLABFieldIdentifier | StructArray

Introduced in R2017b

1 API Reference

1-52

matlabdataGetArrayTypeC++ struct TBD

DescriptionUse GetArrayType objects to TBD

Class DetailsNamespace matlabdataInclude GetArrayTypehpp

See Also

Introduced in R2017b

matlabdataGetArrayType

1-53

matlabdataGetReturnTypeC++ struct TBD

DescriptionUse GetReturnType to convert a template argument to the appropriate templateargument when creating a TypedArray

Class DetailsNamespace matlabdataInclude GetReturnTypehpp

See Also

Introduced in R2017b

1 API Reference

1-54

matlabdataMATLABFieldIdentifierC++ class used to identify field names in MATLAB struct array

Description

Class DetailsNamespace matlabdataInclude MATLABFieldIdentifierhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-55bull ldquoConstructorrdquo on page 1-55bull ldquoDestructorrdquo on page 1-56bull ldquoCopy Constructorsrdquo on page 1-56bull ldquoCopy Assignment Operatorsrdquo on page 1-56bull ldquoMove Constructorsrdquo on page 1-57bull ldquoMove Assignment Operatorsrdquo on page 1-57

Default ConstructorMATLABFieldIdentifier()

Construct an empty MATLABFieldIdentifier

None

ConstructorMATLABFieldIdentifier(stdstring str)

matlabdataMATLABFieldIdentifier

1-55

Construct a MATLABFieldIdentifier from stdstring

stdstring str String that contains the field name

Destructor

~MATLABFieldIdentifier()

Destroy a MATLABFieldIdentifier

None

Copy Constructors

MATLABFieldIdentifier(const MATLABFieldIdentifieramp rhs)

Creates a shared data copy of a MATLABFieldIdentifier object

constMATLABFieldIdentifieramprhs

Value to copy

None

Copy Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifier constamp rhs)

Assigns a shared data copy to a MATLABFieldIdentifier object

MATLABFieldIdentifierconstamp rhs

Value to move

1 API Reference

1-56

MATLABFieldIdentifieramp Updated instance

None

Move Constructors

MATLABFieldIdentifier(MATLABFieldIdentifierampamp rhs)

Moves contents a MATLABFieldIdentifier object to a new instance

MATLABFieldIdentifierampamprhs

Value to move

None

Move Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifierampamp rhs)

MATLABFieldIdentifierampamprhs

Value to move

MATLABFieldIdentifieramp Updated instance

None

Destructor~MATLABFieldIdentifier()

Description

Destroy a MATLABFieldIdentifier

matlabdataMATLABFieldIdentifier

1-57

Other Operators

operator stdstringoperator stdstring() const

stdstring Representation of the MATLABFieldIdentifier object

None

Free Functions

operator==bool operator==(const MATLABFieldIdentifieramp rhs) const

Check if two MATLABFieldIdentifier objects are identical

constMATLABFieldIdentifieramprhs

Value to be compared

bool Returns true if the objects are identical Otherwisereturns false

None

See AlsoForwardIterator | StructArray

Introduced in R2017b

1 API Reference

1-58

matlabdataMATLABStringElement type for MATLAB string arrays

DescriptionMATLABString is defined as

using MATLABString = OptionalltStringgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataString

Introduced in R2017b

matlabdataMATLABString

1-59

matlabdataReferenceltMATLABStringgtC++ class to get reference to element of StringArray

DescriptionA ReferenceltMATLABStringgt object is created when using operator[] into anStringArray or dereferenceing a String arrary iterator

Class DetailsNamespace matlabdataInclude MATLABStringReferenceExthpp

Cast

String()operator String() const

matlabdataString Element of a MATLABString array converted toString

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

stdruntime_error Array element does not have a value

1 API Reference

1-60

Member Functionsbull ldquoboolrdquo on page 1-61bull ldquohas_valuerdquo on page 1-61

booloperator bool() const

Check whether string contains a value

operator True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

has_valuebool has_value() const

Check whether string contains a value

bool True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

matlabdataReferenceltMATLABStringgt

1-61

See Also

Introduced in R2017b

1 API Reference

1-62

matlabdataArrayC++ base class for all array types

DescriptionUse Array objects to represent single and multi-dimensional arrays The Array classprovides methods for users to be able to query generic information about all arrays suchas dimensions and type and has methods to create deep copies and shared data copiesUse ArrayFactory methods to construct Arrays Once an Array has been constructedit can be moved or cloned (deep-copied) or a shared-data copy can be created Arrayssupport copy-on-write semantics

Class DetailsNamespace matlabdataInclude MDArrayhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-63bull ldquoCopy Constructorsrdquo on page 1-64bull ldquoCopy Assignment Operatorsrdquo on page 1-64bull ldquoMove Constructorsrdquo on page 1-64bull ldquoMove Assignment Operatorsrdquo on page 1-65

Default Constructor

Array()

None

matlabdataArray

1-63

Copy Constructors

Array(const Arrayamp rhs)

Creates a shared data copy of an Array object

const Arrayamp rhs Value to copy

None

Copy Assignment Operators

Arrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an Array object

const Arrayamp rhsrhs Value to copy

Arrayamp Updated instance

None

Move Constructors

Array(Arrayampamp rhs)

Moves contents of an Array object to a new instance

Arrayampamp rhs Value to move

None

1 API Reference

1-64

Move Assignment Operators

Arrayamp operator=(Arrayampamp rhs)

Assigns the input to this Array object

Arrayampamp rhs Value to move

Arrayamp Updated instance

None

Destructorvirtual ~Array()

Indexing Operators

operator[]ArrayElementRefltfalsegt operator[](size_t idx)

ArrayElementReflttruegt operator[](size_t idx) const

Enables [] indexing on const and non-const arrays Indexing is 0-based

size_t idx First array index

ArrayElementRefltfalsegt Temporary object containing the index specified Thereturn value allows the element of the array to bemodified or retrieved

matlabdataArray

1-65

ArrayElementReflttruegt Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Member Functionsbull ldquogetTyperdquo on page 1-66bull ldquogetDimensionsrdquo on page 1-66bull ldquogetNumberOfElementsrdquo on page 1-66bull ldquoisEmptyrdquo on page 1-67

getTypeArrayType getType() const

ArrayType Array type

None

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Vector of each dimension in the array

None

getNumberOfElementssize_t getNumberOfElements() const

size_t The number of elements in the array

1 API Reference

1-66

None

isEmptybool isEmpty() const

bool True if array is empty False if array is not empty

None

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-67bull ldquogetWritableElementsrdquo on page 1-67

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const Arrayamp arr)

Get a range containing the elements of the Array Iterators contained in the range areconst

const Arrayamp arr Array

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(Arrayamp arr)

matlabdataArray

1-67

Get a range containing the elements of the Array Iterators contained in the range arenon-const

Arrayamp arr Array

RangeltTypedIterator Tgt Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayFactory

Introduced in R2017b

1 API Reference

1-68

matlabdataObjectElement type for MATLAB object arrays

DescriptionObject is the element type for an ObjectArray

Class DetailsNamespace matlabdataInclude Objecthpp

See AlsoObjectArray

Introduced in R2017b

matlabdataObject

1-69

matlabdataObjectArrayC++ class to access MATLAB object arrays

DescriptionUse ObjectArray objects to access MATLAB object arrays You do not create anObjectArray only MATLAB functions create ObjectArrays You can pass anObjectArray to a MATLAB function

ObjectArray is defined as

using ObjectArray = TypedArrayltObjectgt

Class DetailsNamespace matlabdataInclude ObjectArrayhpp

See AlsoObject

Introduced in R2017b

1 API Reference

1-70

matlabdataOptionalltTgtTemplated C++ class representing optional values

DescriptionUse Optional objects to represent values that might or might not exist

Class DetailsNamespace matlabdataInclude Optionalhpp

Template ParametersT Array type specified as matlabdataString

Constructorsbull ldquoDefault Constructorsrdquo on page 1-71bull ldquoCopy Constructorsrdquo on page 1-71bull ldquoCopy Assignment Operatorsrdquo on page 1-72bull ldquoMove Constructorsrdquo on page 1-72bull ldquoMove Assignment Operatorsrdquo on page 1-72

Default Constructors

optional()

Copy Constructors

optional(const optionalamp other)

matlabdataOptionalltTgt

1-71

Creates a shared data copy

const optionalamp other Value to copy

None

Copy Assignment OperatorsoptionalltTgtamp operator=(const optionalltTgtamp other)

Assigns a shared data copy

const optionalltTgtamp other Value to copy

optionalltTgtamp Updated instance

None

Move Constructorsoptional(optionalampamp other)

optional(Tampamp value)

Moves contents of an Optional object to a new instance

optionalampamp other Value to moveTampamp value Value of type T to move

None

Move Assignment OperatorsoptionalltTgtamp operator=(optionalltTgtampamp other)

1 API Reference

1-72

optionalltTgtamp operator=(Tampamp value)

Assigns the input to this instance

optionalltTgtampamp other

Tampamp value

Value to move

optionalltTgtamp Updated instance

None

Other Operatorsbull ldquooperator=rdquo on page 1-73bull ldquooperator-gtrdquo on page 1-74bull ldquooperatorrdquo on page 1-74bull ldquooperator Trdquo on page 1-74

operator=optionalltTgtamp operator=(nullopt_t)

optionalltTgtamp operator=(const optionalltTgtamp other)

optionalltTgtamp operator=(optionalltTgtampamp other)

optionalltTgtamp operator=(Tampamp value)

optionalltTgtamp operator=(const Tamp value)

Assignment operators

optionalltTgtamp Updated instance

None

matlabdataOptionalltTgt

1-73

operator-gtconst T operator-gt() const

T operator-gt()

const T

T

Pointer to the element

stdruntime_error Optional object does not contain a value

operatorconst Tamp operator() const

Tamp operator()

const Tamp

Tamp

Reference to the element

stdruntime_error Optional object does not contain a value

operator Toperator T() const

Cast optionalltTgt value to T

operator Value contained in optionalltTgt if it exists

stdruntime_error There is no value

1 API Reference

1-74

Member Functionsbull ldquoboolrdquo on page 1-75bull ldquohas_valuerdquo on page 1-75bull ldquoswaprdquo on page 1-75bull ldquoresetrdquo on page 1-76

boolexplicit operator bool() const

Check whether object contains a value

operator True if object contains a value

None

has_valuebool has_value() const

Check whether object contains a value

bool True if object contains a value

None

swapvoid swap(optional ampother)

Swap value of this optional instance with value contained in the parameter

optional ampother Value to swap

matlabdataOptionalltTgt

1-75

None

resetvoid reset()

Reset optional value to missing

None

See Also

Introduced in R2017b

1 API Reference

1-76

matlabdataRangeltItTypeElemTypegtTemplated C++ class to provide range-based operation support

DescriptionRange objects wrap begin and end functions to enable range-based operations

Class DetailsNamespace matlabdataInclude Rangehpp

Template ParametersIteratorType Iterator typeElementType Element type

Constructorsbull ldquoConstructorrdquo on page 1-77bull ldquoMove Constructorsrdquo on page 1-78bull ldquoMove Assignment Operatorsrdquo on page 1-78

Constructor

Range(IteratorTypeltElementTypegt begin IteratorTypeltElementTypegtend)

Creates a Range object

matlabdataRangeltItTypeElemTypegt

1-77

IteratorTypeltElementTypegt begin

IteratorTypeltElementTypegt end

First and last elements of range

Range New instance

None

Move Constructors

Range(Rangeampamp rhs)

Moves contents of a Range object to a new instance

Rangeampamp rhs Range to move

Range New instance

None

Move Assignment Operators

Rangeamp operator=(Rangeampamp rhs)

Assigns the input to this Range object

Rangeampamp rhs Range to move

Rangeamp Updated instance

None

1 API Reference

1-78

beginIteratorTypeltElementTypegtamp begin()

ReturnsIteratorTypeltElementTypegtamp

First element in range

None

endIteratorTypeltElementTypegtamp end()

ReturnsIteratorTypeltElementTypegtamp

End of range

None

See Also

Introduced in R2017b

matlabdataRangeltItTypeElemTypegt

1-79

matlabdataReferenceltTgtTemplated C++ class to get references to Array elements

DescriptionA Reference object is a reference to an element of an Array without making a copy AReference is

bull Not a shared copybull Valid as long as the array that contains the reference is validbull Not thread-safe

Class DetailsNamespace matlabdataInclude Referencehpp

Template ParametersT Type of element referred to specified as

bull Arraybull Structbull Enumerationbull MATLABStringbull All stdcomplex types

Constructorsbull ldquoCopy Constructorrdquo on page 1-81bull ldquoCopy Assignment Operatorsrdquo on page 1-81bull ldquoMove Assignment Operatorsrdquo on page 1-81

1 API Reference

1-80

bull ldquoMove Constructorsrdquo on page 1-81

Copy ConstructorReference(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

Copy Assignment OperatorsReferenceltTgtamp operator=(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

ReferenceltTgtamp Updated instance

Move Assignment OperatorsReferenceltTgtamp operator=(ReferenceltTgtampamp rhs)

ReferenceltTgtampamp rhs Value to move

ReferenceltTgtamp Updated instance

None

Move ConstructorsReference(ReferenceltTgtampamp rhs)

Moves contents of a Reference object to a new instance

ReferenceltTgtampamp rhs Value to move

None

matlabdataReferenceltTgt

1-81

Other Operatorsbull ldquooperator=rdquo on page 1-82bull ldquooperatorltltrdquo on page 1-82bull ldquooperator T()rdquo on page 1-83bull ldquooperator stdstring()rdquo on page 1-83

operator=ReferenceltTgtamp operator=(T rhs)

ReferenceltTgtamp operator=(stdstring rhs)

ReferenceltTgtamp operator=(String rhs)

T rhs Value to assign The array being indexed must be non-const

stdstring rhs String to assign The array must be non-const andallow strings to be assigned

String rhs String to assign to StringArray The array beingindexed must be non-const

ReferenceltTgtamp Updated instance

None

operatorltlt

stdostreamamp operator ltlt(stdostreamamp os ReferenceltTgt constamp rhs)

stdostreamamp os ReferenceltTgt constamp rhs

stdostreamamp

1 API Reference

1-82

operator T()operator T() const

Cast to element from the array

T Shared copy of element from the array

None

operator stdstring()operator stdstring() const

Cast to stdstring from the array Makes a copy of the stdstring Only valid fortypes that can be cast to a stdstring

stdstring The string

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

stdruntime_error MATLABString is missing

Free Functions

operator==inline bool operator ==(ReferenceltMATLABStringgt constamp lhsstdstring constamp rhs)

inline bool operator ==(stdstring constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhs Stringconstamp rhs)

matlabdataReferenceltTgt

1-83

inline bool operator ==(String constamp lhs ReferenceltMATLABStringgtconstamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsMATLABString constamp rhs)

inline bool operator ==(MATLABString constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsReferenceltMATLABStringgt constamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhs Tconstamp rhs)

templatelttypename Tgt bool operator ==(T constamp lhs ReferenceltTgtconstamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhsReferenceltTgt constamp rhs)

ReferenceltMATLABStringgtconstamp lhs

stdstring constamp rhs Values tocompare

stdstring constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

String constamp rhs

String constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

MATLABString constamp rhs

MATLABString constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

ReferenceltMATLABStringgtconstamp rhs

ReferenceltTgt constamp lhs T constamp rhsT constamp lhs ReferenceltTgt constamp rhsReferenceltTgt constamp lhs ReferenceltTgt constamp rhs

1 API Reference

1-84

bool Returns true if values are equal

stdruntime_error Cannot compare argument to MATLABString

See Also

TopicsldquoAccess C++ Data Array Container Elementsrdquo

Introduced in R2017b

matlabdataReferenceltTgt

1-85

matlabdataSparseArrayltTgtTemplated C++ class to access data in MATLAB sparse arrays

DescriptionUse SparseArray objects to work with sparse MATLAB arrays To create aSparseArray call createSparseArray

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude SparseArrayhpp

Template ParametersT Type of element referred to specified as

bull boolbull doublebull stdcomplexltdoublegt

Constructorsbull ldquoCopy Constructorsrdquo on page 1-86bull ldquoCopy Assignment Operatorsrdquo on page 1-87bull ldquoMove Constructorsrdquo on page 1-87bull ldquoMove Assignment Operatorsrdquo on page 1-88

Copy Constructors

SparseArray(const SparseArrayltTgtamp rhs)

1 API Reference

1-86

SparseArray(const Arrayamp rhs)

Creates a shared data copy of a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array ofArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Copy Assignment OperatorsSparseArrayamp operator=(const SparseArrayltTgtamp rhs)

SparseArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

Move ConstructorsSparseArray(SparseArrayampamp rhs)

matlabdataSparseArrayltTgt

1-87

SparseArray(Arrayampamp rhs)

Moves contents a SparseArray object to a new instance

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Move Assignment Operators

SparseArrayamp operator=(SparseArrayltTgtampamp rhs)

SparseArrayamp operator=(Arrayampamp rhs)

Assigns the input to this SparseArray object

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

1 API Reference

1-88

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-89bull ldquoEnd Iteratorsrdquo on page 1-89

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functionsbull ldquogetNumberOfNonZeroElementsrdquo on page 1-90

matlabdataSparseArrayltTgt

1-89

bull ldquogetIndexrdquo on page 1-90

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array

size_t Number of nonzero elements in the array

None

getIndexSparseIndex getIndex(const TypedIteratorltTgtamp it)

SparseIndex getIndex(const TypedIteratorltT constgtamp it)

Returns the row-column coordinates of the nonzero entry that the iterator is pointing to

const TypedIteratorltTgtampit

Iterator pointing to the current entry in the sparsematrix

const TypedIteratorltTconstgtamp it

SparseIndex Row-column coordinates of the nonzero entry that theiterator is pointing to SparseIndex is defined asstdpairltsize_t size_tgt

None

See AlsoArray | createSparseArray

1 API Reference

1-90

Introduced in R2017b

matlabdataSparseArrayltTgt

1-91

matlabdataReferenceltSparseArrayltTgtgtTemplated C++ class to get reference to SparseArray

DescriptionUse the ReferenceltSparseArraygt class to get a reference to a SparseArray elementof a container object such as a MATLAB structure or cell array

Class DetailsNamespace matlabdataInclude SparseArrayRefhpp

Template ParametersT Type of elements in SparseArray specified as bool

double or stdcomplexltdoublegt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-92bull ldquoEnd Interatorsrdquo on page 1-93

Begin Interatorsiterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array Iterates over non-zeroelements of the SparseArray

1 API Reference

1-92

None

End Interators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functions

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array Since sparse arrays only storenonzero elements this method returns the actual array size It is different from arraydimensions that specify the full array size

size_t Number of nonzero elements in the array

None

See Also

Introduced in R2017b

matlabdataReferenceltSparseArrayltTgtgt

1-93

matlabdataStringType representing strings as stdbasic_stringltchar16_tgt

DescriptionThe String class defines the element type of a StringArray String is defined as

using String = stdbasic_stringltchar16_tgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

1 API Reference

1-94

matlabdataStringArrayC++ class to access MATLAB string arrays

DescriptionUse StringArray objects to access MATLAB string arrays StringArray is defined as

using StringArray = TypedArrayltMATLABStringgt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

matlabdataStringArray

1-95

matlabdataStructArrayC++ class to access MATLAB struct arrays

DescriptionUse StructArray objects to work with MATLAB struct arrays To access a field for asingle element in the array use the field name To create a StructArray object callcreateStructArray

Class DetailsNamespace matlabdataBase class TypedArrayltStructgtInclude StructArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-96bull ldquoCopy Assignment Operatorsrdquo on page 1-97bull ldquoMove Constructorsrdquo on page 1-97bull ldquoMove Assignment Operatorsrdquo on page 1-98

Copy Constructors

StructArray(const StructArrayamp rhs)

StructArray(const Arrayamp rhs)

Creates a shared data copy of a StructArray object

const StructArrayamp rhs Value to copy

1 API Reference

1-96

const Arrayamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Copy Assignment Operators

StructArrayamp operator=(const StructArrayamp rhs)

StructArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a StructArray object

const StructArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeSTRUCT object

StructArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Move Constructors

StructArray(StructArrayampamp rhs)

StructArray(Arrayampamp rhs)

Moves contents of a StructArray object to a new instance

StructArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

matlabdataStructArray

1-97

Move Assignment OperatorsStructArrayamp operator=(StructArrayampamp rhs)

Assigns the input to this StructArray object

StructArrayampamp rhs Value to move

StructArrayamp Updated instance

None

Destructor~StructArray()

Description

Free memory for StructArray object

Member Functionsbull ldquogetFieldNamesrdquo on page 1-98bull ldquogetNumberOfFieldsrdquo on page 1-99

getFieldNamesRangeltForwardIterator MatlabFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enable access to allfields in StructArray object

None

1 API Reference

1-98

getNumberOfFieldssize_t getNumberOfFields() const

size_t Number of fields

None

ExamplesCreate StructArray

Suppose that you have the following MATLAB structure

s = struct(loc east west data [1 2 3] [4 5 6 7 8])

Create a variable containing the data for loc east

val = s(1)data

The following C++ code creates these variables

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory

StructArray S = factorycreateStructArray( 12 loc data ) S[0][loc] = factorycreateCharArray(east) S[0][data] = factorycreateArrayltuint8_tgt( 1 3 1 2 3 ) S[1][loc] = factorycreateCharArray(west) S[1][data] = factorycreateArrayltdoublegt( 1 5 4 5 6 7 8 )

ReferenceltArraygt val = S[0][data] return 0

bull ldquoCreate Structure Array and Send to MATLABrdquo

matlabdataStructArray

1-99

See AlsoMATLABFieldIdentifier | Range | createStructArray

TopicsldquoCreate Structure Array and Send to MATLABrdquo

Introduced in R2017b

1 API Reference

1-100

matlabdataReferenceltStructArraygtC++ class to get reference to StructArray

DescriptionThe StructArrayExt class extends the APIs available to a reference to a StructArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquogetFieldNamesrdquo on page 1-101bull ldquogetNumberOfFieldsrdquo on page 1-101

getFieldNamesRangeltForwardIterator MATLABFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enables access to allfields in StructArray object

None

getNumberOfFieldssize_t getNumberOfFields() const

matlabdataReferenceltStructArraygt

1-101

size_t Number of fields

None

See AlsoReferenceltTypedArrayltTgtgt | StructArray

Introduced in R2017b

1 API Reference

1-102

matlabdataStructElement type for MATLAB struct arrays

DescriptionStruct is the element type for a StructArray object

Class DetailsNamespace matlabdataInclude Structhpp

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-103bull ldquoEnd Iteratorsrdquo on page 1-103

Begin Iteratorsconst_iterator begin() const

const_iterator cbegin() const

const_iterator Iterator to beginning of list of fields specified asTypedIteratorltArray constgt

None

End Iteratorsconst_iterator end() const

const_iterator cend() const

matlabdataStruct

1-103

const_iterator Iterator to end of list of fields specified asTypedIteratorltArray constgt

None

Indexing Operators

operator[]Array operator[](stdstring idx) const

Enables [] indexing on a StructArray object Indexing is 0-based

stdstring idx Field name

Array Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in this StructArray

See AlsoldquocreateStructArrayrdquo on page 1-17 | StructArray

Introduced in R2017b

1 API Reference

1-104

matlabdataReferenceltStructgtC++ class to get reference to element of StructArray

DescriptionUse the ReferenceltStructgt class to access an element of a StructArray

Class DetailsNamespace matlabdataInclude StructRefhpp

Indexing Operators

operator[]ReferenceltArraygt operator[](stdstring idx)

Array operator[](stdstring idx) const

Index into the Struct with a field name

stdstring idx Field name

ReferenceltArraygt Reference to Array found at specified fieldArray Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in the struct

matlabdataReferenceltStructgt

1-105

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-106bull ldquoEnd Iteratorsrdquo on page 1-106

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

1 API Reference

1-106

Cast

Struct()operator Struct() const

Create a shared copy of the Struct

Struct Shared copy

None

See Also

Introduced in R2017b

matlabdataReferenceltStructgt

1-107

matlabdataTypedArrayltTgtTemplated C++ class to access array data

DescriptionThe templated TypedArray class provides typesafe APIs to handle all array types(except sparse arrays) inside an array This class defines the following iterator types

using iterator = TypedIteratorltTgt

using const_iterator = TypedIteratorltT constgt

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude TypedArrayhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_t

1 API Reference

1-108

uint64_tchar16_tboolstdcomplexltdoublegtstdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorrdquo on page 1-109bull ldquoCopy Assignment Operatorrdquo on page 1-110bull ldquoMove Constructorrdquo on page 1-110bull ldquoMove Assignment Operatorrdquo on page 1-111

Copy ConstructorTypedArray(const TypedArrayltTgtamp rhs)

TypedArray(const Arrayamp rhs)

Creates a shared data copy of the input

matlabdataTypedArrayltTgt

1-109

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Copy Assignment Operator

TypedArrayltTgtamp operator=(const TypedArrayltTgtamp rhs)

TypedArrayltTgtamp operator=(const Arrayamp rhs)

Assigns a shared data copy of the input to this TypedArrayltTgt

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Move Constructor

TypedArray(TypedArrayltTgtampamp rhs)

TypedArray(Arrayampamp rhs)

Moves contents of the input to a new instance

TypedArrayltTgtampamp rhs Value to be movedArrayampamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input does not match

1 API Reference

1-110

Move Assignment Operator

TypedArrayltTgtamp operator=(TypedArrayltTgtampamp rhs)

TypedArrayltTgtamp operator=(Arrayampamp rhs)

Moves the input to this TypedArrayltTgt object

TypedArrayltTgtampamp rhs Value to move

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Destructorvirtual ~TypedArray()

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-111bull ldquoEnd Iteratorsrdquo on page 1-112

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

matlabdataTypedArrayltTgt

1-111

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

Indexing Operators

operator[]ArrayElementTypedRefltT stdis_constltTgtvaluegt operator[](size_tidx)

ArrayElementTypedRefltT truegt operator[](size_t idx) const

Enables [] indexing on a TypedArray Indexing is 0-based

size_t idx First array index

1 API Reference

1-112

ArrayElementTypedRefltTstdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltTtruegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Suppose that you have a cell array c Assign a value to a ReferenceltArraygt object andcall the member function getType

ReferenceltArraygt r = c[0][0]auto t = c[0][0]getType

Member Functions

releasebuffer_ptr_tltTgt release()

Release the underlying buffer from the Array If the Array is shared a copy of the bufferis made otherwise no copy is made After the buffer is released the array contains noelements

buffer_ptr_tltTgt A unique_ptr with the data pointer

InvalidArrayTypeException

This TypedArray does not support releasing the buffer

matlabdataTypedArrayltTgt

1-113

ExamplesAssign Values to Array Elements

Create an array equivalent to the MATLAB array [1 2 3 4] then replace eachelement of the array with a single value

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory Create an array equivalent to the MATLAB array [1 2 3 4] matlabdataTypedArrayltdoublegt D = factorycreateArrayltdoublegt( 22 1324 ) Change the values for (autoamp elem D) elem = 55 return 0

bull ldquoBring Result of MATLAB Calculation Into C++rdquo

See AlsoArray | ArrayType

TopicsldquoBring Result of MATLAB Calculation Into C++rdquo

Introduced in R2017b

1 API Reference

1-114

matlabdataReferenceltTypedArrayltTgtgtC++ class to get reference to TypedArray

DescriptionThe ReferenceltTypedArrayltTgtgt class extends the APIs available to a reference to anArray It derives from the ReferenceltArraygt class and provides iterators and type-safe indexing ReferenceltTypedArrayltTgtgt is not thread-safe - do not pass referencesto TypedArray objects between threads

TypedArrayRef is defined in TypedArrayRefhpp as

template lttypename Tgtusing TypedArrayRef = ReferenceltTypedArrayltTgtgt

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

ConstructorReference(const ReferenceltArraygtamp rhs)

Description

Create a ReferenceltTypedArrayltTgtgt object from a ReferenceltArraygt object

Parametersconst ReferenceltArraygtamprhs

Value to copy

matlabdataReferenceltTypedArrayltTgtgt

1-115

ThrowsTypeMismatchException Element of Array does not match ltTgt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-116bull ldquoEnd Iteratorsrdquo on page 1-116

Begin Interators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

1 API Reference

1-116

None

Indexing Operators

operator[]ArrayElementTypedRefltarr_elem_type stdis_constltTgtvaluegtoperator[](size_t idx)

ArrayElementTypedRefltarr_elem_type truegt operator[](size_t idx)const

Enables [] indexing on a reference to an Array Indexing is 0-based

size_t idx First array index

ArrayElementTypedRefltarr_elem_typestdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltarr_elem_type truegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

InvalidFieldNameException

Field name is invalid for a struct

Other Operators

operator=ReferenceltTypedArrayltTgtgtamp operator= (TypedArrayltTgt rhs)

matlabdataReferenceltTypedArrayltTgtgt

1-117

Assign a TypedArray to an element of the referenced Array The Array being indexedmust be non-const

TypedArrayltTgt rhs Value to assign

ReferenceltTypedArrayltTgtgtamp

Updated instance

None

See Also

Introduced in R2017b

1 API Reference

1-118

matlabdataTypedIteratorltTgtTemplated C++ class to provide random access iterator

DescriptionTypedIterator is the return type of all begin and end functions that support randomaccess

Class DetailsNamespace matlabdataInclude TypedIteratorhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tchar16_tboolstdcomplexltdoublegt

matlabdataTypedIteratorltTgt

1-119

stdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorsrdquo on page 1-120bull ldquoCopy Assignment Operatorsrdquo on page 1-121bull ldquoMove Constructorsrdquo on page 1-121bull ldquoMove Assignment Operatorsrdquo on page 1-121

Copy Constructors

TypedIterator(const TypedIteratorltTgtamp rhs)

Creates a shared data copy of a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

None

1 API Reference

1-120

Copy Assignment OperatorsTypedIteratorltTgtamp operator=(const TypedIteratorltTgtamp rhs)

Assigns a shared data copy to a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

TypedIteratorltTgtamp Updated instance

None

Move ConstructorsTypedIterator(TypedIteratorltTgt ampamprhs)

Moves contents of a TypedIterator object to a new instance

TypedIteratorltTgtampamp rhs Value to move

None

Move Assignment OperatorsTypedIteratorltTgtamp operator=(TypedIteratorltTgtampamp rhs)

Assigns the input to this TypedIterator object

TypedIteratorltTgtampamp rhs Value to move

TypedIteratorltTgtamp Updated instance

None

matlabdataTypedIteratorltTgt

1-121

Other Operatorsbull ldquooperator++rdquo on page 1-122bull ldquooperator--rdquo on page 1-122bull ldquooperator++rdquo on page 1-123bull ldquooperator--rdquo on page 1-123bull ldquooperator+=rdquo on page 1-123bull ldquooperator-=rdquo on page 1-124bull ldquooperator=rdquo on page 1-124bull ldquooperatorltrdquo on page 1-124bull ldquooperatorgtrdquo on page 1-125bull ldquooperatorlt=rdquo on page 1-125bull ldquooperatorgt=rdquo on page 1-125bull ldquooperator+rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperatorrdquo on page 1-127bull ldquooperator-gtrdquo on page 1-127bull ldquooperator[]rdquo on page 1-127

operator++TypedIteratorltTgtamp operator++()

Pre-increment operator

TypedIteratorltTgtamp Original iterator

None

operator--TypedIteratorltTgtamp operator--()

1 API Reference

1-122

Pre-decrement operator

TypedIteratorltTgtamp Original iterator

None

operator++TypedIteratorltTgt operator++(int)

Post-increment operator

TypedIteratorltTgt Copy of original iterator

None

operator--TypedIteratorltTgt operator--(int)

Post-decrement operator

TypedIteratorltTgt Copy of original iterator

None

operator+=TypedIteratorltTgtamp operator+=(difference_type d)

Addition assignment operator

difference_type d Amount to add specified as stdptrdiff_t

matlabdataTypedIteratorltTgt

1-123

TypedIteratorltTgtamp Updated instance

None

operator-=TypedIteratorltTgtamp operator-=(difference_type d)

Subtraction assignment operator

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgtamp Updated instance

None

operator=bool operator=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if iterators do not point to same element

None

operatorltbool operatorlt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

1 API Reference

1-124

bool Returns true if left-side iterator is less than right-sideiterator

operatorgtbool operatorgt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than right-side iterator

operatorlt=bool operatorlt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is less than or equal toright-side iterator

None

operatorgt=bool operatorgt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than orequal to right-side iterator

None

matlabdataTypedIteratorltTgt

1-125

operator+TypedIteratorltTgt operator+(difference_type d) const

Creates an iterator that is added to this one by the amount passed in

difference_type d Amount to add specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-TypedIteratorltTgt operator-(difference_type d) const

Creates an iterator that is decremented from this one by the amount passed in

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-difference_type operator-(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

difference_type Difference between iterators specified asstdptrdiff_t

None

1 API Reference

1-126

operatorreference operator() const

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataTypedIteratorltTgt

1-127

Free Function

operator==bool operator==(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if both iterators point to same element

None

See Also

Introduced in R2017b

1 API Reference

1-128

matlabdataapply_visitorCall Visitor class on arrays

Descriptionauto apply_visitor(Array a V visitor) dispatch to visitor class operationsbased on array type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersmatlabdataArray a

The matlabdataArray to operate on with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

matlabdataapply_visitor

1-129

matlabdataapply_visitor_refCall Visitor class on array references

Descriptionauto apply_visitor_ref(const ArrayRefamp a V visitor) dispatch to visitorclass operations based on array reference type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersconstmatlabdataArrayRefamp a

A matlabdataArrayRef reference to the array to operateon with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

1 API Reference

1-130

matlabengineMATLABEngineEvaluate MATLAB functions from C++ program

DescriptionThe matlabengineMATLABEngine class uses a MATLAB process as acomputational engine for C++ This class provides an interface between the C++language and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom C++ programs

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Factory MethodsThe matlabengineMATLABEngine class provides methods to start MATLAB and toconnect to a shared MATLAB session synchronously or asynchronously

bull matlabenginestartMATLAB mdash Start MATLAB synchronouslybull matlabenginestartMATLABAsync mdash Start MATLAB asynchronouslybull matlabengineconnectMATLAB mdash Connect to shared MATLAB session

synchronouslybull matlabengineconnectMATLABAsync mdash Connect to shared MATLAB session

asynchronously

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -h

matlabengineMATLABEngine

1-131

bull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup OptionsrdquoFor an example of how to use MATLAB startup options when starting engineapplications see ldquoStart MATLAB with Startup Optionsrdquo

Method Summary

Member Functionsldquofevalrdquo on page 1-133

Evaluate MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-136

Evaluate MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-138 Evaluate MATLAB statement as a string synchronouslyldquoevalAsyncrdquo on page1-139

Evaluate MATLAB statement as a string asynchronously

ldquogetVariablerdquo onpage 1-140

Get variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-141

Get variable from the MATLAB base workspace asynchronously

ldquosetVariablerdquo onpage 1-142

Put variable into the MATLAB base workspace synchronously

ldquosetVariableAsyncrdquoon page 1-142

Put variable into the MATLAB base workspace asynchronously

ldquogetPropertyrdquo onpage 1-143

Get object property value

ldquogetPropertyAsyncrdquoon page 1-144

Get object property value asynchronously

1 API Reference

1-132

ldquosetPropertyrdquo onpage 1-145

Set object property value

ldquosetPropertyAsyncrdquoon page 1-146

Set object property value asynchronously

Member Function Details

fevalstdvectorltmatlabdataArraygt feval(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

ResultType feval(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs )

ResultType feval(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB functions with input arguments synchronously Use feval when youwant to pass arguments from C++ to MATLAB and when you want to return a resultfrom MATLAB to C++

Inputs and outputs can be types defined by the MATLAB Data Array API or can benative C++ types

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

matlabengineMATLABEngine

1-133

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

stdvectorltmatlabdataArraygt

Outputs returned from MATLAB function

matlabdataArray Single output returned from MATLAB functionResultType Output returned from MATLAB function as a user-specified

type Can be a stdtuple if returning multiple arguments

matlabengineMATLABNotAvailableException

The MATLAB session is not available

1 API Reference

1-134

matlabengineMATLABExecutionException

There is a MATLAB runtime error in the function

matlabengineTypeConversionException

The result of a MATLAB function cannot be converted tothe specified type

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

This example passes an array of numeric values to a MATLAB function The codeperforms these steps

bull Creates a matlabdataArray with the dimensions 2-by-3 from a vector ofnumeric values of type double

bull Starts a shared MATLAB sessionbull Passes the data array to the MATLAB sqrt function and returns the result to C++

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabengine

stdvectorltdoublegt cppData 4 8 12 16 20 24

Create a 2-by-3 matlab data array matlabdataArrayFactory factory auto inputArray = factorycreateArray( 2 3 cppDatacbegin() cppDatacend())

Start MATLAB engine stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Pass data array to MATLAB sqrt function And return results auto result = matlabPtr-gtfeval(usqrt inputArray)

When calling feval using native C++ types the input arguments are restricted to scalarvalues For example this code returns the square root of a scalar value

include MatlabEnginehppusing namespace matlabengine

Start MATLAB engine synchronously stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Call sqrt function double result = matlabPtr-gt fevalltdoublegt(usqrt double(27))

matlabengineMATLABEngine

1-135

For functions that return multiple output arguments you can use the MATLAB data APIor if using C++ types a stdtuple For an example see ldquoCall Function with Native C++ Typesrdquo

ldquoCall MATLAB Functions from C++rdquo

ldquoMATLAB Data APIrdquo

fevalAsyncFutureResultltstdvectorltmatlabdataArraygtgt fevalAsync(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt amp output = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amp error = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs)

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB function with input arguments and returned values asynchronously

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

1 API Reference

1-136

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

FutureResult A FutureResult object used to get the result of calling theMATLAB function

None

This example passes the scalar double 127 to the MATLAB sqrt functionasynchronously The FutureResult is then used to get the result

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() matlabdataArrayFactory factory matlabdataArray argument = factorycreateScalarltdoublegt(127) FutureResultltmatlabdataArraygt future = matlabPtr-gt fevalAsync(convertUTF8StringToUTF16String(sqrt) stdmove(argument))

matlabengineMATLABEngine

1-137

matlabdataTypedArrayltdoublegt result = futureget()

ldquoCall Function Asynchronouslyrdquo

evalvoid eval(const matlabengineString ampstatement const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string synchronously

constmatlabengineString ampstatement

MATLAB statement to evaluate

conststdshared_ptrltmatlabengineStreamBuffergtampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergtamperror

Stream buffer used to store the error message from theMATLAB command

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

There is a runtime error in the MATLAB statement

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB statement

This example evaluates the following MATLAB statement

a = sqrt(127)

1 API Reference

1-138

The statement creates the variable a in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

evalAsyncFutureResultltvoidgt evalAsync(const matlabengineString ampstr const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string asynchronously

const Stringamp str MATLAB statement to evaluateconststdshared_ptrltmatlabengineStreamBuffergt ampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergt amperror

Stream buffer used to store the error message from theMATLAB command

FutureResult A FutureResult object used to wait for the completion of theMATLAB statement

None

This example evaluates the following MATLAB statement asynchronouslya = sqrt(127)

The statement creates the variable a in the MATLAB base workspace

matlabengineMATLABEngine

1-139

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltvoidgt future = matlabPtr-gt evalAsync(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

getVariablematlabdataArray getVariable(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace

constmatlabengineStringamp varName

Name of a variable in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variablefrom For more information see global

matlabdataArray

Variable obtained from the MATLAB base or global workspace

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The requested variable does not exist in the specifiedMATLAB base or global workspace

This example gets a variable named varName from the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray varName = matlabPtr-gtgetVariable(convertUTF8StringToUTF16String(varName))

1 API Reference

1-140

ldquoPass Variables from MATLAB to C++rdquo

getVariableAsyncFutureResultltmatlabdataArraygt getVariableAsync(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace asynchronously

constmatlabengineStringamp varName

Name of the variable in MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variable fromFor more information see global

FutureResult A FutureResult object that you can use to get the variableobtained from the MATLAB workspace as amatlabdataArray

None

This example gets a variable named varName from the MATLAB base workspaceasynchronously

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltmatlabdataArraygt future = matlabPtr-gt getVariableAsync(convertUTF8StringToUTF16String(varName))matlabdataArray varName = futureget()

ldquoPass Variables from MATLAB to C++rdquo

matlabengineMATLABEngine

1-141

setVariablevoid setVariable(const matlabengineString ampvarName const matlabdataArray ampvar WorkspaceType workspaceType = WorkspaceTypeBASE)

Put a variable into the MATLAB base or global workspace If a variable with the samename exists in the MATLAB workspace setVariable overwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

matlabengineMATLABNotAvailableException

The MATLAB session is not available

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from C++ to MATLABrdquo

setVariableAsyncFutureResultltvoidgt setVariableAsync(const matlabengineString ampvarName const matlabdataArray var WorkspaceType workspaceType = WorkspaceTypeBASE)

1 API Reference

1-142

Put a variable into the MATLAB base or global workspace asynchronously If a variablewith the same name exists in the MATLAB base workspace setVariableAsyncoverwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

None

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )FutureResultltvoidgt future = matlabPtr-gt setVariableAsync(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from MATLAB to C++rdquo

getPropertymatlabdataArray getProperty(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property

matlabengineMATLABEngine

1-143

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

matlabdataArray

Value of the named property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetProperty returns the exception messageproperty value as a matlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(try surf(4) catch me end))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))matlabdataCharArray message = matlabPtr-gt getProperty(mException convertUTF8StringToUTF16String(message))stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

getPropertyAsyncFutureResultltmatlabdataArraygt getPropertyAsync(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property asynchronously

1 API Reference

1-144

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

FutureResult FutureResult object that is used to synchronize the operation

None

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetPropertyAsync returns a FutureResultthat you use to get the exception message property value as amatlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(trysurf(4)catch meend))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))FutureResultltmatlabdataArraygt future = matlabPtr-gt getPropertyAsync(mException convertUTF8StringToUTF16String(message))matlabdataCharArray message = futureget()stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

setPropertyvoid setProperty(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property

matlabdataArray ampobject

MATLAB object

matlabengineMATLABEngine

1-145

const StringamppropertyName

Name of the property to set

constmatlabdataArray amppropertyValue

Value assigned to the property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example shows how to set a MATLAB object property It creates a MATLAB graphand returns the line handle object Setting the value of the line LineStyle property tothe character changes the property value of the line object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray()matlabPtr-gtsetProperty(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

setPropertyAsyncFutureResultltvoidgt setPropertyAsync(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property asynchronously

matlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property to set

1 API Reference

1-146

constmatlabdataArray amppropertyValue

Value assigned to the property

None

This example shows how to set a MATLAB object property asynchronously It creates aMATLAB graph and returns the line handle object Setting the line LineStyle propertyto the character changes the property value of the object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray() FutureResultltvoidgt future = matlabPtr-gt setPropertyAsync(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

See Also

Introduced in R2017b

matlabengineMATLABEngine

1-147

matlabengineconnectMATLABConnect to shared MATLAB session synchronously

Descriptionstdunique_ptrltMATLABEnginegt connectMATLAB()

stdunique_ptrltMATLABEnginegt connectMATLAB(constmatlabengineStringamp name)

Connect synchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-148

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to a MATLABEngine object

ExceptionsmatlabengineEngineException

Throws exception if function fails to connect to the specified MATLABsession

Examples

Connect to Shared MATLAB Session

Connect to a shared MATLAB session named my_matlab

stdunique_ptrltMATLABEnginegt matlabPrt = connectMATLAB(convertUTF8StringToUTF16String(my_matlab))

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineconnectMatlabAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

matlabengineconnectMATLAB

1-149

matlabengineconnectMATLABAsyncConnect to shared MATLAB session asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync()

FutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync(constmatlabengineStringamp name)

Connect asynchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-150

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object that you can use to get the pointer to theMATLABEngine

Examples

Connect to Shared MATLAB Session Asynchronously

Connect to a shared MATLAB session named my_matlab asynchronously Use theFutureResult get method to retrieve the pointer to the MATLABEngine objectFutureResultsltstdunique_ptrltMATLABEnginegtgt future = connectMATLABAsync(convertUTF8StringToUTF16String(my_matlab))stdunique_ptrltMATLABEnginegt matlabPtr = futureget()

bull ldquoConnect C++ to Running MATLAB Sessionrdquo

See AlsomatlabengineconnectMatlab

TopicsldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

matlabengineconnectMATLABAsync

1-151

matlabengineconvertUTF8StringToUTF16StringConvert UTF-8 string to UTF-16 string

Descriptionstdbasic_stringltchar16_tgt convertUTF8StringToUTF16String(conststdstringamp utf8string)

Convert a UTF-8 string to a UTF-16 string Use this function to convert ASCII strings tomatlabengineString strings which are required by MATLAB C++ Enginefunctions

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdstringamputf8string

A UTF-8 string

Return Valuestdbasic_stringltchar16_tgt

A UTF-16 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-152

matlabengineTypeConversionException

The input type cannot be converted tostdbasic_stringltchar16_tgt

Examples

Convert String

Convert a UTF-8 string to a matlabengineString (UTF-16 string)

matlabengineString matlabStatement = convertUTF8StringToUTF16String(sqrt(127))

See AlsomatlabengineString |matlabengineconvertUTF16StringToUTF8String

Introduced in R2017b

matlabengineconvertUTF8StringToUTF16String

1-153

matlabengineconvertUTF16StringToUTF8StringConvert UTF-16 string to UTF-8 string

Descriptionstdstring convertUTF16StringToUTF8String(conststdbasic_stringltchar16_tgtamp utf16string)

Convert a UTF-16 string to a UTF-8 string

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdbasic_stringltchar16_tgtamputf16string

A UTF-16 string

Return Valuestdstring A UTF-8 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-154

matlabengineTypeConversionException

The input type cannot be converted to stdstring

Examples

Convert String

Convert a matlabengineString (UTF-16 string) to a stdstring (UTF-8string)

matlabengineString matlabStatement = (usqrt(127))stdstring cmdString = convertUTF16StringToUTF8String(matlabStatement)

See AlsomatlabengineString |matlabengineconvertUTF8StringToUTF16String

Introduced in R2017b

matlabengineconvertUTF16StringToUTF8String

1-155

matlabenginefindMATLABFind shared MATLAB sessions synchronously

DescriptionstdvectorltStringgt findMATLAB()

Find all shared MATLAB sessions on the local machine

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValuestdvectorltStringgt

A vector of the names of all shared MATLAB sessions on the localmachine or an empty vector if no shared MATLAB sessions areavailable

ExceptionsmatlabengineEngineException

Throws exception if the call fails while searching for shared MATLABsessions

Examples

1 API Reference

1-156

Find Shared MATLAB Session Synchronously

stdvectorltStringgt names = findMATLAB()

See AlsomatlabenginefindMATLABAsync

Introduced in R2017b

matlabenginefindMATLAB

1-157

matlabenginefindMATLABAsyncFind shared MATLAB sessions asynchronously

DescriptionFutureResultltstdvectorltStringgtgt findMATLABAsync()

Find all shared MATLAB sessions on the local machine asynchronously

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValueFutureResultltstdvectorltStringgtgt

A FutureResult object that you can use to get the names of sharedMATLAB sessions on the local machine

Examples

Find Shared MATLAB Session Asynchronously

Find the names of all shared MATLAB sessions on the local machine asynchronouslyUse the FutureResult get method to retrieve the names

1 API Reference

1-158

FutureResultltstdvectorltStringgtgt futureNames = findMATLABAsync()stdvectorltStringgt matlabSessions = futureNamesget()

See AlsomatlabenginefindMATLAB

Introduced in R2017b

matlabenginefindMATLABAsync

1-159

matlabengineFutureResultRetrieve result from asynchronous operation

DescriptionA future result is an object that you can use to retrieve the result of MATLAB functionsor statements The FutureResult class provides all member functions of the C++stdfuture class

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Functions Delegated to stdfutureoperator= share get wait wait_for wait_until

1 API Reference

1-160

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement You cannot cancelasynchronous operations that use matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution had already begun

bool Was command canceled if execution had already begun

bool flag = futurecancel()

No exceptions thrown

matlabengineFutureResult

1-161

See Also

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

1 API Reference

1-162

matlabenginestartMATLABStart MATLAB synchronously

Descriptionstdunique_ptrltMATLABEnginegt startMATLAB(const stdvectorltStringgtampoptions = stdvectorltStringgt())

Start MATLAB synchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtampoptions

Options used to start MATLAB See ldquoSpecify Startup Optionsrdquo

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to the MATLABEngine object

matlabenginestartMATLAB

1-163

ExceptionsmatlabengineEngineException

MATLAB failed to start

Examples

Start MATLAB Synchronously

Start MATLAB synchronously and return a unique pointer to the MATLABEngine object

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Start MATLAB with Startup Options

Start MATLAB with the -nojvm option and return a unique pointer to theMATLABEngine object

stdvectorltStringgt optionVecoptionVecpush_back(convertUTF8StringToUTF16String(-nojvm))stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB(optionVec)

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineMATLABEngine | matlabenginestartMATLABAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

1 API Reference

1-164

matlabenginestartMATLABAsyncStart MATLAB asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt startMATLABAsync(conststdvectorltStringgtamp options = stdvectorltStringgt())

Start MATLAB asynchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtamp options

Startup options used to launch MATLAB

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object used to get the pointer to theMATLABEngine

Examples

matlabenginestartMATLABAsync

1-165

Start MATLAB Asynchronously

Start MATLAB asynchronously and return a FutureResult object Use theFutureResult to get a pointer to the MATLABEngine objectFutureResultltstdunique_ptrltMATLABEnginegtgt matlabFuture = startMATLAB()stdunique_ptrltMATLABEnginegt matlabPtr = matlabFutureget()

bull ldquoSpecify Startup Optionsrdquo

See AlsomatlabenginestartMATLAB

TopicsldquoSpecify Startup Optionsrdquo

Introduced in R2017b

1 API Reference

1-166

matlabengineterminateEngineClientFree engine resources during runtime

Descriptionvoid matlabengineterminateEngineClient releases all MATLAB engineresources during runtime when you no longer need the MATLAB engine in yourapplication program

Note Programs cannot start a new MATLAB engine or connect to a shared MATLABsession after calling terminateEngineClient

IncludeNamespace matlabengineInclude MatlabEnginehpp

ExamplesTerminate the engine session to free resources Start MATLAB sessionstdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Terminate MATLAB sessionmatlabengineterminateEngineClient()

See AlsomatlabenginestartMATLAB

Introduced in R2017b

matlabengineterminateEngineClient

1-167

matlabengineWorkspaceTypeType of MATLAB workspace

DescriptionThe matlabengineWorkspaceType enum class specifies the MATLAB workspaceto pass variables to or get variables fromBASE Variables scoped to the MATLAB base workspace

(command line and nonfunction scripts)GLOBAL Variables scoped to the MATLAB global workspace

(command line functions and scripts)

MATLAB scopes variables by workspace Variables that are scoped to the baseworkspace must be passed to functions as arguments Variables scoped to the globalworkspace can be accessed by any function that defines the specific variable name asglobal

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

ExamplesThis example

bull Connects to a shared MATLAB sessionbull Creates a matlabdataArray containing numeric values of type doublebull Puts the array in the MATLAB global workspaceinclude MatlabDataArrayhppinclude MatlabEnginehppinclude ltiostreamgt

static void putGlobalVar()

1 API Reference

1-168

using namespace matlabengine

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

Create matlab data array factory matlabdataArrayFactory factory

Create data variable matlabdataArray data = factorycreateArrayltdoublegt ( 1 5 40 110 47 362 723 )

Put data variable in MATLAB global workspace matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data WorkspaceTypeGLOBAL)

See AlsomatlabdataArrayFactory | matlabengineMATLABEngine |matlabengineconvertUTF8StringToUTF16String

TopicsldquoPass Variables from C++ to MATLABrdquoldquoPass Variables from MATLAB to C++rdquo

Introduced in R2017b

matlabengineWorkspaceType

1-169

matlabengineStringDefine UTF16 string

DescriptionType definition for stdbasic_stringltchar16_tgt

ExamplesThis example defines a variable containing the name of a shared MATLAB session Passthis string to the matlabengineconnectMATLAB function to connect to the namedsessionmatlabengineString session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

See AlsomatlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoMATLAB Engine API for C++rdquoldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

1 API Reference

1-170

matlabengineStreamBufferDefine stream buffer

DescriptionType definition for stdbasic_streafbufltchar16_tgt

ExamplesThis example defines string buffers to return output from the evaluation of a MATLABfunction by the MATLABEngineeval member function This function uses a bufferderived from matlabengineStreamBuffer to return output from MATLAB to C++include MatlabEnginehppinclude MatlabDataArrayhppinclude ltiostreamgt

using namespace matlabengineusing SBuf = stdbasic_stringbufltchar16_tgt

void printFromBuf(const stdshared_ptrltSBufgt buf) Get text from buf auto text_ = buf-gtstr() stdcout ltlt ltlt convertUTF16StringToUTF8String(text_) ltlt ltlt stdendl

int main()

Create Array factory matlabdataArrayFactory factory

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

auto outBuf = stdmake_sharedltSBufgt() auto errBuf = stdmake_sharedltSBufgt()

matlabPtr-gteval(convertUTF8StringToUTF16String(matlabengineengineName) outBuf errBuf) printFromBuf(outBuf) printFromBuf(errBuf) return 0

matlabengineStreamBuffer

1-171

See AlsomatlabengineconnectMATLAB |matlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoRedirect MATLAB Command Window Output to C++rdquo

Introduced in R2017b

1 API Reference

1-172

matlabengineSharedFutureResultRetrieve result from asynchronous operation as shared future

DescriptionA shared future result is an object that you use to retrieve the result of MATLABfunctions or statements any number of times

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using one of these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Function Delegated to stdshared_futureoperator= get valid wait wait_for wait_until

matlabengineSharedFutureResult

1-173

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement

Note that you cannot cancel asynchronous start connection or find operations which areinitiated using these functions matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution has already begun

bool True if the MATLAB command can be canceled

bool flag = futurecancel()

None

1 API Reference

1-174

See AlsomatlabengineFutureResult

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

matlabengineSharedFutureResult

1-175

commathworksengineMatlabEngine classPackage commathworksengine

Java class using MATLAB as a computational engine

DescriptionThe commathworksengineMatlabEngine class uses a MATLAB process as acomputational engine for Javareg This class provides an interface between the Javalanguage and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom Java

Constructor SummaryThe MatlabEngine class provides static methods to start MATLAB and to connect to ashared MATLAB session synchronously or asynchronously Only these static methodscan instantiate this class

bull Start MATLAB synchronously mdash ldquostartMatlabrdquo on page 1-178bull Connect to shared MATLAB session synchronously mdash ldquoconnectMatlabrdquo on page 1-180bull Start MATLAB asynchronously mdash ldquostartMatlabAsyncrdquo on page 1-179bull Connect to shared MATLAB session asynchronously mdash ldquoconnectMatlabAsyncrdquo on

page 1-181

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -n

1 API Reference

1-176

bull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup Optionsrdquo

Method Summary

Static MethodsldquostartMatlabrdquo onpage 1-178

Start MATLAB synchronously

ldquostartMatlabAsyncrdquoon page 1-179

Start MATLAB asynchronously

ldquofindMatlabrdquo onpage 1-179

Find all available shared MATLAB sessions from a local machinesynchronously

ldquofindMatlabAsyncrdquoon page 1-180

Find all available shared MATLAB sessions from a local machineasynchronously

ldquoconnectMatlabrdquo onpage 1-180

Connect to a shared MATLAB session on a local machinesynchronously

ldquoconnectMatlabAsyncrdquo on page 1-181

Connect to a shared MATLAB session on a local machineasynchronously

Member VariableNULL_WRITER Use a writer that ignores the contents from the MATLAB

command window

Member Functionsldquofevalrdquo on page 1-182

Evaluate a MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-183

Evaluate a MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-184 Evaluate a MATLAB expression as a string synchronously

commathworksengineMatlabEngine class

1-177

ldquoevalAsyncrdquo on page1-185

Evaluate a MATLAB expression as a string asynchronously

ldquogetVariablerdquo onpage 1-186

Get a variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-187

Get a variable from the MATLAB base workspace asynchronously

ldquoputVariablerdquo onpage 1-187

Put a variable into the MATLAB base workspace synchronously

ldquoputVariableAsyncrdquoon page 1-188

Put a variable into the MATLAB base workspace asynchronously

ldquodisconnectrdquo on page1-188

Disconnect from the current MATLAB session synchronously

ldquodisconnectAsyncrdquoon page 1-189

Disconnect from the current MATLAB session asynchronously

ldquoquitrdquo on page 1-189 Force the shutdown of the current MATLAB sessionsynchronously

ldquoquitAsyncrdquo on page1-189

Force the shutdown of the current MATLAB sessionasynchronously

ldquocloserdquo on page 1-190

Disconnect or terminate the current MATLAB session

Method Details

startMatlabstatic MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Start MATLAB synchronously

String[] options Startup options used to start MATLAB engine For options seeldquoStartup and Shutdownrdquo

1 API Reference

1-178

Instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start

MatlabEngine engine = MatlabEnginestartMatlab()

ldquoStart and Close MATLAB Session from Javardquo

startMatlabAsyncstatic FutureltMatlabEnginegt startMatlabAsync(String[] options)

static FutureltMatlabEnginegt startMatlabAsync()

Start MATLAB asynchronously

String[] options Startup options used to start MATLAB For options seeldquoStartup and Shutdownrdquo

Instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEnginestartMatlabAsync()

ldquoStart and Close MATLAB Session from Javardquo

findMatlabstatic String[] findMatlab()

Find all shared MATLAB sessions on the local machine synchronously

commathworksengineMatlabEngine class

1-179

An array of the names of all shared MATLAB sessions on the local machine or an emptyvector if there are no shared MATLAB sessions available on the local machine

commathworksengineEngineException

If there is a failure during the search for MATLAB sessions

String[] engines = MatlabEnginefindMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

findMatlabAsyncstatic FutureltSting[]gt findMatlabAsync()

Find all shared MATLAB sessions on local machine asynchronously

An instance of FutureltString[]gt

FutureltString[]gt future = MatlabEnginefindMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabstatic MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Connect to a shared MATLAB session on local machine synchronously

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session with default options

1 API Reference

1-180

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

String name Name of the shared MATLAB session Use ldquofindMatlabrdquo on page1-179 to get the names of shared MATLAB sessions

An instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start or connect

MatlabEngine engine = MatlabEngineconnectMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabAsyncstatic FutureltMatlabEnginegt connectMatlabAsync(String name)

static FutureltMatlabEnginegt connectMatlabAsync

Connect to a shared MATLAB session on local machine asynchronously The behavior isthe same as that of connectMatlab except the mechanism is asynchronous

String name Name of the shared MATLAB session

An instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEngineconnectMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

commathworksengineMatlabEngine class

1-181

fevalltTgt T feval(int nlhs String func Writer output Writer errorObjecthellip args)

ltTgt T feval(int nlhs String func Objecthellip args)

ltTgt T feval(String func Writer output Writer error Objecthellip args)

ltTgt T feval(String func Objecthellip args)

Evaluate MATLAB functions with input arguments synchronously

String func Name of the MATLAB function or script to evaluateint nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

Result of executing the MATLAB function

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

1 API Reference

1-182

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is a MATLAB runtime error in the function

commathworksengineUnsupportedTypeExeption

There is an unsupported data type

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB function

double result = enginefeval(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

fevalAsyncltTgt FutureltTgt fevalAsync(int nlhs String func Writer outputWriter error Objecthellip args)

ltTgt FutureltTgt fevalAsync(int nlhs String func Objecthellip args)

ltTgt FutureltTgt fevalAsync(String func Writer output Writer errorObjecthellip args)

ltTgt FutureltTgt fevalAsync(String func Objecthellip args)

Evaluate MATLAB functions with input arguments asynchronously

String func Name of the MATLAB function or script to evaluate

commathworksengineMatlabEngine class

1-183

int nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginefevalAsync(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

evalvoid eval(String command Writer output Writer error)

void eval(String command)

Evaluate a MATLAB statement as a string synchronously

1 API Reference

1-184

String command MATLAB statement to evaluateWriter output Stream used to store the standard output from the MATLAB

statement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABstatement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is an error in the MATLAB statement duringruntime

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB statement

engineeval(result = sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

evalAsyncFutureltVoidgt evalAsync(String command Writer output Writer error)

FutureltVoidgt evalAsync(String command)

Evaluate a MATLAB statement as a string asynchronously

String command MATLAB statement to evaluate

commathworksengineMatlabEngine class

1-185

Writer output Stream used to store the standard output from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the output from the MATLABcommand window

Writer error Stream used to store the standard error from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the error message from theMATLAB command window

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineevalAsync(sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

getVariableltTgt T getVariable(String varName)

Get a variable from the MATLAB base workspace

String varName Name of a variable in the MATLAB base workspace

Variable passed from the MATLAB base workspace

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

1 API Reference

1-186

javalangIllegalStateException

The MATLAB session is not available

double myVar = enginegetVariable(myVar)

ldquoPass Variables from MATLAB to Javardquo

getVariableAsyncltTgt FutureltTgt getVariableAsync(String varName)

Get a variable from the MATLAB base workspace asynchronously

String varName Name of a variable in MATLAB base workspace

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginegetVariableAsync(myVar)

ldquoPass Variables from MATLAB to Javardquo

putVariablevoid putVariable(String varName T varData)

Put a variable into the MATLAB base workspace

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

commathworksengineMatlabEngine class

1-187

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

javalangIllegalStateException

The MATLAB session is not available

engineputVariable(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

putVariableAsyncFutureltVoidgt putVariableAsync(String varName T varData)

Put a variable into the MATLAB base workspace asynchronously

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineputVariableAsync(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

disconnectvoid disconnect()

Disconnect from the current MATLAB session

1 API Reference

1-188

commathworksengineEngineException

The current MATLAB session cannot be disconnected

enginedisconnect()

ldquoClose MATLAB Engine Sessionrdquo

disconnectAsyncFutureltVoidgt disconnectAsync()

Disconnect from the current MATLAB session

FutureltVoidgt future = enginedisconnectAsync()

ldquoClose MATLAB Engine Sessionrdquo

quitviod quit()

Force the shutdown of the current MATLAB session

commathworksengineEngineException

The current MATLAB session cannot be shut down

enginequit()

ldquoClose MATLAB Engine Sessionrdquo

quitAsyncFutureltVoidgt quitAsync()

commathworksengineMatlabEngine class

1-189

Force the shutdown of the current MATLAB session asynchronously without waiting fortermination

An instance of FutureltVoidgt

FutureltVoidgt future = enginequitAsync()

ldquoClose MATLAB Engine Sessionrdquo

closevoid close()

MatlabEngine provides the close() method to implement thejavalangAutoCloseable interface for MatlabEngine objects This close()method enables you to use a try-with-resources statement to automatically disconnect orterminate the MATLAB session at the end of the statement

The MatlabEngine close() method disconnects or terminates the current MATLABsession depending on the context

bull If a Java process starts the MATLAB session as a default non-shared sessionclose() terminates MATLAB

bull If the MATLAB session is a shared session close() disconnects MATLAB from thisJava process MATLAB terminates when there are no other connections

To force the shutdown or disconnection of the current MATLAB session explicitly callMatlabEnginequit() MatlabEnginedisconnect() or their asynchronouscounterparts

engineclose()

ldquoClose MATLAB Engine Sessionrdquo

1 API Reference

1-190

Examples

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously The workflowis

bull Open a MATLAB sessionbull Invoke the MATLAB sqrt function with arguments asynchronouslybull Get the result of the MATLAB functionbull Close the MATLAB engine

import commathworksengineMatlabEngine

FutureltMatlabEnginegt engFuture = MatlabEnginestartMatlabAsync()MatlabEngine engine = engFutureget()double myVar = 4FutureltDoublegt future = enginefevalAsync(sqrt myVar)double result = futureget()Systemoutprintln(result)

See AlsomatlabengineengineName | matlabengineisEngineShared |matlabengineshareEngine

TopicsldquoBuild Java Engine ProgramsrdquoldquoStart and Close MATLAB Session from Javardquo

Introduced in R2016b

commathworksengineMatlabEngine class

1-191

commathworksmatlabtypesComplex classPackage commathworksmatlabtypes

Java class to pass complex data to and from MATLAB

DescriptionThe Complex class provides Java support for MATLAB complex arrays Use this class topass complex data to MATLAB The MATLAB engine passes complex data to Java as aninstance of Complex

All MATLAB numeric types are converted to double in Java

Constructor SummaryComplex(double real double imag) constructs an instance of Complex with thespecified real and imaginary values

Field Summarydouble real The real part of the complex datadouble imag The imaginary part of the complex data

Examples

Pass Complex Variable to MATLAB Function

import commathworksengineMatlabEngine

MatlabEngine engine = MatlabEnginestartMatlab()

1 API Reference

1-192

Complex c = new Complex(23)Complex cj = enginefeval(conjc)

bull ldquoUsing Complex Variables in Javardquo

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoUsing Complex Variables in Javardquo

Introduced in R2016b

commathworksmatlabtypesComplex class

1-193

commathworksmatlabtypesHandleObject classPackage commathworksmatlabtypes

Java class to represent MATLAB handle objects

DescriptionJava represents handle objects that are passed from MATLAB as instances of theHandleObject class When passing a handle object back to MATLAB Java passes areference to the HandleObject instance This reference can be either an array or ascalar depending on the original handle object passed to Java from MATLAB

You can pass a handle object only to the MATLAB session in which it was originallycreated You cannot construct a HandleObject in Java

Examples

Get Handle Object from MATLAB

This example starts a shared MATLAB session and creates a containersMap object inthe MATLAB workspace The statement evaluated in the MATLAB workspace returns ahandle variable that refers to the Map object

The engine getVariable function returns the MATLAB handle variable as aHandleObject instance This instance is used to call the MATLABcontainersMapkeys function to obtain the Map keys

import commathworksengineMatlabEngineimport commathworksmatlabtypes

MatlabEngine engine = MatlabEnginestartMatlab()engineeval(cm = containersMap(idname11mw))

1 API Reference

1-194

HandleObject handle = enginegetVariable(cm)String[] cells = enginefeval(keys handle)

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex | commathworksmatlabtypesStruct

TopicsldquoUsing MATLAB Handle Objects in Javardquo

Introduced in R2016b

commathworksmatlabtypesHandleObject class

1-195

commathworksmatlabtypesStruct classPackage commathworksmatlabtypes

Java class to pass MATLAB struct to and from MATLAB

DescriptionThe Struct class provides support for passing data between MATLAB and Java as aMATLAB struct The Struct class implements the javautilMap interface

The Struct class is designed as an immutable type Attempting to change the mappingskeys or values of the returned Struct causes an UnsupportedOperationExceptionCalling these methods can cause the exception put() putAll() remove()entrySet() keySet() and values()

For an example see ldquoUsing MATLAB Structures in Javardquo

Constructor SummaryStruct s = new Struct(field1value1field2value2 ) creates aninstance of Struct with the specified field names and values

Method SummarycontainsKey(Object key) Returns true if this map contains a

mapping for the specified keycontainsValue(Object value) Returns true if this map maps one or more

keys to the specified valueentrySet() Returns a Set view of the mappings

contained in this mapequals(Object o) Compares the specified object with this

map for equality

1 API Reference

1-196

get(Object key) Returns the value to which the specifiedkey is mapped or null if this map containsno mapping for the key

hashCode() Returns the hash code value for this mapisEmpty() Returns true if this map contains no key-

value mappingskeySet() Returns a Set view of the keys contained

in this mapsize() Returns the number of key-value mappings

in this mapvalues() Returns a Collection view of the values

contained in this map

Examples

Create Struct for MATLAB Function Argument

Create a Struct and assign a key and value

import commathworksengineimport commathworksmatlabtypes

class StructProperties public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() int[] y = 12345 double[] color = 100507 Struct s = new Struct(ColorcolorLineWidth2) engfeval(plotys)

bull ldquoUsing MATLAB Structures in Javardquo

commathworksmatlabtypesStruct class

1-197

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject

TopicsldquoUsing MATLAB Structures in Javardquo

Introduced in R2016b

1 API Reference

1-198

commathworksmatlabtypesCellStr classPackage commathworksmatlabtypes

Java class to represent MATLAB cell array of char vectors

DescriptionThe CellStr class provides support for passing data from Java to MATLAB as aMATLAB cell array of char vectors (called a cellstr in MATLAB see cellstr) Thereare MATLAB functions that require cell arrays of char vectors as inputs To passarguments from Java to a MATLAB function requiring cellst inputs use the JavaCellStr class to create a compatible type

A MATLAB cellstr is mapped to a Java String array

Constructor SummaryCellStr(Object stringArray) creates a CellStr using a String or String arrayThe String array can have multiple dimensions

Method SummaryObject getStringArray() Get the String or String array used to

create the CellStrboolean equals(CellStr1CellStr2) Compare one CellStr instance with

another Two CellStr instances are equalif the String or String array they containare the same

commathworksmatlabtypesCellStr class

1-199

Examples

Construct CellStrThis example constructs a CellStr named keySet and puts the variable in theMATLAB base workspaceimport commathworksengineimport commathworksmatlabtypes

class javaCellstr public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() CellStr keySet = new CellStr(new String[]JanFebMarApr) engputVariable(mapKeyskeySet) engclose()

Construct CellStr Array

This example creates a CellStr array and passes it to the MATLAB plot function tochange the appearance of the graph produced by MATLAB The call to the MATLABprint function exports the figure as a jpeg file named myPlotjpg

import commathworksengineimport commathworksmatlabtypes

class CellStrArray public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() String[][] strArray = new String[2][2] strArray[0][0] = MarkerFaceColor strArray[0][1] = MarkerEdgeColor strArray[1][0] = green strArray[1][1] = red CellStr markerCellStr = new CellStr(strArray) engputVariable(MmarkerCellStr) engeval(plot(110--bsM)) engeval(print(myPlot-djpeg)) engclose()

1 API Reference

1-200

See AlsocommathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoPass Java CellStr to MATLABrdquo

Introduced in R2016b

commathworksmatlabtypesCellStr class

1-201

engClose (C and Fortran)Quit MATLAB engine session

C Syntaxinclude enginehint engClose(Engine ep)

Fortran Syntaxinclude enginehinteger4 engClose(ep)mwPointer ep

Argumentsep

Engine pointer

Returns0 on success and 1 otherwise Possible failure includes attempting to terminate analready-terminated MATLAB engine session

DescriptionThis routine sends a quit command to the MATLAB engine session and closes theconnection

1 API Reference

1-202

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIXreg operating systemsbull engwindemoc for a C example on Microsoftreg Windowsreg operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen

Introduced before R2006a

engClose (C and Fortran)

1-203

engEvalString (C and Fortran)Evaluate expression in string

C Syntaxinclude enginehint engEvalString(Engine ep const char string)

Fortran Syntaxinclude enginehinteger4 engEvalString(ep string)mwPointer epcharacter() string

Argumentsep

Engine pointerstring

String to execute

Returns1 if the engine session is no longer running or the engine pointer is invalid or NULLOtherwise returns 0 even if the MATLAB engine session cannot evaluate the command

DescriptionengEvalString evaluates the expression contained in string for the MATLAB enginesession ep previously started by engOpen

1 API Reference

1-204

UNIX Operating Systems

On UNIX systems engEvalString sends commands to the MATLAB workspace bywriting down a pipe connected to the MATLAB stdin process MATLAB reads back fromstdout any output resulting from the command that ordinarily appears on the screeninto the buffer defined by engOutputBuffer

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Microsoft Windows Operating Systems

On a Windows system engEvalString communicates with MATLAB software using aComponent Object Model (COM) interface

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engOutputBuffer

Introduced before R2006a

engEvalString (C and Fortran)

1-205

engGetVariable (C and Fortran)Copy variable from MATLAB engine workspace

C Syntaxinclude enginehmxArray engGetVariable(Engine ep const char name)

Fortran Syntaxinclude enginehmwPointer engGetVariable(ep name)mwPointer epcharacter() name

Argumentsep

Engine pointername

Name of mxArray to get from MATLAB workspace

ReturnsPointer to a newly allocated mxArray structure or NULL if the attempt failsengGetVariable fails if the named variable does not exist

DescriptionengGetVariable reads the named mxArray from the MATLAB engine sessionassociated with ep

1 API Reference

1-206

The limit for the size of data transferred is 2 GB

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengPutVariable mxDestroyArray

Introduced before R2006a

engGetVariable (C and Fortran)

1-207

engGetVisible (C)Determine visibility of MATLAB engine session

C Syntaxinclude enginehint engGetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Pointer to value returned from engGetVisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengGetVisible returns the current visibility setting for MATLAB engine session ep Avisible engine session runs in a window on the Windows desktop thus making the engineavailable for user interaction MATLAB removes an invisible session from the desktop

ExamplesThe following code opens engine session ep and disables its visibility

1 API Reference

1-208

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengSetVisible

engGetVisible (C)

1-209

Engine (C)Type for MATLAB engine

DescriptionA handle to a MATLAB engine object

Engine is a C language opaque type

You can call MATLAB software as a computational engine by writing C and Fortranprograms that use the MATLAB engine library Engine is the link between yourprogram and the separate MATLAB engine process

The header file containing this type is

include engineh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc shows how to call the MATLAB engine functions from a C programbull engwindemoc show how to call the MATLAB engine functions from a C program for

Windows systemsbull fengdemoF shows how to call the MATLAB engine functions from a Fortran

program

See AlsoengOpen

1 API Reference

1-210

engOpen (C and Fortran)Start MATLAB engine session

C Syntaxinclude enginehEngine engOpen(const char startcmd)

Fortran Syntaxinclude enginehmwPointer engOpen(startcmd)character() startcmd

Argumentsstartcmd

String to start the MATLAB process On Windows systems the startcmd stringmust be NULL

ReturnsPointer to an engine handle or NULL if the open fails

DescriptionThis routine allows you to start a MATLAB process for using MATLAB as acomputational engine

engOpen starts a MATLAB process using the command specified in the stringstartcmd establishes a connection and returns an engine pointer

engOpen (C and Fortran)

1-211

On UNIX systems if startcmd is NULL or the empty string engOpen starts a MATLABprocess on the current host using the command matlab If startcmd is a hostnameengOpen starts a MATLAB process on the designated host by embedding the specifiedhostname string into the larger string

rsh hostname bincsh -c setenv DISPLAY hostname0 matlab

If startcmd is any other string (has white space in it or nonalphanumeric characters)MATLAB executes the string literally

On UNIX systems engOpen performs the following steps

1 Creates two pipes2 Forks a new process Sets up the pipes to pass stdin and stdout from MATLAB

(parent) software to two file descriptors in the engine program (child)3 Executes a command to run MATLAB software (rsh for remote execution)

On Windows systems engOpen opens a COM channel to MATLAB The MATLABsoftware you registered during installation starts If you did not register duringinstallation enter the following command at the MATLAB prompt

matlab -regserver

See ldquoMATLAB COM Integrationrdquo for additional details

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

Introduced before R2006a

1 API Reference

1-212

engOpenSingleUse (C)Start MATLAB engine session for single nonshared use

C Syntaxinclude enginehEngine engOpenSingleUse(const char startcmd void dcom int retstatus)

Argumentsstartcmd

String to start MATLAB process On Microsoft Windows systems the startcmdstring must be NULL

dcomReserved for future use must be NULL

retstatusReturn status possible cause of failure

Returns

Microsoft Windows Operating Systems Only

Pointer to an engine handle or NULL if the open fails

UNIX Operating Systems

Not supported on UNIX systems

engOpenSingleUse (C)

1-213

DescriptionThis routine allows you to start multiple MATLAB processes using MATLAB as acomputational engine

engOpenSingleUse starts a MATLAB process establishes a connection and returns aunique engine identifier or NULL if the open fails Each call to engOpenSingleUsestarts a new MATLAB process

engOpenSingleUse opens a COM channel to MATLAB This starts the MATLABsoftware you registered during installation If you did not register during installationenter the following command at the MATLAB prompt

matlab -regserver

engOpenSingleUse allows single-use instances of an engine serverengOpenSingleUse differs from engOpen which allows multiple applications to use thesame engine server

See ldquoMATLAB COM Integrationrdquo for additional details

1 API Reference

1-214

engOutputBuffer (C and Fortran)Specify buffer for MATLAB output

C Syntaxinclude enginehint engOutputBuffer(Engine ep char p int n)

Fortran Syntaxinclude enginehinteger4 engOutputBuffer(ep p)mwPointer epcharactern p

Argumentsep

Engine pointerp

Pointer to character buffern

Length of buffer p

Returns1 if you pass it a NULL engine pointer Otherwise returns 0

engOutputBuffer (C and Fortran)

1-215

DescriptionengOutputBuffer defines a character buffer for engEvalString to return any outputthat ordinarily appears on the screen

The default behavior of engEvalString is to discard any standard output caused by thecommand it is executing A call to engOutputBuffer with a buffer of nonzero lengthtells any subsequent calls to engEvalString to save output in the character bufferpointed to by p

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Note The buffer returned by engEvalString is not NULL terminated

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engEvalString

Introduced before R2006a

1 API Reference

1-216

engPutVariable (C and Fortran)Put variable into MATLAB engine workspace

C Syntaxinclude enginehint engPutVariable(Engine ep const char name const mxArray pm)

Fortran Syntaxinclude enginehinteger4 engPutVariable(ep name pm)mwPointer ep pmcharacter() name

Argumentsep

Engine pointername

Name of mxArray in the engine workspacepm

mxArray pointer

Returns0 if successful and 1 if an error occurs

DescriptionengPutVariable writes mxArray pm to the engine ep giving it the variable name name

engPutVariable (C and Fortran)

1-217

If the mxArray does not exist in the workspace the function creates it If an mxArraywith the same name exists in the workspace the function replaces the existing mxArraywith the new mxArray

The limit for the size of data transferred is 2 GB

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The engine application owns the original mxArray and is responsible for freeing itsmemory Although the engPutVariable function sends a copy of the mxArray to theMATLAB workspace the engine application does not need to account for or free memoryfor the copy

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengGetVariable

Introduced before R2006a

1 API Reference

1-218

engSetVisible (C)Show or hide MATLAB engine session

C Syntaxinclude enginehint engSetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Value to set the Visible property to Set value to 1 to make the engine windowvisible or to 0 to make it invisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengSetVisible makes the window for the MATLAB engine session ep either visible orinvisible on the Windows desktop You can use this function to enable or disable userinteraction with the MATLAB engine session

engSetVisible (C)

1-219

ExamplesThe following code opens engine session ep and disables its visibility

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengGetVisible

1 API Reference

1-220

matClose (C and Fortran)Close MAT-file

C Syntaxinclude mathint matClose(MATFile mfp)

Fortran Syntaxinclude mathinteger4 matClose(mfp)mwPointer mfp

Argumentsmfp

Pointer to MAT-file information

ReturnsEOF in C (-1 in Fortran) for a write error and 0 if successful

DescriptionmatClose closes the MAT-file associated with mfp

ExamplesSee the following examples in matlabrootexternexampleseng_mat

matClose (C and Fortran)

1-221

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen

Introduced before R2006a

1 API Reference

1-222

matDeleteVariable (C and Fortran)Delete array from MAT-file

C Syntaxinclude mathint matDeleteVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathinteger4 matDeleteVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to delete

Returns0 if successful and nonzero otherwise

DescriptionmatDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp

matDeleteVariable (C and Fortran)

1-223

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

Introduced before R2006a

1 API Reference

1-224

MATFile (C and Fortran)Type for MAT-file

DescriptionA handle to a MAT-file object A MAT-file is the data file format MATLAB software usesfor saving data to your disk

MATFile is a C language opaque type

The MAT-file interface library contains routines for reading and writing MAT-files Callthese routines from your own CC++ and Fortran programs using MATFile to accessyour data file

The header file containing this type is

include math

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen matClose matPutVariable matGetVariable mxDestroyArray

MATFile (C and Fortran)

1-225

matGetDir (C and Fortran)List of variables in MAT-file

C Syntaxinclude mathchar matGetDir(MATFile mfp int num)

Fortran Syntaxinclude mathmwPointer matGetDir(mfp num)mwPointer mfpinteger4 num

Argumentsmfp

Pointer to MAT-file informationnum

Pointer to the variable containing the number of mxArrays in the MAT-file

ReturnsPointer to an internal array containing pointers to the names of the mxArrays in theMAT-file pointed to by mfp In C each name is a NULL-terminated string The numoutput argument is the length of the internal array (number of mxArrays in the MAT-file) If num is zero mfp contains no arrays

matGetDir returns NULL in C (0 in Fortran) If matGetDir fails sets num to a negativenumber

1 API Reference

1-226

DescriptionThis routine provides you with a list of the names of the mxArrays contained within aMAT-file

matGetDir allocates memory for the internal array of strings using a mxCalloc Freethe memory using mxFree when you are finished with the array

MATLAB variable names can be up to length mxMAXNAM defined in the C header filematrixh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo2F

Introduced before R2006a

matGetDir (C and Fortran)

1-227

matGetFp (C)File pointer to MAT-file

C Syntaxinclude mathFILE matGetFp(MATFile mfp)

Argumentsmfp

Pointer to MAT-file information

ReturnsC file handle to the MAT-file with handle mfp Returns NULL if mfp is a handle to aMAT-file in HDF5-based format

DescriptionUse matGetFp to obtain a C file handle to a MAT-file Standard C library routines likeferror and feof use file handle to investigate errors

Introduced before R2006a

1 API Reference

1-228

matGetNextVariable (C and Fortran)Next array in MAT-file

C Syntaxinclude mathmxArray matGetNextVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing the next mxArray from theMAT-file pointed to by mfp The function returns the name of the mxArray in name

matGetNextVariable returns NULL in C (0 in Fortran) for end of file or if there is anerror condition In C use feof and ferror from the Standard C Library to determinestatus

matGetNextVariable (C and Fortran)

1-229

DescriptionmatGetNextVariable allows you to step sequentially through a MAT-file and readevery mxArray in a single pass The function reads and returns the next mxArray fromthe MAT-file pointed to by mfp

Use matGetNextVariable immediately after opening the MAT-file with matOpen andnot with other MAT-file routines Otherwise the concept of the next mxArray isundefined

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariable is notguaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariableInfo matGetVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-230

matGetNextVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetNextVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing header information for thenext mxArray from the MAT-file pointed to by mfp The function returns the name of themxArray in name

matGetNextVariableInfo returns NULL in C (0 in Fortran) when the end of file isreached or if there is an error condition In C use feof and ferror from the Standard CLibrary to determine status

matGetNextVariableInfo (C and Fortran)

1-231

DescriptionmatGetNextVariableInfo loads only the array header information includingeverything except pr pi ir and jc from the current file offset

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetNextVariableInfo sets them to -1 instead These headers are forinformational use only Never pass this data back to the MATLAB workspace or save it toMAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariableInfo isnot guaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariable matGetVariableInfo

Introduced before R2006a

1 API Reference

1-232

matGetVariable (C and Fortran)Array from MAT-file

C Syntaxinclude mathmxArray matGetVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing the mxArray named byname from the MAT-file pointed to by mfp

matGetVariable returns NULL in C (0 in Fortran) if the attempt to return the mxArraynamed by name fails

matGetVariable (C and Fortran)

1-233

DescriptionThis routine allows you to copy an mxArray out of a MAT-file

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-234

matGetVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing header information for themxArray named by name from the MAT-file pointed to by mfp

matGetVariableInfo returns NULL in C (0 in Fortran) if the attempt to return headerinformation for the mxArray named by name fails

matGetVariableInfo (C and Fortran)

1-235

DescriptionmatGetVariableInfo loads only the array header information including everythingexcept pr pi ir and jc It recursively creates the cells and structures through theirleaf elements but does not include pr pi ir and jc

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetVariableInfo sets them to -1 instead These headers are for informational useonly Never pass this data back to the MATLAB workspace or save it to MAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomatGetVariable

Introduced before R2006a

1 API Reference

1-236

matlabengineconnect_matlabConnect shared MATLAB session to MATLAB Engine for Python

Syntaxeng = matlabengineconnect_matlab(name=None)eng = matlabengineconnect_matlab( ___ async)

Descriptioneng = matlabengineconnect_matlab(name=None) connects to the sharedMATLAB session name and returns a MatlabEngine object as eng The inputargument name specifies the name of a MATLAB session that is already running on yourlocal machine

bull If you specify name and the engine cannot find a shared MATLAB session of the samename then you receive an EngineError exception

bull If you do not specify name and the engine cannot find any shared MATLAB sessionsthen it starts a new shared MATLAB session If there are shared MATLAB sessionsrunning the engine connects to the first available session

bull If you do not specify name and the engine finds multiple shared MATLAB sessionsrunning then it connects to the first available session

eng = matlabengineconnect_matlab( ___ async) connects asynchronously ifasync is True

Examples

Connect to MATLAB Session

Connect to a shared MATLAB session that is already running on your local machine

matlabengineconnect_matlab

1-237

import matlabengineeng = matlabengineconnect_matlab()engsqrt(40)

20

matlabengineconnect_matlab connects to the first available shared MATLABsession If no MATLAB sessions are shared matlabengineconnect_matlab starts anew session

Connect to MATLAB Sessions by Name

When there are multiple shared MATLAB sessions on your local machine connect to twodifferent sessions one at a time by specifying their names

Connect to the first shared MATLAB session

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

Connect to the second shared MATLAB session

eng = matlabengineconnect_matlab(MATLAB_7090)engsqrt(40)

20

bull ldquoConnect Python to Running MATLAB Sessionrdquo

Input Argumentsname mdash Name of shared MATLAB sessioncharacter array

Name of the shared MATLAB session specified as a character array

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

1 API Reference

1-238

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

Output Argumentseng mdash Pythonreg variable for communicating with MATLABMatlabEngine object

Python variable for communicating with MATLAB returned as a MatlabEngine objecteng communicates with a shared MATLAB session that is already running on your localmachine

Limitationsbull Do not connect the engine multiple times to the same shared MATLAB session

See AlsomatlabengineMatlabEngine | matlabenginefind_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabengineconnect_matlab

1-239

matlabenginefind_matlabFind shared MATLAB sessions to connect to MATLAB Engine for Python

Syntaxnames = matlabenginefind_matlab()

Descriptionnames = matlabenginefind_matlab() finds all shared MATLAB sessions on yourlocal machine and returns their names in a tuple Any name in names can be the inputargument to matlabengineconnect_matlab If there are no shared sessionsrunning on your local machine matlabenginefind_matlab returns an emptytuple

Examples

Find Shared MATLAB Sessions

Identify the shared MATLAB sessions running on your local machine and connect to oneof them

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

There are two shared MATLAB sessions running so matlabenginefind_matlabreturns two names in a tuple

Connect to the first shared MATLAB session

1 API Reference

1-240

eng = matlabengineconnect_matlab(MATLAB_6830)

bull ldquoConnect Python to Running MATLAB Sessionrdquo

See Alsomatlabengineconnect_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabenginefind_matlab

1-241

matlabengineFutureResult classPackage matlabengine

Results of asynchronous call to MATLAB function stored in Python object

DescriptionThe FutureResult class stores results of an asynchronous call to a MATLAB function ina Python object

ConstructionThe MATLAB Engine for Python creates a FutureResult object when a MATLABfunction is called asynchronously There is no need to callmatlabengineFutureResult() to create FutureResult objects of your own

Methods

cancel Cancel asynchronous call to MATLAB function from Pythoncancelled Cancellation status of asynchronous call to MATLAB function from Pythondone Completion status of asynchronous call to MATLAB function from Pythonresult Result of asynchronous call to MATLAB function from Python

ExceptionsSyntaxError Python exception syntax error in function

callTypeError Python exception data type of output

argument not supported

1 API Reference

1-242

matlabengineCancelledError MATLAB engine cannot cancel functioncall

matlabengineInterruptedError Function call interruptedmatlabengineMatlabExecutionError

Function call fails to execute

matlabengineRejectedExecutionError

Engine terminated

matlabengineTimeoutError Result cannot be returned within thetimeout period

Examples

Get Result of Asynchronous MATLAB Call from Python

Call the MATLAB sqrt function from Python Set async to True to make the functioncall asynchronously

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquo

See AlsomatlabengineMatlabEngine

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from Pythonrdquo

matlabengineFutureResult class

1-243

Introduced in R2014b

1 API Reference

1-244

cancelClass matlabengineFutureResultPackage matlabengine

Cancel asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancel()

Descriptiontf = FutureResultcancel() cancels a call to a MATLAB function calledasynchronously from Python FutureResultcancel returns True if it successfullycancels the function and False if it cannot cancel the function

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status returned as either True or False The status tf is True ifFutureResultcancel successfully cancels the asynchronous function call and isFalse otherwise

Examples

Cancel an Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval function Thencancel it

cancel

1-245

import matlabengineeng = matlabenginestart_matlab()ret = engeval(while 1 endnargout=0async=True)tf = retcancel()print(tf)

True

See Also

1 API Reference

1-246

cancelledClass matlabengineFutureResultPackage matlabengine

Cancellation status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancelled()

Descriptiontf = FutureResultcancelled() returns the cancellation status of a call to aMATLAB function called asynchronously from Python FutureResultcancelledreturns True if a previous call to FutureResultcancel succeeded and Falseotherwise

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status of an asynchronous function call returned as either True or False

Examples

Check Cancellation Status of Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval functionCancel it and check that the engine stopped the loopimport matlabengineeng = matlabenginestart_matlab()

cancelled

1-247

ret = engeval(while 1 endnargout=0async=True)eval_stop = retcancel()tf = retcancelled()print(tf)

True

See Also

1 API Reference

1-248

doneClass matlabengineFutureResultPackage matlabengine

Completion status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultdone()

Descriptiontf = FutureResultdone() returns the completion status of a MATLAB functioncalled asynchronously from Python FutureResultdone returns True if the functionhas finished and False if it has not finished

Output Argumentstf mdash Completion status of asynchronous function callTrue | False

Completion status of an asynchronous function call returned as either True or False

Examples

Check If Asynchronous Call Finished

Call the MATLAB sqrt function with async = True Check the status of ret to learn ifsqrt is finished

import matlabengineeng = matlabenginestart_matlab()

done

1-249

ret = engsqrt(40async=True)tf = retdone()print(tf)

True

When retdone() returns True then you can call retresult() to return the squareroot

See Also

1 API Reference

1-250

resultClass matlabengineFutureResultPackage matlabengine

Result of asynchronous call to MATLAB function from Python

Syntaxret = FutureResultresult(timeout=None)

Descriptionret = FutureResultresult(timeout=None) returns the actual result of a call to aMATLAB function called asynchronously from Python

Input Argumentstimeout mdash Timeout value in secondsNone (default) | Python float

Timeout value in seconds specified as Python data type float to wait for result of thefunction call If timeout = None the FutureResultresult function waits until thefunction call finishes and then returns the result

Output Argumentsret mdash Result of asynchronous function callPython object

Result of an asynchronous function call returned as a Python object that is the actualoutput argument of a call to a MATLAB function

result

1-251

Examples

Get MATLAB Output Argument from Asynchronous Call

Call the MATLAB sqrt function from Python Set async to True and get the squareroot from the FutureResult object

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

See Also

1 API Reference

1-252

matlabengineMatlabEngine classPackage matlabengine

Python object using MATLAB as computational engine within Python session

DescriptionThe MatlabEngine class uses a MATLAB process as a computational engine for PythonYou can call MATLAB functions as methods of a MatlabEngine object because thefunctions are dynamically invoked when you call them You also can call functions andscripts that you define You can send data to and retrieve data from the MATLABworkspace associated with a MatlabEngine object

ConstructionThe matlabenginestart_matlab function creates a MatlabEngine object each timeit is called There is no need to call matlabengineMatlabEngine() to createMatlabEngine objects of your own

MethodsYou can call any MATLAB function as a method of a MatlabEngine object The enginedynamically invokes a MATLAB function when you call it The syntax shows positionalkeyword and output arguments of a function call

ret =MatlabEnginematlabfunc(argsnargout=1async=Falsestdout=sysstsdoutstderr=sysstderr)

Replace matlabfunc with the name of any MATLAB function (such as isprime orsqrt) Replace args with input arguments for the MATLAB function you call Thekeyword arguments specify

matlabengineMatlabEngine class

1-253

bull The number of output arguments the function returnsbull Whether the engine calls the function asynchronouslybull Where the engine sends standard output and standard error coming from the function

Specify keyword arguments only when specifying values that are not the default valuesshown in the syntax

Input Arguments to MATLAB FunctionArgument Description Python Typeargs Input arguments to

MATLAB function specifiedas positional arguments

Any Python types that theengine can convert toMATLAB types

Keyword Arguments to EngineArgument Description Python Typenargout Number of output

arguments from MATLABfunction

intDefault 1

async Flag to call MATLABfunction asynchronously

boolDefault False

stdout Standard output StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstdout

stderr Standard error StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstderr

1 API Reference

1-254

Output ArgumentsOutput Type Description Required Keyword

ArgumentsPython variable One output argument from

MATLAB functionDefault values

tuple Multiple output argumentsfrom MATLAB function

nargout=n (where n gt 1)

None No output argument fromMATLAB function

nargout=0

FutureResult object A placeholder for outputarguments fromasynchronous call toMATLAB function

async=True

ExceptionsMatlabExecutionError Function call fails to executeRejectedExecutionError MATLAB engine terminatedSyntaxError Syntax error in a function callTypeError Data type of an input or output argument

not supported

Attributesworkspace Python dictionary containing references to

MATLAB variables You can assign data toand get data from a MATLAB variablethrough the workspace The name of eachMATLAB variable you create becomes akey in the workspace dictionary The keysin workspace must be valid MATLABidentifiers (for example you cannot usenumbers as keys)

matlabengineMatlabEngine class

1-255

Examples

Call MATLAB Functions from Python

Call the MATLAB sqrt function from Python using the engine

import matlabengineeng = matlabenginestart_matlab()ret = engsqrt(40)print(ret)

20

Put Array Into MATLAB Workspace

Create an array in Python and put it into the MATLAB workspace

import matlabengineeng = matlabenginestart_matlab()px = englinspace(006281000)

px is a MATLAB array but englinspace returned it to Python To use it in MATLABput the array into the MATLAB workspace

engworkspace[mx] = px

When you add an entry to the engine workspace dictionary you create a MATLABvariable as well The engine converts the data to a MATLAB data type

Get Data from MATLAB Workspace

Get pi from the MATLAB workspace and copy it to a Python variable

import matlabengineeng = matlabenginestart_matlab()engeval(a = pinargout=0)mpi = engworkspace[a]print(mpi)

1 API Reference

1-256

314159265359

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquobull ldquoRedirect Standard Output and Error to Pythonrdquo

See AlsomatlabengineFutureResult | matlabenginestart_matlab

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from PythonrdquoldquoRedirect Standard Output and Error to Pythonrdquo

Introduced in R2014b

matlabengineMatlabEngine class

1-257

matlabenginestart_matlabStart MATLAB Engine for Python

Syntaxeng = matlabenginestart_matlab()

eng = matlabenginestart_matlab(option)eng = matlabenginestart_matlab(async)eng = matlabenginestart_matlab(background)eng = matlabenginestart_matlab( ___ )

Descriptioneng = matlabenginestart_matlab() starts a new MATLAB process and returnsPython variable eng which is a MatlabEngine object for communicating with theMATLAB process

If MATLAB cannot be started the engine raises an EngineError exception

eng = matlabenginestart_matlab(option) uses startup options specified byoption

For example call matlabenginestart_matlab(-desktop) to start the MATLABdesktop from Python

eng = matlabenginestart_matlab(async) starts MATLAB asynchronously ifasync is True

eng = matlabenginestart_matlab(background) starts MATLABasynchronously if background is True

eng = matlabenginestart_matlab( ___ ) can include any of the input argumentsin previous syntaxes

1 API Reference

1-258

Examples

Start MATLAB Engine from Python

Start an engine and a new MATLAB process from the Python command line

import matlabengineeng = matlabenginestart_matlab()

Start Multiple Engines

Start a different MATLAB process from each engine

import matlabengineeng1 = matlabenginestart_matlab()eng2 = matlabenginestart_matlab()

Start MATLAB Desktop with Engine

Start an engine with the MATLAB desktop

import matlabengineeng = matlabenginestart_matlab(-desktop)

You also can start the desktop after you start the engineimport matlabengineeng = matlabenginestart_matlab()engdesktop(nargout=0)

Note You can call MATLAB functions from both the desktop and Python

Start Engine Asynchronously

Start the engine with async=True While MATLAB starts you can enter commands atthe Python command line

matlabenginestart_matlab

1-259

import matlabenginefuture = matlabenginestart_matlab(async=True)eng = futureresult()engsqrt(4)

20

bull ldquoStart and Stop MATLAB Engine for Pythonrdquo

Input Argumentsoption mdash Startup options for MATLAB process-nodesktop (default) | string

Startup options for the MATLAB process specified as a string You can specify multiplestartup options with option

The engine supports -desktop to start MATLAB with the desktop In addition theengine supports all MATLAB startup options except for the options listed inldquoLimitationsrdquo on page 1-261Example matlabenginestart_matlab(-desktop -r format short) startsthe desktop from Python The engine passes -r format short to MATLAB

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

background mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargument background is an alias for async and will be removed in a future releaseExample matlabenginestart_matlab(background=True)

1 API Reference

1-260

Output Argumentseng mdash Python variable for communicating with MATLABMatlabEngine object | FutureResult object

Python variable for communicating with MATLAB returned as a MatlabEngine objectif async or background is set to False or a FutureResult object if async orbackground is set to True

Each time you call matlabenginestart_matlab it starts a new MATLAB process

LimitationsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

See AlsomatlabengineMatlabEngine

TopicsldquoStart and Stop MATLAB Engine for PythonrdquoldquoSpecify Startup OptionsrdquoldquoCommonly Used Startup Optionsrdquo

Introduced in R2014b

matlabenginestart_matlab

1-261

matOpen (C and Fortran)Open MAT-file

C Syntaxinclude mathMATFile matOpen(const char filename const char mode)

Fortran Syntaxinclude mathmwPointer matOpen(filename mode)character() filename mode

Argumentsfilename

Name of file to openmode

File opening mode The following table lists valid values for moder Opens file for reading only determines the current version of the MAT-

file by inspecting the files and preserves the current versionu Opens file for update both reading and writing If the file does not exist

does not create a file (equivalent to the r+ mode of fopen) Determinesthe current version of the MAT-file by inspecting the files and preservesthe current version

w Opens file for writing only deletes previous contents if anyw4 Creates a MAT-file compatible with MATLAB Versions 4 software and

earlierw6 Creates a MAT-file compatible with MATLAB Version 5 (R8) software or

earlier Equivalent to wL mode

1 API Reference

1-262

wL Opens file for writing character data using the default character set foryour system Use MATLAB Version 6 or 65 software to read theresulting MAT-file

If you do not use the wL mode switch MATLAB writes character data tothe MAT-file using Unicodereg character encoding by default

Equivalent to w6 modew7 Creates a MAT-file compatible with MATLAB Version 70 (R14) software

or earlier Equivalent to wz modewz Opens file for writing compressed data By default the MATLAB save

function compresses workspace variables as they are saved to a MAT-fileTo use the same compression ratio when creating a MAT-file with thematOpen function use the wz option

Equivalent to w7 modew73 Creates a MAT-file in an HDF5-based format that can store objects that

occupy more than 2 GB

ReturnsFile handle or NULL in C (0 in Fortran) if the open fails

DescriptionThis routine opens a MAT-file for reading and writing

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1F

matOpen (C and Fortran)

1-263

bull matdemo2F

See AlsomatClose save

Introduced before R2006a

1 API Reference

1-264

matPutVariable (C and Fortran)Array to MAT-file

C Syntaxinclude mathint matPutVariable(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariable(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library along with matGetFp to determine status

matPutVariable (C and Fortran)

1-265

DescriptionThis routine puts an mxArray into a MAT-file

matPutVariable writes mxArray pm to the MAT-file mfp If the mxArray does notexist in the MAT-file the function appends it to the end If an mxArray with the samename exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatGetVariable matGetFp

Introduced before R2006a

1 API Reference

1-266

matPutVariableAsGlobal (C and Fortran)Array to MAT-file as originating from global workspace

C Syntaxinclude mathint matPutVariableAsGlobal(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariableAsGlobal(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library with matGetFp to determine status

matPutVariableAsGlobal (C and Fortran)

1-267

DescriptionThis routine puts an mxArray into a MAT-file matPutVariableAsGlobal is likematPutVariable except that MATLAB software loads the array into the globalworkspace and sets a reference to it in the local workspace If you write to a MATLAB 4format file matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable

matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp If the mxArraydoes not exist in the MAT-file the function appends it to the end If an mxArray with thesame name exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable matGetFp

Introduced before R2006a

1 API Reference

1-268

mexAtExit (C and Fortran)Register function to call when MEX function clears or MATLAB terminates

C Syntaxinclude mexhint mexAtExit(void (ExitFcn)(void))

Fortran Syntaxinclude fintrfhinteger4 mexAtExit(ExitFcn)subroutine ExitFcn()

ArgumentsExitFcn

Pointer to function you want to run on exit

ReturnsAlways returns 0

DescriptionUse mexAtExit to register a function to call just before clearing the MEX function orterminating MATLAB mexAtExit gives your MEX function a chance to perform taskssuch as freeing persistent memory and closing files Other typical tasks include closingstreams or sockets

mexAtExit (C and Fortran)

1-269

Each MEX function can register only one active exit function at a time If you callmexAtExit more than once MATLAB uses the ExitFcn from the more recentmexAtExit call as the exit function

If a MEX function is locked you cannot clear the MEX file Therefore if you attempt toclear a locked MEX file MATLAB does not call the ExitFcn

In Fortran declare the ExitFcn as external in the Fortran routine that callsmexAtExit if it is not within the scope of the file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See AlsomexLock mexUnlock

Introduced before R2006a

1 API Reference

1-270

mexCallMATLAB (C and Fortran)Call MATLAB function user-defined function or MEX file

C Syntaxinclude mexhint mexCallMATLAB(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhinteger4 mexCallMATLAB(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

Argumentsnlhs

Number of output arguments Must be less than or equal to 50plhs

Array of pointers to output argumentsnrhs

Number of input arguments Must be less than or equal to 50prhs

Array of pointers to input argumentsfunctionName

Character string containing name of the MATLAB built-in function operator user-defined function or MEX file you are calling

mexCallMATLAB (C and Fortran)

1-271

If functionName is an operator place the operator inside a pair of single quotes forexample +

Returns0 if successful and a nonzero value if unsuccessful

DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions MATLABoperators user-defined functions or other MEX files Both mexCallMATLAB andmexEvalString execute MATLAB commands Use mexCallMATLAB for returningresults (left side arguments) back to the MEX file The mexEvalString function cannotreturn values to the MEX file

For a complete description of the input and output arguments passed to functionNamesee mexFunction

Error HandlingIf functionName detects an error MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt To trap errors use the mexCallMATLABWithTrapfunction

Limitationsbull Avoid using the mexCallMATLAB function in Simulinkreg S-functions If you do do not

store the resulting plhs mxArray pointers in any S-function block state that persistsafter the MEX function finishes Outputs of mexCallMATLAB have temporary scopeand are automatically destroyed at the end of the MEX function call

bull It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLABFor example this function returns two variables but only assigns one of them a value

function [ab] = foo(c)a = 2c

1 API Reference

1-272

If you then call foo using mexCallMATLAB the unassigned output variable is nowtype mxUNKNOWN_CLASS

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexevalstringcbull mexcallmatlabwithtrapc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxisclassc

See AlsomexFunction mexCallMATLABWithTrap mexEvalString mxDestroyArray

Tipsbull MATLAB allocates dynamic memory to store the arrays in plhs for mexCallMATLAB

MATLAB automatically deallocates the dynamic memory when you exit the MEX fileHowever if heap space is at a premium call mxDestroyArray when you are finishedwith the arrays in plhs

Note The plhs argument for mexCallMATLAB is not the same as the plhs formexFunction Do not destroy an mxArray returned in plhs for mexFunction

mexCallMATLAB (C and Fortran)

1-273

Introduced before R2006a

1 API Reference

1-274

mexCallMATLABWithTrap (C and Fortran)Call MATLAB function user-defined function or MEX-file and capture error information

C Syntaxinclude mexhmxArray mexCallMATLABWithTrap(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhmwPointer mexCallMATLABWithTrap(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

ArgumentsFor more information about arguments see mexCallMATLAB

nlhsNumber of desired output arguments

plhsArray of pointers to output arguments

nrhsNumber of input arguments

prhsArray of pointers to input arguments

functionNameCharacter string containing the name of the MATLAB built-in function operatorfunction or MEX-file that you are calling

mexCallMATLABWithTrap (C and Fortran)

1-275

ReturnsNULL if no error occurred otherwise a pointer to an mxArray of class MException

DescriptionThe mexCallMATLABWithTrap function performs the same function as mexCallMATLABHowever if MATLAB detects an error when executing functionName MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexCallMATLABWithTrap For information about MException see ldquoRespond to anExceptionrdquo

See AlsomexCallMATLAB MException

Introduced in R2008b

1 API Reference

1-276

mexErrMsgIdAndTxt (C and Fortran)Display error message with identifier and return to MATLAB prompt

C Syntaxinclude mexhvoid mexErrMsgIdAndTxt(const char errorid const char errormsg )

Fortran Syntaxinclude fintrfhsubroutine mexErrMsgIdAndTxt(errorid errormsg)character() errorid errormsg

Argumentserrorid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

errormsgString to display In C the string can include conversion specifications used by theANSIreg C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexErrMsgIdAndTxt function writes an error message to the MATLAB windowFor more information see the error function syntax statement using a message

mexErrMsgIdAndTxt (C and Fortran)

1-277

identifier After the error message prints MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt

Calling mexErrMsgIdAndTxt does not clear the MEX file from memory SomexErrMsgIdAndTxt does not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgIdAndTxt automatically frees the allocated memory

Note If you get warnings when using mexErrMsgIdAndTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errorid and errormsg the mexErrMsgIdAndTxt functiondetermines where the error occurred and displays the following information Forexample in the function foo mexErrMsgIdAndTxt displays

Error using foo

If you compile your MEX file with the MinGW-w64 compiler see the limitations withexception handling topic in ldquoTroubleshooting and Limitations Compiling CC++ MEXFiles with MinGW-w64rdquo

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrcbull matrixDividecbull timestwoFbull xtimesyF

1 API Reference

1-278

Validate char Input

The following code snippet checks if input argument prhs[0] is a string If not thecode displays a warning If there is an error reading the input string the code displaysan error message and terminates the MEX file

char bufint buflen

if (mxIsChar(prhs[0])) if (mxGetString(prhs[0] buf buflen) == 0) mexPrintf(The input string is sn buf) else mexErrMsgIdAndTxt(MyProgConvertString Could not convert string data) exit MEX file else mexWarnMsgIdAndTxt(MyProgInputString Input should be a string to print properly)

continue with processing

See Alsoerror | mexWarnMsgIdAndTxt

TopicsldquoMemory Considerations for Class DestructorsrdquoldquoTroubleshooting and Limitations Compiling CC++ MEX Files with MinGW-w64rdquo

Introduced before R2006a

mexErrMsgIdAndTxt (C and Fortran)

1-279

mexErrMsgTxt (C and Fortran)Display error message and return to MATLAB prompt

Note mexErrMsgTxt is not recommended Use mexErrMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexErrMsgTxt(const char errormsg)

Fortran Syntaxsubroutine mexErrMsgTxt(errormsg)character() errormsg

Argumentserrormsg

String containing the error message to display

DescriptionmexErrMsgTxt writes an error message to the MATLAB window After the errormessage prints MATLAB terminates the MEX-file and returns control to the MATLABprompt

Calling mexErrMsgTxt does not clear the MEX-file from memory So mexErrMsgTxtdoes not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgTxt automatically frees the allocated memory

1 API Reference

1-280

Note If you get warnings when using mexErrMsgTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errormsg the mexerrmsgtxt function determines where the erroroccurred and displays the following information If an error labeled Print my errormessage occurs in the function foo mexerrmsgtxt displays

Error using fooPrint my error message

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexErrMsgTxt (C and Fortran)

1-281

mexEvalString (C and Fortran)Execute MATLAB command in caller workspace

C Syntaxinclude mexhint mexEvalString(const char command)

Fortran Syntaxinclude fintrfhinteger4 mexEvalString(command)character() command

Argumentscommand

String containing MATLAB command to execute

Returns0 if successful and 1 if an error occurs

DescriptionCall mexEvalString to invoke a MATLAB command in the workspace of the caller

mexEvalString and mexCallMATLAB both execute MATLAB commands UsemexCallMATLAB for returning results (left side arguments) back to the MEX file ThemexEvalString function cannot return values to the MEX file

1 API Reference

1-282

All arguments that appear to the right of an equal sign in the command string must becurrent variables of the caller workspace

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction For more information see ldquoVariable Namesrdquo

Error HandlingIf command detects an error MATLAB returns control to the MEX-file andmexEvalString returns 1 If you want to trap errors use themexEvalStringWithTrap function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexevalstringc

See AlsomexCallMATLAB mexEvalStringWithTrap

Introduced before R2006a

mexEvalString (C and Fortran)

1-283

mexEvalStringWithTrap (C and Fortran)Execute MATLAB command in caller workspace and capture error information

C Syntaxinclude mexhmxArray mexEvalStringWithTrap(const char command)

Fortran Syntaxinclude fintrfhmwPointer mexEvalStringWithTrap(command)character() command

Argumentscommand

String containing the MATLAB command to execute

ReturnsObject ME of class MException

DescriptionThe mexEvalStringWithTrap function performs the same function as mexEvalStringHowever if MATLAB detects an error when executing command MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexEvalStringWithTrap

1 API Reference

1-284

See AlsomexEvalString MException mexCallMATLAB

Introduced before R2006a

mexEvalStringWithTrap (C and Fortran)

1-285

mexFunction (C and Fortran)Entry point to CC++ or Fortran MEX file

C Syntaxinclude mexhvoid mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

Fortran Syntaxinclude fintrfhsubroutine mexFunction(nlhs plhs nrhs prhs)integer nlhs nrhsmwPointer plhs() prhs()

Argumentsnlhs

Number of expected output mxArraysplhs

Array of pointers to the expected output mxArraysnrhs

Number of input mxArraysprhs

Array of pointers to the input mxArrays Do not modify any prhs values in yourMEX file Changing the data in these read-only mxArrays can produce undesiredside effects

1 API Reference

1-286

DescriptionmexFunction is not a routine you call Rather mexFunction is the name of the gatewayfunction in C (subroutine in Fortran) which every MEX file requires When you invoke aMEX function MATLAB software finds and loads the corresponding MEX file of thesame name MATLAB then searches for a symbol named mexFunction within the MEXfile If it finds one it calls the MEX function using the address of the mexFunctionsymbol MATLAB displays an error message if it cannot find a routine namedmexFunction inside the MEX file

When you invoke a MEX file MATLAB automatically seeds nlhs plhs nrhs and prhswith the calling arguments In the syntax of the MATLAB language functions have thegeneral form

[abc] = fun(def)

where the denotes more items of the same format The abc are left-sideoutput arguments and the def are right-side input arguments The argumentsnlhs and nrhs contain the number of left side and right side arguments respectivelyprhs is an array of mxArray pointers whose length is nrhs plhs is an array whoselength is nlhs where your function must set pointers for the output mxArrays

Note It is possible to return an output value even if nlhs = 0 which corresponds toreturning the result in the ans variable

To experiment with passing input arguments build the mexfunctionc examplefollowing the instructions in ldquoTable of MEX File Source Code Filesrdquo

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctioncbull mexlockfF

mexFunction (C and Fortran)

1-287

See Also

TopicsldquoIntroducing MEX Filesrdquo

Introduced before R2006a

1 API Reference

1-288

mexFunctionName (C and Fortran)Name of current MEX function

C Syntaxinclude mexhconst char mexFunctionName(void)

Fortran Syntaxinclude fintrfhcharacter() mexFunctionName()

ReturnsName of the current MEX function

DescriptionmexFunctionName returns the name of the current MEX function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

Introduced before R2006a

mexFunctionName (C and Fortran)

1-289

mexGet (C)Value of specified graphics property

Note Do not use mexGet Use mxGetProperty instead

C Syntaxinclude mexhconst mxArray mexGet(double handle const char property)

Argumentshandle

Handle to a particular graphics objectproperty

Graphics property

ReturnsValue of the specified property in the specified graphics object on success Returns NULLon failure Do not modify the return argument from mexGet Changing the data in aconst (read-only) mxArray can produce undesired side effects

DescriptionCall mexGet to get the value of the property of a certain graphics object mexGet is theAPI equivalent of the MATLAB get function To set a graphics property value callmexSet

1 API Reference

1-290

See AlsomxGetProperty mxSetProperty

mexGet (C)

1-291

mexGetVariable (C and Fortran)Copy of variable from specified workspace

C Syntaxinclude mexhmxArray mexGetVariable(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariable(workspace varname)character() workspace varname

Argumentsworkspace

Specifies where mexGetVariable searches for array varname The possible valuesarebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of the variable to copy

ReturnsCopy of the variable on success Returns NULL in C (0 on Fortran) on failure A commoncause of failure is specifying a variable that is not currently in the workspace Perhapsthe variable was in the workspace at one time but has since been cleared

1 API Reference

1-292

DescriptionCall mexGetVariable to get a copy of the specified variable The returned mxArraycontains a copy of all the data and characteristics that the variable had in the otherworkspace Modifications to the returned mxArray do not affect the variable in theworkspace unless you write the copy back to the workspace with mexPutVariable

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

See AlsomexGetVariablePtr mexPutVariable mxDestroyArray

mexGetVariable (C and Fortran)

1-293

mexGetVariablePtr (C and Fortran)Read-only pointer to variable from another workspace

C Syntaxinclude mexhconst mxArray mexGetVariablePtr(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariablePtr(workspace varname)character() workspace varname

Argumentsworkspace

Specifies which workspace you want mexGetVariablePtr to search The possiblevalues arebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of a variable in another workspace This is a variable name not an mxArraypointer

ReturnsRead-only pointer to the mxArray on success Returns NULL in C (0 in Fortran) onfailure

1 API Reference

1-294

DescriptionCall mexGetVariablePtr to get a read-only pointer to the specified variable varnameinto your MEX-file workspace This command is useful for examining an mxArrays dataand characteristics If you want to change data or characteristics use mexGetVariable(along with mexPutVariable) instead of mexGetVariablePtr

If you simply want to examine data or characteristics mexGetVariablePtr offerssuperior performance because the caller wants to pass only a pointer to the array

See AlsomexGetVariable

Introduced before R2006a

mexGetVariablePtr (C and Fortran)

1-295

mexIsLocked (C and Fortran)Determine if MEX-file is locked

C Syntaxinclude mexhbool mexIsLocked(void)

Fortran Syntaxinclude fintrfhinteger4 mexIsLocked()

ReturnsLogical 1 (true) if the MEX-file is locked logical 0 (false) if the file is unlocked

DescriptionCall mexIsLocked to determine if the MEX-file is locked By default MEX-files areunlocked meaning you can clear the MEX-file at any time

To unlock a MEX-file call mexUnlock

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-296

See AlsomexLock mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexIsLocked (C and Fortran)

1-297

mexLock (C and Fortran)Prevent clearing MEX-file from memory

C Syntaxinclude mexhvoid mexLock(void)

Fortran Syntaxinclude fintrfhsubroutine mexLock()

DescriptionBy default MEX files are unlocked meaning you can clear them at any time CallmexLock to prohibit clearing a MEX file

To unlock a MEX file call mexUnlock Do not use the munlock function

mexLock increments a lock count If you call mexLock n times call mexUnlock n timesto unlock your MEX file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-298

See AlsomexIsLocked mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexLock (C and Fortran)

1-299

mexMakeArrayPersistent (C and Fortran)Make array persist after MEX file completes

C Syntaxinclude mexhvoid mexMakeArrayPersistent(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mexMakeArrayPersistent(pm)mwPointer pm

Argumentspm

Pointer to an mxArray created by an mxCreate function

DescriptionBy default an mxArray allocated by an mxCreate function is not persistent TheMATLAB memory management facility automatically frees a nonpersistent mxArraywhen the MEX function finishes If you want the mxArray to persist through multipleinvocations of the MEX function call the mexMakeArrayPersistent function

Do not assign an array created with the mexMakeArrayPersistent function to theplhs output argument of a MEX file

Note If you create a persistent mxArray you are responsible for destroying it usingmxDestroyArray when the MEX file is cleared If you do not destroy a persistentmxArray MATLAB leaks memory See mexAtExit to see how to register a function that

1 API Reference

1-300

gets called when the MEX file is cleared See mexLock to see how to lock your MEX fileso that it is never cleared

See AlsomexAtExit mxDestroyArray mexLock mexMakeMemoryPersistent and themxCreate functions

Introduced before R2006a

mexMakeArrayPersistent (C and Fortran)

1-301

mexMakeMemoryPersistent (C and Fortran)Make memory allocated by MATLAB software persist after MEX-function completes

C Syntaxinclude mexhvoid mexMakeMemoryPersistent(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mexMakeMemoryPersistent(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of memory allocated by one of the MATLAB memoryallocation routines

DescriptionBy default memory allocated by MATLAB is nonpersistent so it is freed automaticallywhen the MEX function finishes If you want the memory to persist callmexMakeMemoryPersistent

Note If you create persistent memory you are responsible for freeing it when the MEXfunction is cleared If you do not free the memory MATLAB leaks memory To freememory use mxFree See mexAtExit to see how to register a function that gets calledwhen the MEX function is cleared See mexLock to see how to lock your MEX function sothat it is never cleared

1 API Reference

1-302

See AlsomexAtExit mexLock mexMakeArrayPersistent mxCalloc mxFree mxMallocmxRealloc

Introduced before R2006a

mexMakeMemoryPersistent (C and Fortran)

1-303

mexPrintf (C and Fortran)ANSI C PRINTF-style output routine

C Syntaxinclude mexhint mexPrintf(const char message )

Fortran Syntaxinclude fintrfhinteger4 mexPrintf(message)character() message

Argumentsmessage

String to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

ReturnsNumber of characters printed including characters specified with backslash codes suchas n and b

1 API Reference

1-304

DescriptionThis routine prints a string on the screen and in the diary (if the diary is in use) Itprovides a callback to the standard C printf routine already linked inside MATLABsoftware which avoids linking the entire stdio library into your MEX file

In a C MEX file call mexPrintf instead of printf to display a string

Note If you want the literal in your message use in the message string since hasspecial meaning to printf Failing to do so causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See Alsosprintf mexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexPrintf (C and Fortran)

1-305

mexPutVariable (C and Fortran)Array from MEX-function into specified workspace

C Syntaxinclude mexhint mexPutVariable(const char workspace const char varname const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mexPutVariable(workspace varname pm)character() workspace varnamemwPointer pm

Argumentsworkspace

Specifies scope of the array you are copying Values for workspace arebase Copy mxArray to the base workspacecaller Copy mxArray to the caller workspaceglobal Copy mxArray to the list of global variables

varnameName of mxArray in the workspace

pmPointer to the mxArray

1 API Reference

1-306

Returns0 on success 1 on failure A possible cause of failure is that pm is NULL in C (0 inFortran)

DescriptionCall mexPutVariable to copy the mxArray at pointer pm from your MEX-function intothe specified workspace MATLAB software gives the name varname to the copiedmxArray in the receiving workspace

mexPutVariable makes the array accessible to other entities such as MATLAB user-defined functions or other MEX-functions

If a variable of the same name exists in the specified workspace mexPutVariableoverwrites the previous contents of the variable with the contents of the new mxArrayFor example suppose the MATLAB workspace defines variable Peaches as

Peaches1 2 3 4

and you call mexPutVariable to copy Peaches into the same workspace

mexPutVariable(base Peaches pm)

The value passed by mexPutVariable replaces the old value of Peaches

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

mexPutVariable (C and Fortran)

1-307

See AlsomexGetVariable

1 API Reference

1-308

mexSet (C)Set value of specified graphics property

Note Do not use mexSet Use mxSetProperty instead

C Syntaxinclude mexhint mexSet(double handle const char property mxArray value)

Argumentshandle

Handle to a particular graphics objectproperty

String naming a graphics propertyvalue

Pointer to an mxArray holding the new value to assign to the property

Returns0 on success 1 on failure Possible causes of failure include

bull Specifying a nonexistent propertybull Specifying an illegal value for that property for example specifying a string value for

a numerical property

mexSet (C)

1-309

DescriptionCall mexSet to set the value of the property of a certain graphics object mexSet is theAPI equivalent of the MATLAB set function To get the value of a graphics property callmexGet

See AlsomxGetProperty mxSetProperty

1 API Reference

1-310

mexSetTrapFlag (C and Fortran)Control response of MEXCALLMATLAB to errors

C Syntaxinclude mexhvoid mexSetTrapFlag(int trapflag)

Note mexSetTrapFlag will be removed in a future version UsemexCallMATLABWithTrap instead

Fortran Syntaxsubroutine mexSetTrapFlag(trapflag)integer4 trapflag

Argumentstrapflag

Control flag Possible values are0 On error control returns to the MATLAB prompt1 On error control returns to your MEX-file

DescriptionCall mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB

If you do not call mexSetTrapFlag then whenever MATLAB detects an error in a call tomexCallMATLAB MATLAB automatically terminates the MEX-file and returns controlto the MATLAB prompt Calling mexSetTrapFlag with trapflag set to 0 is equivalentto not calling mexSetTrapFlag at all

mexSetTrapFlag (C and Fortran)

1-311

If you call mexSetTrapFlag and set the trapflag to 1 then whenever MATLABdetects an error in a call to mexCallMATLAB MATLAB does not automatically terminatethe MEX-file Rather MATLAB returns control to the line in the MEX-file immediatelyfollowing the call to mexCallMATLAB The MEX-file is then responsible for taking anappropriate response to the error

If you call mexSetTrapFlag the value of the trapflag you set remains in effect untilthe next call to mexSetTrapFlag within that MEX-file or if there are no more calls tomexSetTrapFlag until the MEX-file exits If a routine defined in a MEX-file callsanother MEX-file MATLAB

1 Saves the current value of the trapflag in the first MEX-file2 Calls the second MEX-file with the trapflag initialized to 0 within that file3 Restores the saved value of trapflag in the first MEX-file when the second MEX-

file exits

See AlsomexCallMATLAB mexCallMATLABWithTrap mexAtExit mexErrMsgTxt

Introduced in R2008b

1 API Reference

1-312

mexUnlock (C and Fortran)Allow clearing MEX-file from memory

C Syntaxinclude mexhvoid mexUnlock(void)

Fortran Syntaxinclude fintrfhsubroutine mexUnlock()

DescriptionBy default MEX-files are unlocked meaning you can clear them at any time CallingmexLock locks a MEX-file so that you cannot clear it from memory Call mexUnlock toremove the lock

mexLock increments a lock count If you called mexLock n times call mexUnlock ntimes to unlock your MEX-file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

mexUnlock (C and Fortran)

1-313

See AlsomexIsLocked mexLock mexMakeArrayPersistent mexMakeMemoryPersistentclear

1 API Reference

1-314

mexWarnMsgIdAndTxt (C and Fortran)Warning message with identifier

C Syntaxinclude mexhvoid mexWarnMsgIdAndTxt(const char warningid const char warningmsg )

Fortran Syntaxinclude fintrfhsubroutine mexWarnMsgIdAndTxt(warningid warningmsg)character() warningid warningmsg

Argumentswarningid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

warningmsgString to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexWarnMsgIdAndTxt function writes a warning message to the MATLABcommand prompt The warnings displayed are the same as warnings issued by the

mexWarnMsgIdAndTxt (C and Fortran)

1-315

MATLAB warning function To control the information displayed or suppressed call thewarning function with the desired settings before calling your MEX-file

Unlike mexErrMsgIdAndTxt calling mexWarnMsgIdAndTxt does not terminate theMEX-file

See AlsomexErrMsgIdAndTxt warning

Introduced before R2006a

1 API Reference

1-316

mexWarnMsgTxt (C and Fortran)Warning message

Note mexWarnMsgTxt is not recommended Use mexWarnMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexWarnMsgTxt(const char warningmsg)

Fortran Syntaxsubroutine mexWarnMsgTxt(warningmsg)character() warningmsg

Argumentswarningmsg

String containing the warning message to display

DescriptionmexWarnMsgTxt causes MATLAB software to display the contents of warningmsgmexWarnMsgTxt does not terminate the MEX-file

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexWarnMsgTxt (C and Fortran)

1-317

mwIndex (C and Fortran)Type for index values

DescriptionmwIndex is a type that represents index values such as indices into arrays Use thisfunction for cross-platform flexibility By default mwIndex is equivalent to int in CWhen using the mex -largeArrayDims switch mwIndex is equivalent to size_t in CIn Fortran mwIndex is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwIndex is a preprocessor macro The Fortran header file containing thistype is

include fintrfh

See Alsomex mwSize mwSignedIndex

Introduced before R2006a

1 API Reference

1-318

mwPointer (Fortran)Platform-independent pointer type

DescriptionmwPointer is a preprocessor macro that declares the appropriate Fortran typerepresenting a pointer to an mxArray or to other data that is not of a native Fortrantype such as memory allocated by mxMalloc On 32-bit platforms the Fortran type thatrepresents a pointer is INTEGER4 on 64-bit platforms it is INTEGER8 The Fortranpreprocessor translates mwPointer to the Fortran declaration that is appropriate for theplatform on which you compile your file

If your Fortran compiler supports preprocessing you can use mwPointer to declarefunctions arguments and variables that represent pointers If you cannot usemwPointer ensure that your declarations have the correct size for the platform on whichyou are compiling Fortran code

The Fortran header file containing this type is

include fintrfh

ExamplesThis example declares the arguments for mexFunction in a Fortran MEX file

subroutine mexFunction(nlhs plhs nrhs prhs)mwPointer plhs() prhs()integer nlhs nrhs

For additional examples see the Fortran files with names ending in F in thematlabrootexternexamples folder

Introduced in R2006a

mwPointer (Fortran)

1-319

mwSignedIndex (C and Fortran)Signed integer type for size values

DescriptionmwSignedIndex is a signed integer type that represents size values such as arraydimensions Use this function for cross-platform flexibility By default mwSignedIndexis equivalent to ptrdiff_t in C++ In Fortran mwSignedIndex is similarly equivalentto INTEGER4 or INTEGER8 based on platform and compilation flags

The C header file containing this type is

include matrixh

The Fortran header file containing this type is

include fintrfh

See AlsomwSize mwIndex

Introduced in R2009a

1 API Reference

1-320

mwSize (C and Fortran)Type for size values

DescriptionmwSize is a type that represents size values such as array dimensions Use this functionfor cross-platform flexibility By default mwSize is equivalent to size_t in C mwSize isan unsigned type meaning a nonnegative integer

When using the mex -compatibleArrayDims switch mwSize is equivalent to int in CIn Fortran mwSize is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwSize is a preprocessor macro The Fortran header file containing this typeis

include fintrfh

See Alsomex mwIndex mwSignedIndex

Introduced before R2006a

mwSize (C and Fortran)

1-321

mxAddField (C and Fortran)Add field to structure array

C Syntaxinclude matrixhextern int mxAddField(mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxAddField(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of the field you want to add

ReturnsField number on success or -1 if inputs are invalid or an out-of-memory conditionoccurs

1 API Reference

1-322

DescriptionCall mxAddField to add a field to a structure array Create the values with themxCreate functions and use mxSetFieldByNumber to set the individual values for thefield

See AlsomxRemoveField mxSetFieldByNumber

Introduced before R2006a

mxAddField (C and Fortran)

1-323

mxArray (C)Type for MATLAB array

DescriptionThe fundamental type underlying MATLAB data For information on how the MATLABarray works with MATLAB-supported variables see ldquoMATLAB Datardquo

mxArray is a C language opaque type

All C MEX-files start with a gateway routine called mexFunction which requiresmxArray for both input and output parameters For information about the C MEX-filegateway routine see ldquoComponents of MEX Filerdquo

Once you have MATLAB data in your MEX-file use functions in the Matrix Library tomanipulate the data and functions in the MEX Library to perform operations in theMATLAB environment You use mxArray to pass data to and from these functions

Use any of the mxCreate functions to create data and the correspondingmxDestroyArray function to free memory

The header file containing this type is

include matrixh

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomexFunction mxClassID mxCreateDoubleMatrix mxCreateNumericArraymxCreateString mxDestroyArray mxGetData mxSetData

1 API Reference

1-324

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquobull For troubleshooting mxArray errors in other MathWorks products search the

documentation for that product or see MATLAB Answerstrade topic Subscripting intoan mxArray is not supported

Introduced before R2006a

mxArray (C)

1-325

mxArrayToString (C)Array to string

C Syntaxinclude matrixhchar mxArrayToString(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string Returns NULL on failure Possible reasons for failure include out ofmemory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToString to copy the character data of an mxCHAR array into a C-stylestring The C-style string is always terminated with a NULL character and stored incolumn-major order

If the array contains multiple rows the rows are copied column-wise into a single array

This function is similar to mxGetString except that

bull It does not require the length of the string as an inputbull It supports both multi-byte and single-byte encoded characters On Windows and

Linuxreg platforms the default encoding is specified by the user locale setting

1 API Reference

1-326

mxArrayToString does not free the dynamic memory that the char pointer points toTherefore you typically free the C-style string (using mxFree) immediately after youhave finished using it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxArrayToUTF8String mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetString

Introduced before R2006a

mxArrayToString (C)

1-327

mxArrayToUTF8String (C)Array to string in UTF-8 encoding

C Syntaxinclude matrixhchar mxArrayToUTF8String(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string in UTF-8 encoding Returns NULL on failure Possible reasons for failureinclude out of memory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToUTF8String to copy the character data of an mxCHAR array into a C-style string The data is stored in column-major order If the array contains multiplerows the rows are copied column-wise into a single array

mxArrayToUTF8String does not free the dynamic memory that the char pointer pointsto Use mxFree to free memory

See AlsomxArrayToString mxFree mxCreateCharArray mxCreateString mxGetString

1 API Reference

1-328

Introduced in R2015a

mxArrayToUTF8String (C)

1-329

mxAssert (C)Check assertion value for debugging purposes

C Syntaxinclude matrixhvoid mxAssert(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionLike the ANSI C assert macro mxAssert checks the value of an assertion andcontinues execution only if the assertion holds If expr evaluates to logical 1 (true)mxAssert does nothing If expr evaluates to logical 0 (false) mxAssert terminates theMEX file and prints an error to the MATLAB command window The error contains theexpression of the failed assertion the file name and line number where the failedassertion occurred and the error_message text The error_message allows you tospecify a better description of why the assertion failed Use an empty string if you do notwant a description to follow the failed assertion message

The mex script turns off these assertions when building optimized MEX functions so useassertions for debugging purposes only To use mxAssert build the MEX file using themex -g filename syntax

Assertions are a way of maintaining internal consistency of logic Use them to keepyourself from misusing your own code and to prevent logical errors from propagating

1 API Reference

1-330

before they are caught Do not use assertions to prevent users of your code from misusingit

Assertions can be taken out of your code by the C preprocessor You can use these checksduring development and then remove them when the code works properly letting youuse them for troubleshooting during development without slowing down the finalproduct

See AlsomxAssertS mexErrMsgIdAndTxt

Introduced before R2006a

mxAssert (C)

1-331

mxAssertS (C)Check assertion value without printing assertion text

C Syntaxinclude matrixhvoid mxAssertS(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionmxAssertS is like mxAssert except mxAssertS does not print the text of the failedassertion

See AlsomxAssert

Introduced before R2006a

1 API Reference

1-332

mxCalcSingleSubscript (C and Fortran)Offset from first element to desired element

C Syntaxinclude matrixhmwIndex mxCalcSingleSubscript(const mxArray pm mwSize nsubs mwIndex subs)

Fortran Syntaxinclude fintrfhmwIndex mxCalcSingleSubscript(pm nsubs subs)mwPointer pmmwSize nsubsmwIndex subs

Argumentspm

Pointer to an mxArraynsubs

Number of elements in the subs array Typically you set nsubs equal to the numberof dimensions in the mxArray that pm points to

subsAn array of integers Each value in the array specifies that dimensions subscript InC syntax the value in subs[0] specifies the row subscript and the value insubs[1] specifies the column subscript Use zero-based indexing for subscripts Forexample to express the starting element of a two-dimensional mxArray in subs setsubs[0] to 0 and subs[1] to 0

In Fortran syntax the value in subs(1) specifies the row subscript and the value insubs(2) specifies the column subscript Use 1-based indexing for subscripts For

mxCalcSingleSubscript (C and Fortran)

1-333

example to express the starting element of a two-dimensional mxArray in subs setsubs(1) to 1 and subs(2) to 1

ReturnsThe number of elements or index between the start of the mxArray and the specifiedsubscript This number is the linear index equivalent of the subscripts Many MatrixLibrary routines (for example mxGetField) require an index as an argument

If subs describes the starting element of an mxArray mxCalcSingleSubscriptreturns 0 If subs describes the final element of an mxArray mxCalcSingleSubscriptreturns N-1 (where N is the total number of elements)

DescriptionCall mxCalcSingleSubscript to determine how many elements there are between thebeginning of the mxArray and a given element of that mxArray The function convertssubscripts to linear indices

For example given a subscript like (57) mxCalcSingleSubscript returns thedistance from the first element of the array to the (57) element Remember that themxArray data type internally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have For examplesshowing the internal representation see ldquoData Storagerdquo

Avoid using mxCalcSingleSubscript to traverse the elements of an array In C it ismore efficient to find the starting address of the array and then use pointerautoincrementing to access successive elements For example to find the startingaddress of a numerical array call mxGetPr or mxGetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

1 API Reference

1-334

See AlsomxGetCell mxSetCell

Introduced before R2006a

mxCalcSingleSubscript (C and Fortran)

1-335

mxCalloc (C and Fortran)Allocate dynamic memory for array initialized to 0 using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxCalloc(mwSize n mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxCalloc(n size)mwSize n size

Argumentsn

Number of elements to allocate This must be a nonnegative numbersize

Number of bytes per element (The C sizeof operator calculates the number of bytesper element)

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxCalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxCalloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-336

DescriptionmxCalloc allocates contiguous heap space sufficient to hold n elements of size byteseach and initializes this newly allocated memory to 0 Use mxCalloc instead of theANSI C calloc function to allocate memory in MATLAB applications

In MEX files but not MAT or engine applications mxCalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatacbull phonebookcbull revordc

mxCalloc (C and Fortran)

1-337

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxsetdimensionsc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistentmxDestroyArray mxFree mxMalloc mxRealloc

Introduced before R2006a

1 API Reference

1-338

mxChar (C)Type for string array

DescriptionMATLAB stores an mxArray string as type mxChar to represent the C-style char typeMATLAB uses 16-bit unsigned integer character encoding for Unicode characters

The header file containing this type is

include matrixh

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxcreatecharmatrixfromstrc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCharArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

mxChar (C)

1-339

Introduced before R2006a

1 API Reference

1-340

mxClassID (C)Enumerated value identifying class of array

C Syntaxtypedef enum mxUNKNOWN_CLASS mxCELL_CLASS mxSTRUCT_CLASS mxLOGICAL_CLASS mxCHAR_CLASS mxVOID_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_CLASS

Undetermined class You cannot specify this category for an mxArray however ifmxGetClassID cannot identify the class it returns this value

mxCELL_CLASSIdentifies a cell mxArray

mxSTRUCT_CLASSIdentifies a structure mxArray

mxClassID (C)

1-341

mxLOGICAL_CLASSIdentifies a logical mxArray an mxArray of mxLogical data

mxCHAR_CLASSIdentifies a string mxArray an mxArray whose data is represented as mxChar

mxVOID_CLASSReserved

mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

1 API Reference

1-342

mxINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxFUNCTION_CLASSIdentifies a function handle mxArray

DescriptionVarious Matrix Library functions require or return an mxClassID argumentmxClassID identifies how the mxArray represents its data elements

The following table shows MATLAB types with their equivalent C types Use the typefrom the right-most column for reading mxArrays with the mxClassID value shown inthe left columnMATLAB Primitive Types

mxClassID Value MATLAB Type MEX Type C Primitive TypemxINT8_CLASS int8 int8_T char bytemxUINT8_CLASS uint8 uint8_T unsigned char bytemxINT16_CLASS int16 int16_T shortmxUINT16_CLASS uint16 uint16_T unsigned shortmxINT32_CLASS int32 int32_T intmxUINT32_CLASS uint32 uint32_T unsigned intmxINT64_CLASS int64 int64_T long longmxUINT64_CLASS uint64 uint64_T unsigned long longmxSINGLE_CLASS single float floatmxDOUBLE_CLASS double double double

mxClassID (C)

1-343

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetClassID mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-344

mxClassIDFromClassName (Fortran)Identifier corresponding to class

Fortran Syntaxinclude fintrfhinteger4 mxClassIDFromClassName(classname)character() classname

Argumentsclassname

character array specifying a MATLAB class name For a list of valid classnamechoices see the mxIsClass reference page

ReturnsNumeric identifier used internally by MATLAB software to represent the MATLAB classclassname Returns unknown if classname is not a recognized MATLAB class

DescriptionUse mxClassIDFromClassName to obtain an identifier for any MATLAB class Thisfunction is most commonly used to provide a classid argument tomxCreateNumericArray and mxCreateNumericMatrix

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matsqint8F

mxClassIDFromClassName (Fortran)

1-345

See AlsomxGetClassName mxCreateNumericArray mxCreateNumericMatrix mxIsClass

Introduced before R2006a

1 API Reference

1-346

mxComplexity (C)Flag specifying whether array has imaginary components

C Syntaxtypedef enum mxComplexity mxREAL=0 mxCOMPLEX

ConstantsmxREAL

Identifies an mxArray with no imaginary componentsmxCOMPLEX

Identifies an mxArray with imaginary components

DescriptionVarious Matrix Library functions require an mxComplexity argument You can set anmxComplex argument to either mxREAL or mxCOMPLEX

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

See AlsomxCreateNumericArray mxCreateDoubleMatrix mxCreateSparse

mxComplexity (C)

1-347

Introduced before R2006a

1 API Reference

1-348

mxCopyCharacterToPtr (Fortran)CHARACTER values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyCharacterToPtr(y px n)character() ymwPointer pxmwSize n

Argumentsy

character Fortran arraypx

Pointer to character or name arrayn

Number of elements to copy

DescriptionmxCopyCharacterToPtr copies n character values from the Fortran characterarray y into the MATLAB character vector pointed to by px This subroutine is essentialfor copying character data between MATLAB pointer arrays and ordinary Fortrancharacter arrays

See AlsomxCopyPtrToCharacter mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

mxCopyCharacterToPtr (Fortran)

1-349

Introduced before R2006a

1 API Reference

1-350

mxCopyComplex16ToPtr (Fortran)COMPLEX16 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex16ToPtr(y pr pi n)complex16 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX16 Fortran arraypr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex16ToPtr copies n COMPLEX16 values from the Fortran COMPLEX16array y into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex16ToPtr (Fortran)

1-351

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyPtrToComplex16 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-352

mxCopyComplex8ToPtr (Fortran)COMPLEX8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex8ToPtr(y pr pi n)complex8 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX8 Fortran arraypr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex8ToPtr copies n COMPLEX8 values from the Fortran COMPLEX8 arrayy into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex8ToPtr (Fortran)

1-353

See AlsomxCopyPtrToComplex8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-354

mxCopyInteger1ToPtr (Fortran)INTEGER1 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger1ToPtr(y px n)integer1 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER1 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger1ToPtr copies n INTEGER1 values from the Fortran INTEGER1 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyInteger1ToPtr (Fortran)

1-355

bull matsqint8F

See AlsomxCopyPtrToInteger1 mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-356

mxCopyInteger2ToPtr (Fortran)INTEGER2 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger2ToPtr(y px n)integer2 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER2 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger2ToPtr copies n INTEGER2 values from the Fortran INTEGER2 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger2 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger2ToPtr (Fortran)

1-357

Introduced before R2006a

1 API Reference

1-358

mxCopyInteger4ToPtr (Fortran)INTEGER4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger4ToPtr(y px n)integer4 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER4 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger4ToPtr copies n INTEGER4 values from the Fortran INTEGER4 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger4 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger4ToPtr (Fortran)

1-359

Introduced before R2006a

1 API Reference

1-360

mxCopyPtrToCharacter (Fortran)CHARACTER values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToCharacter(px y n)mwPointer pxcharacter() ymwSize n

Argumentspx

Pointer to character or name arrayy

character Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToCharacter copies n character values from the MATLAB array pointedto by px into the Fortran character array y This subroutine is essential for copyingcharacter data from MATLAB pointer arrays into ordinary Fortran character arrays

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxCopyPtrToCharacter (Fortran)

1-361

See AlsomxCopyCharacterToPtr mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

Introduced before R2006a

1 API Reference

1-362

mxCopyPtrToComplex16 (Fortran)COMPLEX16 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex16(pr pi y n)mwPointer pr picomplex16 y(n)mwSize n

Argumentspr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayy

COMPLEX16 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex16 copies n COMPLEX16 values from the MATLAB arrayspointed to by pr and pi into the Fortran COMPLEX16 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex16 (Fortran)

1-363

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyComplex16ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-364

mxCopyPtrToComplex8 (Fortran)COMPLEX8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex8(pr pi y n)mwPointer pr picomplex8 y(n)mwSize n

Argumentspr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayy

COMPLEX8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex8 copies n COMPLEX8 values from the MATLAB arrays pointedto by pr and pi into the Fortran COMPLEX8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex8 (Fortran)

1-365

See AlsomxCopyComplex8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-366

mxCopyPtrToInteger1 (Fortran)INTEGER1 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger1(px y n)mwPointer pxinteger1 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER1 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger1 copies n INTEGER1 values from the MATLAB array pointed toby px either a real or imaginary array into the Fortran INTEGER1 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyPtrToInteger1 (Fortran)

1-367

bull matsqint8F

See AlsomxCopyInteger1ToPtr mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-368

mxCopyPtrToInteger2 (Fortran)INTEGER2 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger2(px y n)mwPointer pxinteger2 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER2 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger2 copies n INTEGER2 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER2 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger2ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger2 (Fortran)

1-369

Introduced before R2006a

1 API Reference

1-370

mxCopyPtrToInteger4 (Fortran)INTEGER4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger4(px y n)mwPointer pxinteger4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger4 copies n INTEGER4 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger4ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger4 (Fortran)

1-371

Introduced before R2006a

1 API Reference

1-372

mxCopyPtrToPtrArray (Fortran)Pointer values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToPtrArray(px y n)mwPointer pxmwPointer y(n)mwSize n

Argumentspx

Pointer to pointer arrayy

Fortran array of mwPointer valuesn

Number of pointers to copy

DescriptionmxCopyPtrToPtrArray copies n pointers from the MATLAB array pointed to by px intothe Fortran array y This subroutine is essential for copying the output of matGetDirinto an array of pointers After calling this function each element of y contains a pointerto a string You can convert these strings to Fortran character arrays by passing eachelement of y as the first argument to mxCopyPtrToCharacter

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToPtrArray (Fortran)

1-373

bull matdemo2F

See AlsomatGetDir mxCopyPtrToCharacter

Introduced before R2006a

1 API Reference

1-374

mxCopyPtrToReal4 (Fortran)REAL4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal4(px y n)mwPointer pxreal4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a single-precision MATLAB arrayy

REAL4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal4 copies n REAL4 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToReal4 (Fortran)

1-375

See AlsomxCopyReal4ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-376

mxCopyPtrToReal8 (Fortran)REAL8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal8(px y n)mwPointer pxreal8 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a double-precision MATLAB arrayy

REAL8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal8 copies n REAL8 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToReal8 (Fortran)

1-377

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyReal8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-378

mxCopyReal4ToPtr (Fortran)REAL4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal4ToPtr(y px n)real4 y(n)mwPointer pxmwSize n

Argumentsy

REAL4 Fortran arraypx

Pointer to the real or imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal4ToPtr copies n REAL4 values from the Fortran REAL4 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyReal4ToPtr (Fortran)

1-379

See AlsomxCopyPtrToReal4 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-380

mxCopyReal8ToPtr (Fortran)REAL8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal8ToPtr(y px n)real8 y(n)mwPointer pxmwSize n

Argumentsy

REAL8 Fortran arraypx

Pointer to the real or imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal8ToPtr copies n REAL8 values from the Fortran REAL8 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyReal8ToPtr (Fortran)

1-381

bull matdemo1F

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyPtrToReal8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-382

mxCreateCellArray (C and Fortran)N-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the created cell For example to create a three-dimensionalcell mxArray set ndim to 3

dimsDimensions array Each element in the dimensions array contains the size of themxArray in that dimension For example in C setting dims[0] to 5 and dims[1] to7 establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellArray (C and Fortran)

1-383

DescriptionUse mxCreateCellArray to create a cell mxArray with size defined by ndim and dimsFor example in C to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims[0] = 4 dims[1] = 8 dims[2] = 7

In Fortran to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims(1) = 4 dims(2) = 8 dims(3) = 7

The created cell mxArray is unpopulated mxCreateCellArray initializes each cell toNULL To put data into a cell call mxSetCell

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateCellMatrix mxGetCell mxSetCell mxIsCell

Introduced before R2006a

1 API Reference

1-384

mxCreateCellMatrix (C and Fortran)2-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellMatrix(mwSize m mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellMatrix(m n)mwSize m n

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellMatrix (C and Fortran)

1-385

DescriptionUse mxCreateCellMatrix to create an m-by-n two-dimensional cell mxArray Thecreated cell mxArray is unpopulated mxCreateCellMatrix initializes each cell to NULLin C (0 in Fortran) To put data into cells call mxSetCell

mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only butmxCreateCellArray can create mxArrays having any number of dimensions greaterthan 1

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray

Introduced before R2006a

1 API Reference

1-386

mxCreateCharArray (C and Fortran)N-D mxChar array

C Syntaxinclude matrixhmxArray mxCreateCharArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the mxArray specified as a positive number If you specify0 1 or 2 mxCreateCharArray creates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray The dims array must have at least ndimelements

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateCharArray (C and Fortran)

1-387

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateCharArray to create an N-dimensional mxChar array The createdmxArray is unpopulated that is mxCreateCharArray initializes each cell to NULL in C(0 in Fortran)

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateCharMatrixFromStrings mxCreateString

1 API Reference

1-388

mxCreateCharMatrixFromStrings (C and Fortran)2-D mxChar array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateCharMatrixFromStrings(mwSize m const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharMatrixFromStrings(m str)mwSize mcharacter() str(m)

Argumentsm

Number of rows in the mxArray The value you specify for m is the number of stringsin str

strIn C an array of strings containing at least m strings In Fortran a characternarray of size m where each element of the array is n bytes

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray Another possible reasonfor failure is that str contains fewer than m strings

mxCreateCharMatrixFromStrings (C and Fortran)

1-389

DescriptionUse mxCreateCharMatrixFromStrings to create a two-dimensional mxArray whereeach row is initialized to a string from str In C the created mxArray has dimensions m-by-max where max is the length of the longest string in str In Fortran the createdmxArray has dimensions m-by-n where n is the number of characters in str(i)

The mxArray represents its data elements as mxChar rather than as C char

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxCreateCharArray mxCreateString mxGetString

Introduced before R2006a

1 API Reference

1-390

mxCreateDoubleMatrix (C and Fortran)2-D double-precision floating-point array

C Syntaxinclude matrixhmxArray mxCreateDoubleMatrix(mwSize m mwSize n mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleMatrix(m n ComplexFlag)mwSize m ninteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsComplexFlag

If the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateDoubleMatrix (C and Fortran)

1-391

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateDoubleMatrix to create an m-by-n mxArray mxCreateDoubleMatrixinitializes each element in the pr array to 0 If you set ComplexFlag to mxCOMPLEX in C(1 in Fortran) mxCreateDoubleMatrix also initializes each element in the pi array to0

If you set ComplexFlag to mxREAL in C (0 in Fortran) mxCreateDoubleMatrixallocates enough memory to hold m-by-n real elements If you set ComplexFlag tomxCOMPLEX in C (1 in Fortran) mxCreateDoubleMatrix allocates enough memory tohold m-by-n real elements and m-by-n imaginary elements

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its associated real and complex elements

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull matrixDividecbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull matsqF

1 API Reference

1-392

bull timestwoFbull xtimesyF

See AlsomxCreateNumericArray

Introduced before R2006a

mxCreateDoubleMatrix (C and Fortran)

1-393

mxCreateDoubleScalar (C and Fortran)Scalar double-precision array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateDoubleScalar(double value)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleScalar(value)real8 value

Argumentsvalue

Value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateDoubleScalar to create a scalar double mxArray When you finish usingthe mxArray call mxDestroyArray to destroy it

1 API Reference

1-394

See AlsomxGetPr mxCreateDoubleMatrix

Alternatives

C Language

In C you can replace the statements

pa = mxCreateDoubleMatrix(1 1 mxREAL)mxGetPr(pa) = value

with a call to mxCreateDoubleScalar

pa = mxCreateDoubleScalar(value)

Fortran Language

In Fortran you can replace the statements

pm = mxCreateDoubleMatrix(1 1 0)mxCopyReal8ToPtr(value mxGetPr(pm) 1)

with a call to mxCreateDoubleScalar

pm = mxCreateDoubleScalar(value)

Introduced before R2006a

mxCreateDoubleScalar (C and Fortran)

1-395

mxCreateLogicalArray (C)N-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalArray(mwSize ndim const mwSize dims)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateLogicalArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray There are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalArray to create an N-dimensional mxArray of mxLogicalelements After creating the mxArray mxCreateLogicalArray initializes all itselements to logical 0 mxCreateLogicalArray differs from mxCreateLogicalMatrixin that the latter can create two-dimensional arrays only

1 API Reference

1-396

mxCreateLogicalArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateLogicalMatrix mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalArray (C)

1-397

mxCreateLogicalMatrix (C)2-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalMatrix(mwSize m mwSize n)

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateLogicalMatrix to create an m-by-n mxArray of mxLogical elementsmxCreateLogicalMatrix initializes each element in the array to logical 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray

1 API Reference

1-398

See AlsomxCreateLogicalArray mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalMatrix (C)

1-399

mxCreateLogicalScalar (C)Scalar logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalScalar(mxLogical value)

Argumentsvalue

Logical value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalScalar to create a scalar logical mxArraymxCreateLogicalScalar is a convenience function that replaces the following code

pa = mxCreateLogicalMatrix(1 1)mxGetLogicals(pa) = value

When you finish using the mxArray call mxDestroyArray to destroy it

1 API Reference

1-400

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxIsLogicalScalarmxIsLogicalScalarTrue mxGetLogicals mxDestroyArray

Introduced before R2006a

mxCreateLogicalScalar (C)

1-401

mxCreateNumericArray (C and Fortran)N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateNumericArray(mwSize ndim const mwSize dims mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericArray(ndim dims classid ComplexFlag)mwSize ndimmwSize dims(ndim)integer4 classid ComplexFlag

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classid

1 API Reference

1-402

value from a MATLAB class name See the Description on page 1-403 section formore information

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericArray to create an N-dimensional mxArray in which all dataelements have the numeric data type specified by classid After creating the mxArraymxCreateNumericArray initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericArray also initializes all itsimaginary data elements to 0 mxCreateNumericArray differs frommxCreateDoubleMatrix as follows

bull All data elements in mxCreateDoubleMatrix are double-precision floating-pointnumbers The data elements in mxCreateNumericArray can be any numerical typeincluding different integer precisions

bull mxCreateDoubleMatrix can create two-dimensional arrays onlymxCreateNumericArray can create arrays of two or more dimensions

mxCreateNumericArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

mxCreateNumericArray (C and Fortran)

1-403

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull doubleelementcbull matrixDividecbull matsqint8F

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-404

Introduced before R2006a

mxCreateNumericArray (C and Fortran)

1-405

mxCreateNumericMatrix (C and Fortran)2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateNumericMatrix(mwSize m mwSize n mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericMatrix(m n classid ComplexFlag)mwSize m ninteger4 classid ComplexFlag

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classidvalue from a MATLAB class name

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

1 API Reference

1-406

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which all data elements havethe numeric data type specified by classid After creating the mxArraymxCreateNumericMatrix initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericMatrix also initializes all itsimaginary data elements to 0 mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray When you finish using the mxArray call mxDestroyArrayto destroy it

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

mxCreateNumericMatrix (C and Fortran)

1-407

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrc

The following Fortran statements create a 4-by-3 matrix of REAL4 elements having noimaginary components

C Create 4x3 mxArray of REAL4 mxCreateNumericMatrix(4 3 + mxClassIDFromClassName(single) 0)

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericMatrix mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-408

mxCreateSparse (C and Fortran)2-D sparse array

C Syntaxinclude matrixhmxArray mxCreateSparse(mwSize m mwSize n mwSize nzmax mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateSparse(m n nzmax ComplexFlag)mwSize m n nzmaxinteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparse should allocate to hold the pr ir and ifComplexFlag is mxCOMPLEX in C (1 in Fortran) pi arrays Set the value of nzmax tobe greater than or equal to the number of nonzero elements you plan to put into themxArray but make sure that nzmax is less than or equal to mn nzmax is greaterthan or equal to 1

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

mxCreateSparse (C and Fortran)

1-409

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray In that case tryreducing nzmax m or n

DescriptionCall mxCreateSparse to create an unpopulated sparse double mxArray The returnedsparse mxArray contains no sparse information and cannot be passed as an argument toany MATLAB sparse functions To make the returned sparse mxArray useful initializethe pr ir jc and (if it exists) pi arrays

mxCreateSparse allocates space for

bull A pr array of length nzmaxbull A pi array of length nzmax but only if ComplexFlag is mxCOMPLEX in C (1 in

Fortran)bull An ir array of length nzmaxbull A jc array of length n+1

When you finish using the sparse mxArray call mxDestroyArray to reclaim all its heapspace

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

1 API Reference

1-410

See AlsomxDestroyArray mxSetNzmax mxSetPr mxSetPi mxSetIr mxSetJcmxComplexity

Introduced before R2006a

mxCreateSparse (C and Fortran)

1-411

mxCreateSparseLogicalMatrix (C)2-D sparse logical array

C Syntaxinclude matrixhmxArray mxCreateSparseLogicalMatrix(mwSize m mwSize n mwSize nzmax)

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparseLogicalMatrix should allocate to holdthe data Set the value of nzmax to be greater than or equal to the number of nonzeroelements you plan to put into the mxArray but make sure that nzmax is less than orequal to mn nzmax is greater than or equal to 1

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

1 API Reference

1-412

DescriptionUse mxCreateSparseLogicalMatrix to create an m-by-n mxArray of mxLogicalelements mxCreateSparseLogicalMatrix initializes each element in the array tological 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its elements

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxCreateSparse mxIsLogical

Introduced before R2006a

mxCreateSparseLogicalMatrix (C)

1-413

mxCreateString (C and Fortran)1-N array initialized to specified string

C Syntaxinclude matrixhmxArray mxCreateString(const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateString(str)character() str

Argumentsstr

String used to initialize mxArray data Only ASCII characters are supported

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateString to create an mxArray initialized to str Many MATLAB functions(for example strcmp and upper) require string array inputs

1 API Reference

1-414

mxCreateString supports both multi-byte and single-byte encoded characters OnWindows and Linux platforms the default encoding is specified by the user localesetting

Free the mxArray when you are finished using it by calling mxDestroyArray

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull revordcbull revordF

See the following examples in matlabrootexternexamplesmx

bull mxcreatestructarraycbull mxisclassc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxCreateCharMatrixFromStrings mxCreateCharArray

Introduced before R2006a

mxCreateString (C and Fortran)

1-415

mxCreateStructArray (C and Fortran)N-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructArray(mwSize ndim const mwSize dims int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructArray(ndim dims nfields fieldnames)mwSize ndimmwSize dims(ndim)integer4 nfieldscharacter() fieldnames(nfields)

Argumentsndim

Number of dimensions If you set ndim to be less than 2 mxCreateStructArraycreates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Typically the dims array should have ndim elements

nfieldsNumber of fields in each element Positive integer

fieldnamesList of field names Field names must be valid MATLAB identifiers which meansthey cannot be NULL or empty

1 API Reference

1-416

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateStructArray to create an unpopulated structure mxArray Each elementof a structure mxArray contains the same number of fields (specified in nfields) Eachfield has a name the list of names is specified in fieldnames A MATLAB structuremxArray is conceptually identical to an array of structs in the C language

Each field holds one mxArray pointer mxCreateStructArray initializes each field toNULL in C (0 in Fortran) Call mxSetField or mxSetFieldByNumber to place a non-NULL mxArray pointer in a field

When you finish using the returned structure mxArray call mxDestroyArray to reclaimits space

Any trailing singleton dimensions specified in the dims argument are automaticallyremoved from the resulting array For example if ndim equals 5 and dims equals [4 17 1 1] the resulting array is given the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

mxCreateStructArray (C and Fortran)

1-417

See AlsomxDestroyArray mxAddField mxRemoveField mxSetFieldmxSetFieldByNumber namelengthmax

Introduced before R2006a

1 API Reference

1-418

mxCreateStructMatrix (C and Fortran)2-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructMatrix(mwSize m mwSize n int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructMatrix(m n nfields fieldnames)mwSize m ninteger4 nfieldscharacter() fieldnames(nfields)

Argumentsm

Number of rows must be a positive integern

Number of columns must be a positive integernfields

Number of fields in each elementfieldnames

List of field names

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

mxCreateStructMatrix (C and Fortran)

1-419

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxCreateStructMatrix and mxCreateStructArray are almost identical The onlydifference is that mxCreateStructMatrix can create only two-dimensional mxArrayswhile mxCreateStructArray can create an mxArray having two or more dimensions

C ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray namelengthmax

Introduced before R2006a

1 API Reference

1-420

mxCreateUninitNumericArray (C)Uninitialized N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateUninitNumericArray(size_t ndim size_t dims mxClassID classid mxComplexity ComplexFlag)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateUninitNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericArray (C)

1-421

DescriptionCall mxCreateUninitNumericArray to create an N-dimensional mxArray in which alldata elements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericArray allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericMatrix mxCreateNumericArray

Introduced in R2015a

1 API Reference

1-422

mxCreateUninitNumericMatrix (C)Uninitialized 2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateUninitNumericMatrix(size_t m size_t n mxClassID classid mxComplexity ComplexFlag)

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericMatrix (C)

1-423

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreateuninitnumericmatrixc

DescriptionCall mxCreateUninitNumericMatrix to create a 2-D mxArray in which all dataelements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericMatrix allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-424

Introduced in R2015a

mxCreateUninitNumericMatrix (C)

1-425

mxDestroyArray (C and Fortran)Free dynamic memory allocated by MXCREATE functions

C Syntaxinclude matrixhvoid mxDestroyArray(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mxDestroyArray(pm)mwPointer pm

Argumentspm

Pointer to the mxArray to free If pm is a NULL pointer the function does nothing

DescriptionmxDestroyArray deallocates the memory occupied by the specified mxArray including

bull Characteristics fields of the mxArray such as size (m and n) and typebull Associated data arrays such as pr and pi for complex arrays and ir and jc for

sparse arraysbull Fields of structure arraysbull Cells of cell arrays

Do not call mxDestroyArray on an mxArray

bull returned in a left-side argument of a MEX file

1 API Reference

1-426

bull returned by the mxGetField or mxGetFieldByNumber functionsbull returned by the mxGetCell function

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexgetarrayc

See the following examples in matlabrootexternexamplesmx

bull mxisclasscbull mxcreatecellmatrixfF

See AlsomxCalloc mxMalloc mxFree mexMakeArrayPersistentmexMakeMemoryPersistent

Introduced before R2006a

mxDestroyArray (C and Fortran)

1-427

mxDuplicateArray (C and Fortran)Make deep copy of array

C Syntaxinclude matrixhmxArray mxDuplicateArray(const mxArray in)

Fortran Syntaxinclude fintrfhmwPointer mxDuplicateArray(in)mwPointer in

Argumentsin

Pointer to the mxArray you want to copy

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxDuplicateArray makes a deep copy of an array and returns a pointer to the copy Adeep copy refers to a copy in which all levels of data are copied For example a deep copyof a cell array copies each cell and the contents of each cell (if any)

1 API Reference

1-428

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxgetinfcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

Introduced before R2006a

mxDuplicateArray (C and Fortran)

1-429

mxFree (C and Fortran)Free dynamic memory allocated by mxCalloc mxMalloc mxRealloc mxArrayToString ormxArrayToUTF8String functions

C Syntaxinclude matrixhvoid mxFree(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mxFree(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of any memory parcel allocated by mxCalloc mxMalloc ormxRealloc If ptr is a NULL pointer the function does nothing

DescriptionmxFree deallocates heap space using the MATLAB memory management facility Thisfunction ensures correct memory management in error and abort (Ctrl+C) conditions

To deallocate heap space MATLAB applications in C should always call mxFree ratherthan the ANSI C free function

In MEX files but excluding MAT or engine standalone applications the MATLABmemory management facility maintains a list of all memory allocated by the followingfunctions

1 API Reference

1-430

bull mxCallocbull mxMallocbull mxReallocbull mxArrayToStringbull mxArrayToUTF8String

The memory management facility automatically deallocates all parcels managed by aMEX file when the MEX file completes and control returns to the MATLAB promptmxFree also removes the memory parcel from the memory management list of parcels

When mxFree appears in a MAT or engine standalone MATLAB application it simplydeallocates the contiguous heap space that begins at address ptr

In MEX files your use of mxFree depends on whether the specified memory parcel ispersistent or nonpersistent By default memory parcels created by mxCallocmxMalloc mxRealloc mxArrayToString and mxArrayToUTF8String arenonpersistent The memory management facility automatically frees all nonpersistentmemory whenever a MEX file completes Thus even if you do not call mxFree MATLABtakes care of freeing the memory for you Nevertheless it is good programming practiceto deallocate memory when you are through using it Doing so generally makes the entiresystem run more efficiently

If an application calls mexMakeMemoryPersistent the specified memory parcelbecomes persistent When a MEX file completes the memory management facility doesnot free persistent memory parcels Therefore the only way to free a persistent memoryparcel is to call mxFree Typically MEX files call mexAtExit to register a cleanuphandler The cleanup handler calls mxFree

Do not use mxFree for an mxArray created by any other functions in the Matrix LibraryAPI Use mxDestroyArray instead

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxcreatecharmatrixfromstrc

mxFree (C and Fortran)

1-431

bull mxisfinitecbull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxMalloc mxRealloc mxArrayToString mxArrayToUTF8String

Introduced before R2006a

1 API Reference

1-432

mxGetCell (C and Fortran)Pointer to element in cell array

C Syntaxinclude matrixhmxArray mxGetCell(const mxArray pm mwIndex index)

Fortran Syntaxinclude fintrfhmwPointer mxGetCell(pm index)mwPointer pmmwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Number of elements in the cell mxArray between the first element and the desiredone See mxCalcSingleSubscript for details on calculating an index in amultidimensional cell array

ReturnsPointer to the ith cell mxArray if successful Otherwise returns NULL in C (0 inFortran) Causes of failure include

bull Specifying the index of a cell array element that has not been populatedbull Specifying a pm that does not point to a cell mxArray

mxGetCell (C and Fortran)

1-433

bull Specifying an index to an element outside the bounds of the mxArraybull Insufficient heap space

Do not call mxDestroyArray on an mxArray returned by the mxGetCell function

DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexed element of the cellmxArray

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCellArray mxIsCell mxSetCell

Introduced before R2006a

1 API Reference

1-434

mxGetChars (C)Pointer to character array data

C Syntaxinclude matrixhmxChar mxGetChars(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first character in the mxArray Returns NULL if the specified array is not acharacter array

DescriptionCall mxGetChars to access the first character in the mxArray that array_ptr points toOnce you have the starting address you can access any other element in the mxArray

See AlsomxGetString

Introduced before R2006a

mxGetChars (C)

1-435

mxGetClassID (C and Fortran)Class of array

C Syntaxinclude matrixhmxClassID mxGetClassID(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetClassID(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumeric identifier of the class (category) of the mxArray that pm points to For a list ofC-language class identifiers see the mxClassID reference page For user-defined typesmxGetClassId returns a unique value identifying the class of the array contents UsemxIsClass to determine whether an array is of a specific user-defined type

DescriptionUse mxGetClassId to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray then mxGetClassId returns mxLOGICAL_CLASS (in C)

1 API Reference

1-436

mxGetClassId is like mxGetClassName except that the former returns the class as aninteger identifier and the latter returns the class as a string

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxClassID mxGetClassName mxIsClass

Introduced before R2006a

mxGetClassID (C and Fortran)

1-437

mxGetClassName (C and Fortran)Class of array as string

Note Use mxGetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhconst char mxGetClassName(const mxArray pm)

Fortran Syntaxinclude fintrfhcharacter() mxGetClassName(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsClass (as a string) of the mxArray pointed to by pm

DescriptionCall mxGetClassName to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray mxGetClassName returns logical

1 API Reference

1-438

mxGetClassID is like mxGetClassName except that the former returns the class as aninteger identifier as listed in the mxClassID reference page and the latter returns theclass as a string as listed in the mxIsClass reference page

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxGetClassID mxIsClass

Introduced before R2006a

mxGetClassName (C and Fortran)

1-439

mxGetData (C and Fortran)Pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxGetData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionIn C mxGetData returns a void pointer (void ) Since void pointers point to a valuethat has no type cast the return value to the pointer type that matches the type specifiedby pm To see how MATLAB types map to their equivalent C types see the table on themxClassID reference page

1 API Reference

1-440

In Fortran to copy values from the returned pointer use one of the mxCopyPtrTofunctions in the following manner

C Get the data in mxArray pm mxCopyPtrToReal8(mxGetData(pm)data + mxGetNumberOfElements(pm))

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxisfinitec

See AlsomxGetImagData mxGetPr mxClassID

Introduced before R2006a

mxGetData (C and Fortran)

1-441

mxGetDimensions (C and Fortran)Pointer to dimensions array

C Syntaxinclude matrixhconst mwSize mxGetDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element in the dimensions array Each integer in the dimensionsarray represents the number of elements in a particular dimension The array is notNULL terminated

DescriptionUse mxGetDimensions to determine how many elements are in each dimension of themxArray that pm points to Call mxGetNumberOfDimensions to get the number ofdimensions in the mxArray

To copy the values to Fortran use mxCopyPtrToInteger4 in the following manner

1 API Reference

1-442

C Get dimensions of mxArray pm mxCopyPtrToInteger4(mxGetDimensions(pm) dims + mxGetNumberOfDimensions(pm))

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetNumberOfDimensions

Introduced before R2006a

mxGetDimensions (C and Fortran)

1-443

mxGetElementSize (C and Fortran)Number of bytes required to store each data element

C Syntaxinclude matrixhsize_t mxGetElementSize(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetElementSize(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of bytes required to store one element of the specified mxArray if successfulReturns 0 on failure The primary reason for failure is that pm points to an mxArrayhaving an unrecognized class If pm points to a cell mxArray or a structure mxArraymxGetElementSize returns the size of a pointer (not the size of all the elements in eachcell or structure field)

DescriptionCall mxGetElementSize to determine the number of bytes in each data element of themxArray For example if the MATLAB class of an mxArray is int16 the mxArray

1 API Reference

1-444

stores each data element as a 16-bit (2-byte) signed integer Thus mxGetElementSizereturns 2

mxGetElementSize is helpful when using a non-MATLAB routine to manipulate dataelements For example the C function memcpy requires (for its third argument) the sizeof the elements you intend to copy

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull doubleelementcbull phonebookc

See AlsomxGetM mxGetN

Introduced before R2006a

mxGetElementSize (C and Fortran)

1-445

mxGetEps (C and Fortran)Value of EPS

C Syntaxinclude matrixhdouble mxGetEps(void)

Fortran Syntaxreal8 mxGetEps

ReturnsValue of the MATLAB eps variable

DescriptionCall mxGetEps to return the value of the MATLAB eps variable This variable holds thedistance from 10 to the next largest floating-point number As such it is a measure offloating-point accuracy The MATLAB pinv and rank functions use eps as a defaulttolerance

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

1 API Reference

1-446

See AlsomxGetInf mxGetNan

Introduced before R2006a

mxGetEps (C and Fortran)

1-447

mxGetField (C and Fortran)Pointer to field value from structure array given index and field name

C Syntaxinclude matrixhmxArray mxGetField(const mxArray pm mwIndex index const char fieldname)

Fortran Syntaxinclude fintrfhmwPointer mxGetField(pm index fieldname)mwPointer pmmwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

fieldnameName of the field whose value you want to extract

1 API Reference

1-448

ReturnsPointer to the mxArray in the specified field at the specified fieldname on successReturns NULL in C (0 in Fortran) if passed an invalid argument or if there is no valueassigned to the specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray Todetermine whether pm points to a structure mxArray call mxIsStruct

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains 10 elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent fieldname Call mxGetFieldNameByNumber ormxGetFieldNumber to get existing field names

bull Insufficient heap space

DescriptionCall mxGetField to get the value held in the specified element of the specified field Inpseudo-C terminology mxGetField returns the value at

pm[index]fieldname

mxGetFieldByNumber is like mxGetField Both functions return the same value Theonly difference is in the way you specify the field mxGetFieldByNumber takes a fieldnumber as its third argument and mxGetField takes a field name as its thirdargument

Do not call mxDestroyArray on an mxArray returned by the mxGetField function

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

mxGetField(pa index field_name)

mxGetField (C and Fortran)

1-449

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where if you have a 1-by-1 structure index is 0

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where if you have a 1-by-1 structure index is 1

ExamplesSee the following example in matlabrootexternexampleseng_mat

bull matreadstructarrayc

See AlsomxGetFieldByNumber mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-450

mxGetFieldByNumber (C and Fortran)Pointer to field value from structure array given index and field number

C Syntaxinclude matrixhmxArray mxGetFieldByNumber(const mxArray pm mwIndex index int fieldnumber)

Fortran Syntaxinclude fintrfhmwPointer mxGetFieldByNumber(pm index fieldnumber)mwPointer pmmwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for more details on calculating an indexfieldnumber

Position of the field whose value you want to extract

mxGetFieldByNumber (C and Fortran)

1-451

In C the first field within each element has a field number of 0 the second field hasa field number of 1 and so on The last field has a field number of N-1 where N is thenumber of fields

In Fortran the first 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 field number of N whereN is the number of fields

ReturnsPointer to the mxArray in the specified field for the desired element on success ReturnsNULL in C (0 in Fortran) if passed an invalid argument or if there is no value assigned tothe specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains ten elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent field number Call mxGetFieldNumber to determine thefield number that corresponds to a given field name

DescriptionCall mxGetFieldByNumber to get the value held in the specified fieldnumber at theindexed element

Do not call mxDestroyArray on an mxArray returned by the mxGetFieldByNumberfunction

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

1 API Reference

1-452

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldByNumber (C and Fortran)

1-453

mxGetFieldNameByNumber (C and Fortran)Pointer to field name from structure array given field number

C Syntaxinclude matrixhconst char mxGetFieldNameByNumber(const mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhcharacter() mxGetFieldNameByNumber(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Position of the desired field For instance in C to get the name of the first field setfieldnumber to 0 to get the name of the second field set fieldnumber to 1 and soon In Fortran to get the name of the first field set fieldnumber to 1 to get thename of the second field set fieldnumber to 2 and so on

ReturnsPointer to the nth field name on success Returns NULL in C (0 in Fortran) on failureCommon causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

1 API Reference

1-454

bull Specifying a value of fieldnumber outside the bounds of the number of fields in thestructure mxArray In C fieldnumber 0 represents the first field andfieldnumber N-1 represents the last field where N is the number of fields in thestructure mxArray In Fortran fieldnumber 1 represents the first field andfieldnumber N represents the last field

DescriptionCall mxGetFieldNameByNumber to get the name of a field in the given structuremxArray A typical use of mxGetFieldNameByNumber is to call it inside a loop to get thenames of all the fields in a given mxArray

Consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test A field number other than 0 1 or 2causes mxGetFieldNameByNumber to return NULL

In Fortran the field number 1 represents the field name field number 2 represents fieldbilling field number 3 represents field test A field number other than 1 2 or 3causes mxGetFieldNameByNumber to return 0

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

mxGetFieldNameByNumber (C and Fortran)

1-455

bull explorec

See AlsomxGetField mxGetFieldByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-456

mxGetFieldNumber (C and Fortran)Field number from structure array given field name

C Syntaxinclude matrixhint mxGetFieldNumber(const mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxGetFieldNumber(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of a field in the structure mxArray

ReturnsField number of the specified fieldname on success In C the first field has a fieldnumber of 0 the second field has a field number of 1 and so on In Fortran the first fieldhas a field number of 1 the second field has a field number of 2 and so on Returns -1 inC (0 in Fortran) on failure Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

mxGetFieldNumber (C and Fortran)

1-457

bull 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 do not know its fieldname call mxGetFieldNameByNumber

For example consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field name has a field number of 0 the field billing has a field number of 1and the field test has a field number of 2 If you call mxGetFieldNumber and specify afield name of anything other than name billing or test mxGetFieldNumber returns-1

Calling

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran the field name has a field number of 1 the field billing has a field numberof 2 and the field test has a field number of 3 If you call mxGetFieldNumber andspecify a field name of anything other than name billing or testmxGetFieldNumber returns 0

Calling

mxGetField(pm index fieldname)

is equivalent to calling

1 API Reference

1-458

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxGetField mxGetFieldByNumber mxGetFieldNameByNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldNumber (C and Fortran)

1-459

mxGetImagData (C and Fortran)Pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxGetImagData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetImagData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the imaginary data Returns NULL in C (0 in Fortran) ifthere is no imaginary data or if there is an error

DescriptionThis function is like mxGetPi except that in C it returns a void For moreinformation see the description for the mxGetData function

1 API Reference

1-460

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxGetData mxGetPi

Introduced before R2006a

mxGetImagData (C and Fortran)

1-461

mxGetInf (C and Fortran)Value of infinity

C Syntaxinclude matrixhdouble mxGetInf(void)

Fortran Syntaxreal8 mxGetInf

ReturnsValue of infinity on your system

DescriptionCall mxGetInf to return the value of the MATLAB internal inf variable inf is apermanent variable representing IEEEreg arithmetic positive infinity Your systemspecifies the value of inf you cannot modify it

Operations that return infinity include

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-462

bull mxgetinfc

See AlsomxGetEps mxGetNaN

Introduced before R2006a

mxGetInf (C and Fortran)

1-463

mxGetIr (C and Fortran)Sparse matrix IR array

C Syntaxinclude matrixhmwIndex mxGetIr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetIr(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the ir array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetIr to obtain the starting address of the ir array The ir array is an array ofintegers The length of ir is nzmax the storage allocated for the sparse array or nnz

1 API Reference

1-464

the number of nonzero matrix elements For example if nzmax equals 100 the ir arraycontains 100 integers

Each value in an ir array indicates a row (offset by 1) at which a nonzero element can befound (The jc array is an index that indirectly specifies a column where nonzeroelements can be found)

For details on the ir and jc arrays see mxSetIr and mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetJc mxGetNzmax mxSetIr mxSetJc mxSetNzmax nzmax nnz

Introduced before R2006a

mxGetIr (C and Fortran)

1-465

mxGetJc (C and Fortran)Sparse matrix JC array

C Syntaxinclude matrixhmwIndex mxGetJc(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetJc(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the jc array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetJc to obtain the starting address of the jc array The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

1 API Reference

1-466

The values in the jc array indirectly indicate columns containing nonzero elements Fora detailed explanation of the jc array see mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetIr mxGetNzmax mxSetIr mxSetJc mxSetNzmax

Introduced before R2006a

mxGetJc (C and Fortran)

1-467

mxGetLogicals (C)Pointer to logical array data

C Syntaxinclude matrixhmxLogical mxGetLogicals(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first logical element in the mxArray The result is unspecified if themxArray is not a logical array

DescriptionCall mxGetLogicals to access the first logical element in the mxArray that array_ptrpoints to Once you have the starting address you can access any other element in themxArray

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxIsLogical mxIsLogicalScalar mxIsLogicalScalarTrue

Introduced before R2006a

1 API Reference

1-468

mxGetM (C and Fortran)Number of rows in array

C Syntaxinclude matrixhsize_t mxGetM(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetM(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of rows in the mxArray to which pm points

DescriptionmxGetM returns the number of rows in the specified array The term rows always meansthe first dimension of the array no matter how many dimensions the array has Forexample if pm points to a four-dimensional array having dimensions 8-by-9-by-5-by-3mxGetM returns 8

mxGetM (C and Fortran)

1-469

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull matrixDividecbull matrixDivideComplexcbull revordcbull timestwocbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull timestwoFbull xtimesyF

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-470

bull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomxGetN mxSetM mxSetN

Introduced before R2006a

mxGetM (C and Fortran)

1-471

mxGetN (C and Fortran)Number of columns in array

C Syntaxinclude matrixhsize_t mxGetN(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetN(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of columns in the mxArray

DescriptionCall mxGetN to determine the number of columns in the specified mxArray

If pm is an N-dimensional mxArray mxGetN is the product of dimensions 2 through NFor example if pm points to a four-dimensional mxArray having dimensions 13-by-5-by-4-by-6 mxGetN returns the value 120 (5 times 4 times 6) If the specified mxArray has morethan two dimensions and you need to know exactly how many elements are in eachdimension call mxGetDimensions

1 API Reference

1-472

If pm points to a sparse mxArray mxGetN still returns the number of columns not thenumber of occupied columns

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull revordcbull timestwocbull xtimesyc

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxGetN (C and Fortran)

1-473

See AlsomxGetM mxGetDimensions mxSetM mxSetN

Introduced before R2006a

1 API Reference

1-474

mxGetNaN (C and Fortran)Value of NaN (Not-a-Number)

C Syntaxinclude matrixhdouble mxGetNaN(void)

Fortran Syntaxreal8 mxGetNaN

ReturnsValue of NaN (Not-a-Number) on your system

DescriptionCall mxGetNaN to return the value of NaN for your system NaN is the IEEE arithmeticrepresentation for Not-a-Number Certain mathematical operations return NaN as aresult for example

bull 0000bull Inf-Inf

Your system specifies the value of Not-a-Number You cannot modify it

C ExamplesSee the following examples in matlabrootexternexamplesmx

mxGetNaN (C and Fortran)

1-475

bull mxgetinfc

See AlsomxGetEps mxGetInf

Introduced before R2006a

1 API Reference

1-476

mxGetNumberOfDimensions (C and Fortran)Number of dimensions in array

C Syntaxinclude matrixhmwSize mxGetNumberOfDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNumberOfDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of dimensions in the specified mxArray The returned value is always 2 orgreater

DescriptionUse mxGetNumberOfDimensions to determine how many dimensions are in thespecified array To determine how many elements are in each dimension callmxGetDimensions

mxGetNumberOfDimensions (C and Fortran)

1-477

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsecbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See AlsomxSetM mxSetN mxGetDimensions

Introduced before R2006a

1 API Reference

1-478

mxGetNumberOfElements (C and Fortran)Number of elements in array

C Syntaxinclude matrixhsize_t mxGetNumberOfElements(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetNumberOfElements(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of elements in the specified mxArray

DescriptionmxGetNumberOfElements tells you how many elements an array has For example ifthe dimensions of an array are 3-by-5-by-10 mxGetNumberOfElements returns thenumber 150

mxGetNumberOfElements (C and Fortran)

1-479

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxgetepsfFbull mxgetinfcbull mxisfinitecbull mxsetdimensionscbull mxsetdimensionsfF

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetDimensions mxGetM mxGetN mxGetClassID mxGetClassName

Introduced before R2006a

1 API Reference

1-480

mxGetNumberOfFields (C and Fortran)Number of fields in structure array

C Syntaxinclude matrixhint mxGetNumberOfFields(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetNumberOfFields(pm)mwPointer pm

Argumentspm

Pointer to a structure mxArray

ReturnsNumber of fields on success Returns 0 on failure The most common cause of failure isthat pm is not a structure mxArray Call mxIsStruct to determine whether pm is astructure

DescriptionCall mxGetNumberOfFields to determine how many fields are in the specified structuremxArray

Once you know the number of fields in a structure you can loop through every field to setor to get field values

mxGetNumberOfFields (C and Fortran)

1-481

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxIsStruct mxSetField

Introduced before R2006a

1 API Reference

1-482

mxGetNzmax (C and Fortran)Number of elements in IR PR and PI arrays

C Syntaxinclude matrixhmwSize mxGetNzmax(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNzmax(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsNumber of elements allocated to hold nonzero entries in the specified sparse mxArray onsuccess Returns an indeterminate value on error The most likely cause of failure is thatpm points to a full (nonsparse) mxArray

DescriptionUse mxGetNzmax to get the value of the nzmax field The nzmax field holds an integervalue that signifies the number of elements in the ir pr and if it exists the pi arraysThe value of nzmax is always greater than or equal to the number of nonzero elements ina sparse mxArray In addition the value of nzmax is always less than or equal to thenumber of rows times the number of columns

mxGetNzmax (C and Fortran)

1-483

As you adjust the number of nonzero elements in a sparse mxArray MATLAB softwareoften adjusts the value of the nzmax field MATLAB adjusts nzmax to reduce the numberof costly reallocations and to optimize its use of heap space

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetnzmaxc

See AlsomxSetNzmax

Introduced before R2006a

1 API Reference

1-484

mxGetPi (C and Fortran)Imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPi(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPi(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the imaginary data elements of the specified mxArray on success ReturnsNULL in C (0 in Fortran) if there is no imaginary data or if there is an error

DescriptionUse mxGetPi on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetImagData

The pi field points to an array containing the imaginary data of the mxArray CallmxGetPi to get the contents of the pi field that is to get the starting address of thisimaginary data

mxGetPi (C and Fortran)

1-485

The best way to determine whether an mxArray is purely real is to call mxIsComplex

If any of the input matrices to a function are complex MATLAB allocates the imaginaryparts of all input matrices

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull fulltosparsec

For Fortran examples see

bull convecF

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetinfcbull mxisfinitecbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexcallmatlabc

See AlsomxGetPr mxSetPi mxSetPr mxGetImagData mxIsDouble

Introduced before R2006a

1 API Reference

1-486

mxGetPr (C and Fortran)Real data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPr(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionUse mxGetPr on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetData

Call mxGetPr to access the real data in the mxArray that pm points to Once you havethe starting address you can access any other element in the mxArray

mxGetPr (C and Fortran)

1-487

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull arrayFillGetPrcbull conveccbull doubleelementcbull findnzcbull fulltosparsecbull matrixDividecbull matrixMultiplycbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull sincallFbull timestwoFbull xtimesyF

See AlsomxGetPi mxSetPi mxSetPr mxGetData mxIsDouble

Introduced before R2006a

1 API Reference

1-488

mxGetProperty (C and Fortran)Value of public property of MATLAB object

C Syntaxinclude matrixhmxArray mxGetProperty(const mxArray pa mwIndex index const char propname)

Fortran Syntaxinclude fintrfhmwPointer mxGetProperty(pa index propname)mwPointer pamwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you want to extract

mxGetProperty (C and Fortran)

1-489

ReturnsPointer to the mxArray of the specified propname on success Returns NULL in C (0 inFortran) if unsuccessful Common causes of failure include

bull Specifying a nonexistent propnamebull Specifying a nonpublic propnamebull Specifying an index to an element outside the bounds of the mxArray To test the

index value use mxGetNumberOfElements or mxGetM and mxGetNbull Insufficient heap space

DescriptionCall mxGetProperty to get the value held in the specified element In pseudo-Cterminology mxGetProperty returns the value at

pa[index]propname

mxGetProperty makes a copy of the value If the property uses a large amount ofmemory creating a copy might be a concern There must be sufficient memory (in theheap) to hold the copy of the value

Examples

Display Name Property of timeseries Object

Create a MEX file disppropertyc in a folder on your MATLAB path================================================================= disppropertyc - Display timeseries Name property This is a MEX file for MATLAB Copyright 2013 The MathWorks Inc All rights reserved ================================================================= include mexh

void mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

1 API Reference

1-490

Check for proper number of arguments if(nrhs=1) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidNumInputs One input required) else if(nlhsgt1) mexErrMsgIdAndTxt( MATLABdisppropertymaxlhs Too many output arguments) Check for timeseries object if (mxIsClass(prhs[0] timeseries)) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidClass Input must be timeseries object) plhs[0] = mxGetProperty(prhs[0]0Name)

Build the MEX file

mex(-vdisppropertyc)

Create a timeseries object

ts = timeseries(rand(5 4)NameLaunchData)

Display name

tsname = dispproperty(ts)

tsname =LaunchData

Change Object Color

Open and build the mexgetpropertyc MEX file in the matlabrootexternexamplesmex folder

Limitationsbull mxGetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

mxGetProperty (C and Fortran)

1-491

See AlsomxSetProperty mxGetNumberOfElements mxGetM mxGetN

Introduced in R2008a

1 API Reference

1-492

mxGetScalar (C and Fortran)Real component of first data element in array

C Syntaxinclude matrixhdouble mxGetScalar(const mxArray pm)

Fortran Syntaxinclude fintrfhreal8 mxGetScalar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray cannot be a cell mxArray a structure mxArray or an emptymxArray

ReturnsThe value of the first real (nonimaginary) element of the mxArray

In C mxGetScalar returns a double If real elements in the mxArray are of a typeother than double then mxGetScalar automatically converts the scalar value into adouble To preserve the original data representation of the scalar cast the return valueto the desired data type

If pm points to a sparse mxArray then mxGetScalar returns the value of the firstnonzero real element in the mxArray If there are no nonzero elements then the functionreturns 0

mxGetScalar (C and Fortran)

1-493

DescriptionCall mxGetScalar to get the value of the first real (nonimaginary) element of themxArray

Usually you call mxGetScalar when pm points to an mxArray containing only oneelement (a scalar) However pm can point to an mxArray containing many elements Ifpm points to an mxArray containing multiple elements then the function returns thevalue of the first real element For example if pm points to a two-dimensional mxArraythen mxGetScalar returns the value of the (11) element If pm points to a three-dimensional mxArray then the function returns the value of the (111) element andso on

Use mxGetScalar on a nonempty mxArray of type numeric logical or char only To testfor these conditions use Matrix Library functions such as mxIsEmpty mxIsLogicalmxIsNumeric or mxIsChar

If the input value to mxGetScalar is type int64 or uint64 then the value might loseprecision if it is greater than flintmax

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull timestwoaltcbull xtimesyc

See the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

1 API Reference

1-494

See AlsomxGetM mxGetN mxIsScalar

mxGetScalar (C and Fortran)

1-495

mxGetString (C and Fortran)mxChar array to C-style string or Fortran character array

C Syntaxinclude matrixhint mxGetString(const mxArray pm char str mwSize strlen)

Fortran Syntaxinclude fintrfhinteger4 mxGetString(pm str strlen)mwPointer pmcharacter() strmwSize strlen

Argumentspm

Pointer to an mxChar arraystr

Starting location mxGetString writes the character data into str and then in Cterminates the string with a NULL character (in the manner of C strings) str canpoint to either dynamic or static memory

strlenSize in bytes of destination buffer pointed to by str Typically in C you set strlento 1 plus the number of elements in the mxArray to which pm points To get thenumber of elements use mxGetM or mxGetN

Do not use with ldquoMultibyte Encoded Charactersrdquo on page 1-497

1 API Reference

1-496

Returns0 on success or if strlen == 0 and 1 on failure Possible reasons for failure include

bull mxArray is not an mxChar arraybull strlen is not large enough to store the entire mxArray If so the function returns 1

and truncates the string

DescriptionCall mxGetString to copy the character data of an mxArray into a C-style string in C ora character array in Fortran The copied data starts at str and contains no more thanstrlen-1 characters in C (no more than strlen characters in Fortran) In C the C-style string is always terminated with a NULL character

If the array contains multiple rows the function copies them into a single array onecolumn at a time

Multibyte Encoded Characters

Use this function only with characters represented in single-byte encoding schemes Forcharacters represented in multibyte encoding schemes use the C functionmxArrayToString Fortran users must allocate sufficient space for the return string toavoid possible truncation

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmallocc

See the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

mxGetString (C and Fortran)

1-497

bull revordF

See AlsomxArrayToString mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetChars

Introduced before R2006a

1 API Reference

1-498

mxIsCell (C and Fortran)Determine whether input is cell array

C Syntaxinclude matrixhbool mxIsCell(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsCell(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCELL_CLASS and logical 0(false) otherwise

DescriptionUse mxIsCell to determine whether the specified array is a cell array

In C calling mxIsCell is equivalent to calling

mxGetClassID(pm) == mxCELL_CLASS

mxIsCell (C and Fortran)

1-499

In Fortran calling mxIsCell is equivalent to calling

mxGetClassName(pm) eq cell

Note mxIsCell does not answer the question ldquoIs this mxArray a cell of a cell arrayrdquo Anindividual cell of a cell array can be of any type

See AlsomxIsClass

Introduced before R2006a

1 API Reference

1-500

mxIsChar (C and Fortran)Determine whether input is mxChar array

C Syntaxinclude matrixhbool mxIsChar(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsChar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCHAR_CLASS and logical 0(false) otherwise

DescriptionUse mxIsChar to determine whether pm points to an mxChar array

In C calling mxIsChar is equivalent to calling

mxGetClassID(pm) == mxCHAR_CLASS

mxIsChar (C and Fortran)

1-501

In Fortran calling mxIsChar is equivalent to calling

mxGetClassName(pm) eq char

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull revordc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxmallocc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxIsClass mxGetClassID

Introduced before R2006a

1 API Reference

1-502

mxIsClass (C and Fortran)Determine whether array is object of specified class

C Syntaxinclude matrixhbool mxIsClass(const mxArray pm const char classname)

Fortran Syntaxinclude fintrfhinteger4 mxIsClass(pm classname)mwPointer pmcharacter() classname

Argumentspm

Pointer to an mxArrayclassname

Array category to test Specify classname as a string (not as an integer identifier)You can specify any one of the following predefined constants

Value of classname Corresponding Classcell mxCELL_CLASSchar mxCHAR_CLASSdouble mxDOUBLE_CLASSfunction_handle mxFUNCTION_CLASSint8 mxINT8_CLASSint16 mxINT16_CLASS

mxIsClass (C and Fortran)

1-503

Value of classname Corresponding Classint32 mxINT32_CLASSint64 mxINT64_CLASSlogical mxLOGICAL_CLASSsingle mxSINGLE_CLASSstruct mxSTRUCT_CLASSuint8 mxUINT8_CLASSuint16 mxUINT16_CLASSuint32 mxUINT32_CLASSuint64 mxUINT64_CLASSltclass_namegt ltclass_idgt

unknown mxUNKNOWN_CLASS

In the table ltclass_namegt represents the name of a specific MATLAB custom objectYou can also specify one of your own class names

ReturnsLogical 1 (true) if pm points to an array having category classname and logical 0(false) otherwise

DescriptionEach mxArray is tagged as being a certain type Call mxIsClass to determine whetherthe specified mxArray has this type MATLAB does not check if the class is derived froma base class

In C

mxIsClass(pm double)

is equivalent to calling either of these forms

1 API Reference

1-504

mxIsDouble(pm)

strcmp(mxGetClassName(pm) double)

In Fortran

mxIsClass(pm double)

is equivalent to calling either one of the following

mxIsDouble(pm)

mxGetClassName(pm) eq double

It is most efficient to use the mxIsDouble form

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxClassID mxGetClassID mxIsEmpty mxGetClassName

Introduced before R2006a

mxIsClass (C and Fortran)

1-505

mxIsComplex (C and Fortran)Determine whether data is complex

C Syntaxinclude matrixhbool mxIsComplex(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsComplex(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm is a numeric array containing complex data and logical 0 (false)otherwise If pm points to a cell array or a structure array mxIsComplex returns false

DescriptionUse mxIsComplex to determine whether an imaginary part is allocated for an mxArrayIf an mxArray is purely real and does not have any imaginary data the imaginarypointer pi is NULL in C (0 in Fortran) If an mxArray is complex pi points to an array ofnumbers

1 API Reference

1-506

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxgetinfc

See the following examples in matlabrootexternexamplesrefbook

bull conveccbull convecFbull fulltosparseFbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorecbull yprimecbull mexlockc

See AlsomxIsNumeric

Introduced before R2006a

mxIsComplex (C and Fortran)

1-507

mxIsDouble (C and Fortran)Determine whether mxArray represents data as double-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsDouble(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsDouble(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as double-precision floating-pointnumbers and logical 0 (false) otherwise

DescriptionCall mxIsDouble to determine whether the specified mxArray represents its real andimaginary data as double-precision floating-point numbers

Older versions of MATLAB software store all mxArray data as double-precision floating-point numbers However starting with MATLAB Version 5 software MATLAB can storereal and imaginary data in various numerical formats

1 API Reference

1-508

In C calling mxIsDouble is equivalent to calling

mxGetClassID(pm) == mxDOUBLE_CLASS

In Fortran calling mxIsDouble is equivalent to calling

mxGetClassName(pm) eq double

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsDouble (C and Fortran)

1-509

mxIsEmpty (C and Fortran)Determine whether array is empty

C Syntaxinclude matrixhbool mxIsEmpty(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsEmpty(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is empty and logical 0 (false) otherwise

DescriptionUse mxIsEmpty to determine whether an mxArray contains no data An mxArray isempty if the size of any of its dimensions is 0

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-510

bull mxisfinitec

See AlsomxIsClass

Introduced before R2006a

mxIsEmpty (C and Fortran)

1-511

mxIsFinite (C and Fortran)Determine whether input is finite

C Syntaxinclude matrixhbool mxIsFinite(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsFinite(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is finite and logical 0 (false) otherwise

DescriptionCall mxIsFinite to determine whether value is finite A number is finite if it is greaterthan -Inf and less than Inf

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-512

bull mxisfinitec

See AlsomxIsInf mxIsNan

Introduced before R2006a

mxIsFinite (C and Fortran)

1-513

mxIsFromGlobalWS (C and Fortran)Determine whether array was copied from MATLAB global workspace

C Syntaxinclude matrixhbool mxIsFromGlobalWS(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsFromGlobalWS(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array was copied out of the global workspace and logical 0(false) otherwise

DescriptionmxIsFromGlobalWS is useful for standalone MAT-file programs

1 API Reference

1-514

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnsc

Introduced before R2006a

mxIsFromGlobalWS (C and Fortran)

1-515

mxIsInf (C and Fortran)Determine whether input is infinite

C Syntaxinclude matrixhbool mxIsInf(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsInf(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is infinite and logical 0 (false) otherwise

DescriptionCall mxIsInf to determine whether value is equal to infinity or minus infinityMATLAB software stores the value of infinity in a permanent variable named Inf whichrepresents IEEE arithmetic positive infinity The value of the variable Inf is built intothe system you cannot modify it

Operations that return infinity include

1 API Reference

1-516

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

If value equals NaN (Not-a-Number) mxIsInf returns false In other words NaN is notequal to infinity

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxIsFinite mxIsNaN

Introduced before R2006a

mxIsInf (C and Fortran)

1-517

mxIsInt16 (C and Fortran)Determine whether array represents data as signed 16-bit integers

C Syntaxinclude matrixhbool mxIsInt16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt16 to determine whether the specified array represents its real andimaginary data as 16-bit signed integers

In C calling mxIsInt16 is equivalent to calling

mxGetClassID(pm) == mxINT16_CLASS

1 API Reference

1-518

In Fortran calling mxIsInt16 is equivalent to calling

mxGetClassName(pm) == int16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt16 (C and Fortran)

1-519

mxIsInt32 (C and Fortran)Determine whether array represents data as signed 32-bit integers

C Syntaxinclude matrixhbool mxIsInt32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt32 to determine whether the specified array represents its real andimaginary data as 32-bit signed integers

In C calling mxIsInt32 is equivalent to calling

mxGetClassID(pm) == mxINT32_CLASS

1 API Reference

1-520

In Fortran calling mxIsInt32 is equivalent to calling

mxGetClassName(pm) == int32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt32 (C and Fortran)

1-521

mxIsInt64 (C and Fortran)Determine whether array represents data as signed 64-bit integers

C Syntaxinclude matrixhbool mxIsInt64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt64 to determine whether the specified array represents its real andimaginary data as 64-bit signed integers

In C calling mxIsInt64 is equivalent to calling

mxGetClassID(pm) == mxINT64_CLASS

1 API Reference

1-522

In Fortran calling mxIsInt64 is equivalent to calling

mxGetClassName(pm) == int64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt64 (C and Fortran)

1-523

mxIsInt8 (C and Fortran)Determine whether array represents data as signed 8-bit integers

C Syntaxinclude matrixhbool mxIsInt8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 8-bit integers and logical 0 (false)otherwise

DescriptionUse mxIsInt8 to determine whether the specified array represents its real andimaginary data as 8-bit signed integers

In C calling mxIsInt8 is equivalent to calling

mxGetClassID(pm) == mxINT8_CLASS

1 API Reference

1-524

In Fortran calling mxIsInt8 is equivalent to calling

mxGetClassName(pm) eq int8

See AlsomxIsClass mxGetClassID mxIsInt16 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt8 (C and Fortran)

1-525

mxIsLogical (C and Fortran)Determine whether array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogical(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsLogical(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a logical mxArray Otherwise it returns logical 0(false)

DescriptionUse mxIsLogical to determine whether MATLAB software treats the data in themxArray as Boolean (logical) If an mxArray is logical MATLAB treats all zeros asmeaning false and all nonzero values as meaning true

1 API Reference

1-526

See AlsomxIsClass

TopicsldquoLogical Operationsrdquo

Introduced before R2006a

mxIsLogical (C and Fortran)

1-527

mxIsLogicalScalar (C)Determine whether scalar array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogicalScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is of class mxLogical and has 1-by-1 dimensionsOtherwise it returns logical 0 (false)

DescriptionUse mxIsLogicalScalar to determine whether MATLAB treats the scalar data in themxArray as logical or numerical

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalarTrue

TopicsldquoLogical Operationsrdquo

1 API Reference

1-528

Introduced before R2006a

mxIsLogicalScalar (C)

1-529

mxIsLogicalScalarTrue (C)Determine whether scalar array of type mxLogical is true

C Syntaxinclude matrixhbool mxIsLogicalScalarTrue(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the value of the mxArray logical scalar element is true Otherwise itreturns logical 0 (false)

DescriptionUse mxIsLogicalScalarTrue to determine whether the value of a scalar mxArray istrue or false

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalar

TopicsldquoLogical Operationsrdquo

1 API Reference

1-530

Introduced before R2006a

mxIsLogicalScalarTrue (C)

1-531

mxIsNaN (C and Fortran)Determine whether input is NaN (Not-a-Number)

C Syntaxinclude matrixhbool mxIsNaN(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsNaN(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is NaN (Not-a-Number) and logical 0 (false) otherwise

DescriptionCall mxIsNaN to determine whether value is NaN NaN is the IEEE arithmeticrepresentation for Not-a-Number A NaN is obtained as a result of mathematicallyundefined operations such as

bull 0000bull Inf-Inf

1 API Reference

1-532

The system understands a family of bit patterns as representing NaN NaN is not a singlevalue it is a family of numbers that MATLAB software (and other IEEE-compliantapplications) uses to represent an error condition or missing data

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsec

See AlsomxIsFinite mxIsInf

Introduced before R2006a

mxIsNaN (C and Fortran)

1-533

mxIsNumeric (C and Fortran)Determine whether array is numeric

C Syntaxinclude matrixhbool mxIsNumeric(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsNumeric(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array can contain numeric data The following class IDs representstorage types for arrays that can contain numeric data

bull mxDOUBLE_CLASSbull mxSINGLE_CLASSbull mxINT8_CLASSbull mxUINT8_CLASSbull mxINT16_CLASSbull mxUINT16_CLASS

1 API Reference

1-534

bull mxINT32_CLASSbull mxUINT32_CLASSbull mxINT64_CLASSbull mxUINT64_CLASS

Logical 0 (false) if the array cannot contain numeric data

DescriptionCall mxIsNumeric to determine whether the specified array contains numeric data Ifthe specified array has a storage type that represents numeric data mxIsNumericreturns logical 1 (true) Otherwise mxIsNumeric returns logical 0 (false)

Call mxGetClassID to determine the exact storage type

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxGetClassID

Introduced before R2006a

mxIsNumeric (C and Fortran)

1-535

mxIsScalar (C)Determine whether array is scalar array

C Syntaxinclude matrixhbool mxIsScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray has 1-by-1 dimensions Otherwise it returns logical 0(false)

Note Only use mxIsScalar for mxArray classes with IDs documented by mxClassID

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxisscalarc

See AlsomxClassID | mxGetScalar

1 API Reference

1-536

Introduced in R2015a

mxIsScalar (C)

1-537

mxIsSingle (C and Fortran)Determine whether array represents data as single-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsSingle(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSingle(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as single-precision floating-point numbersand logical 0 (false) otherwise

DescriptionUse mxIsSingle to determine whether the specified array represents its real andimaginary data as single-precision floating-point numbers

In C calling mxIsSingle is equivalent to calling

mxGetClassID(pm) == mxSINGLE_CLASS

1 API Reference

1-538

In Fortran calling mxIsSingle is equivalent to calling

mxGetClassName(pm) eq single

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsSingle (C and Fortran)

1-539

mxIsSparse (C and Fortran)Determine whether input is sparse array

C Syntaxinclude matrixhbool mxIsSparse(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSparse(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a sparse mxArray and logical 0 (false) otherwise Afalse return value means that pm points to a full mxArray or that pm does not point to avalid mxArray

DescriptionUse mxIsSparse to determine whether pm points to a sparse mxArray Many routines(for example mxGetIr and mxGetJc) require a sparse mxArray as input

1 API Reference

1-540

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

See Alsosparse mxGetIr mxGetJc mxCreateSparse

Introduced before R2006a

mxIsSparse (C and Fortran)

1-541

mxIsStruct (C and Fortran)Determine whether input is structure array

C Syntaxinclude matrixhbool mxIsStruct(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsStruct(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a structure mxArray and logical 0 (false) otherwise

DescriptionUse mxIsStruct to determine whether pm points to a structure mxArray Many routines(for example mxGetFieldNameByNumber and mxSetField) require a structuremxArray as an argument

1 API Reference

1-542

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldNameByNumbermxGetField mxSetField

Introduced before R2006a

mxIsStruct (C and Fortran)

1-543

mxIsUint16 (C and Fortran)Determine whether array represents data as unsigned 16-bit integers

C Syntaxinclude matrixhbool mxIsUint16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint16 to determine whether the specified mxArray represents its real andimaginary data as 16-bit unsigned integers

In C calling mxIsUint16 is equivalent to calling

mxGetClassID(pm) == mxUINT16_CLASS

1 API Reference

1-544

In Fortran calling mxIsUint16 is equivalent to calling

mxGetClassName(pm) eq uint16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint16 (C and Fortran)

1-545

mxIsUint32 (C and Fortran)Determine whether array represents data as unsigned 32-bit integers

C Syntaxinclude matrixhbool mxIsUint32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint32 to determine whether the specified mxArray represents its real andimaginary data as 32-bit unsigned integers

In C calling mxIsUint32 is equivalent to calling

mxGetClassID(pm) == mxUINT32_CLASS

1 API Reference

1-546

In Fortran calling mxIsUint32 is equivalent to calling

mxGetClassName(pm) eq uint32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint64

Introduced before R2006a

mxIsUint32 (C and Fortran)

1-547

mxIsUint64 (C and Fortran)Determine whether array represents data as unsigned 64-bit integers

C Syntaxinclude matrixhbool mxIsUint64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint64 to determine whether the specified mxArray represents its real andimaginary data as 64-bit unsigned integers

In C calling mxIsUint64 is equivalent to calling

mxGetClassID(pm) == mxUINT64_CLASS

1 API Reference

1-548

In Fortran calling mxIsUint64 is equivalent to calling

mxGetClassName(pm) eq uint64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint32

Introduced before R2006a

mxIsUint64 (C and Fortran)

1-549

mxIsUint8 (C and Fortran)Determine whether array represents data as unsigned 8-bit integers

C Syntaxinclude matrixhbool mxIsUint8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 8-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint8 to determine whether the specified mxArray represents its real andimaginary data as 8-bit unsigned integers

In C calling mxIsUint8 is equivalent to calling

mxGetClassID(pm) == mxUINT8_CLASS

1 API Reference

1-550

In Fortran calling mxIsUint8 is equivalent to calling

mxGetClassName(pm) eq uint8

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint8 (C and Fortran)

1-551

mxLogical (C)Type for logical array

DescriptionAll logical mxArrays store their data elements as mxLogical rather than as bool

The header file containing this type is

include matrixh

See AlsomxCreateLogicalArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

Introduced before R2006a

1 API Reference

1-552

mxMalloc (C and Fortran)Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxMalloc(mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxMalloc(n)mwSize n

Argumentsn

Number of bytes to allocate for n greater than 0

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxMalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxMalloc is unsuccessful when there is insufficient free heap space

If you call mxMalloc in C with value n = 0 MATLAB returns either NULL or a validpointer

mxMalloc (C and Fortran)

1-553

DescriptionmxMalloc allocates contiguous heap space sufficient to hold n bytes To allocate memoryin MATLAB applications use mxMalloc instead of the ANSI C malloc function

In MEX files but not MAT or engine applications mxMalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

1 API Reference

1-554

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxRealloc

Introduced before R2006a

mxMalloc (C and Fortran)

1-555

mxRealloc (C and Fortran)Reallocate dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxRealloc(void ptr mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxRealloc(ptr size)mwPointer ptrmwSize size

Argumentsptr

Pointer to a block of memory allocated by mxCalloc mxMalloc or mxReallocsize

New size of allocated memory in bytes

ReturnsPointer to the start of the reallocated block of memory if successful If unsuccessful in aMAT or engine standalone application mxRealloc returns NULL in C (0 in Fortran) andleaves the original memory block unchanged (Use mxFree to free the original memoryblock) If unsuccessful in a MEX file the MEX file terminates and control returns to theMATLAB prompt

mxRealloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-556

DescriptionmxRealloc changes the size of a memory block that has been allocated with mxCallocmxMalloc or mxRealloc To allocate memory in MATLAB applications use mxReallocinstead of the ANSI C realloc function

mxRealloc changes the size of the memory block pointed to by ptr to size bytes Thecontents of the reallocated memory are unchanged up to the smaller of the new and oldsizes The reallocated memory might be in a different location from the original memoryso the returned pointer can be different from ptr If the memory location changesmxRealloc frees the original memory block pointed to by ptr

If size is greater than 0 and ptr is NULL in C (0 in Fortran) mxRealloc behaves likemxMalloc mxRealloc allocates a new block of memory of size bytes and returns apointer to the new block

If size is 0 and ptr is not NULL in C (0 in Fortran) mxRealloc frees the memorypointed to by ptr and returns NULL in C (0 in Fortran)

In MEX files but not MAT or engine applications mxRealloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

mxRealloc (C and Fortran)

1-557

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxMalloc

Introduced before R2006a

1 API Reference

1-558

mxRemoveField (C and Fortran)Remove field from structure array

C Syntaxinclude matrixhvoid mxRemoveField(mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhsubroutine mxRemoveField(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Number of the field you want to remove In C to remove the first field setfieldnumber to 0 to remove the second field set fieldnumber to 1 and so on InFortran to remove the first field set fieldnumber to 1 to remove the second fieldset fieldnumber to 2 and so on

DescriptionCall mxRemoveField to remove a field from a structure array If the field does not existnothing happens This function does not destroy the field values To destroy the actualfield values call mxRemoveField and then call mxDestroyArray

Consider a MATLAB structure initialized to

mxRemoveField (C and Fortran)

1-559

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test In Fortran the field number 1represents the field name field number 2 represents field billing field number 3represents field test

See AlsomxAddField mxDestroyArray mxGetFieldByNumber

Introduced before R2006a

1 API Reference

1-560

mxSetCell (C and Fortran)Set contents of cell array

C Syntaxinclude matrixhvoid mxSetCell(mxArray pm mwIndex index mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetCell(pm index value)mwPointer pm valuemwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Index from the beginning of the mxArray Specify the number of elements betweenthe first cell of the mxArray and the cell you want to set The easiest way to calculateindex in a multidimensional cell array is to call mxCalcSingleSubscript

valuePointer to new value for the cell You can put an mxArray of any type into a cell Youcan even put another cell mxArray into a cell

DescriptionCall mxSetCell to put the designated value into a particular cell of a cell mxArray

mxSetCell (C and Fortran)

1-561

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxDestroyArray on the pointer returned by mxGetCellbefore you call mxSetCell

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray mxCreateCellMatrix mxGetCell mxIsCellmxDestroyArray

Introduced before R2006a

1 API Reference

1-562

mxSetClassName (C)Structure array to MATLAB object array

Note Use mxSetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhint mxSetClassName(mxArray array_ptr const char classname)

Argumentsarray_ptr

Pointer to an mxArray of class mxSTRUCT_CLASSclassname

Object class to which to convert array_ptr

Returns0 if successful and nonzero otherwise One cause of failure is that array_ptr is not astructure mxArray Call mxIsStruct to determine whether array_ptr is a structure

DescriptionmxSetClassName converts a structure array to an object array to be saved later to aMAT-file MATLAB does not register or validate the object until it is loaded by the LOADcommand If the specified classname is an undefined class within MATLAB LOADconverts the object back to a simple structure array

mxSetClassName (C)

1-563

See AlsomxIsClass mxGetClassID mxIsStruct

Introduced before R2006a

1 API Reference

1-564

mxSetData (C and Fortran)Set pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxSetData(mxArray pm void pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetData(pm pr)mwPointer pm pr

Argumentspm

Pointer to an mxArraypr

Pointer to an array Each element in the array contains the real component of avalue The array must be in dynamic memory call mxCalloc to allocate thismemory Do not use the ANSI C calloc function which can cause memoryalignment issues leading to program termination

DescriptionmxSetData is like mxSetPr except that in C its second argument is a void Use thisfunction on numeric arrays with contents other than double

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetData before you callmxSetData

mxSetData (C and Fortran)

1-565

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatac

See AlsomxCalloc mxFree mxGetData mxSetPr

Introduced before R2006a

1 API Reference

1-566

mxSetDimensions (C and Fortran)Modify number of dimensions and size of each dimension

C Syntaxinclude matrixhint mxSetDimensions(mxArray pm const mwSize dims mwSize ndim)

Fortran Syntaxinclude fintrfhinteger4 mxSetDimensions(pm dims ndim)mwPointer pmmwSize ndimmwSize dims(ndim)

Argumentspm

Pointer to an mxArraydims

Dimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray In most cases there are ndim elements in the dimsarray

ndimNumber of dimensions

mxSetDimensions (C and Fortran)

1-567

Returns0 on success and 1 on failure mxSetDimensions allocates heap space to hold the inputsize array So it is possible (though unlikely) that increasing the number of dimensionscan cause the system to run out of heap space

DescriptionCall mxSetDimensions to reshape an existing mxArray mxSetDimensions is likemxSetM and mxSetN however mxSetDimensions provides greater control for reshapingan mxArray that has more than two dimensions

mxSetDimensions does not allocate or deallocate any space for the pr or pi arrays Soif your call to mxSetDimensions increases the number of elements in the mxArrayenlarge the pr (and pi if it exists) arrays accordingly

If your call to mxSetDimensions reduces the number of elements in the mxArray youcan optionally reduce the size of the pr and pi arrays using mxRealloc

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetdimensionsfF

See AlsomxGetNumberOfDimensions mxSetM mxSetN mxRealloc

Introduced before R2006a

1 API Reference

1-568

mxSetField (C and Fortran)Set field value in structure array given index and field name

C Syntaxinclude matrixhvoid mxSetField(mxArray pm mwIndex index const char fieldname mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetField(pm index fieldname pvalue)mwPointer pm pvaluemwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of an element in the array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an index

mxSetField (C and Fortran)

1-569

fieldnameName of a field in the structure The field must exist in the structure CallmxGetFieldNameByNumber or mxGetFieldNumber to determine existing fieldnames

pvaluePointer to an mxArray containing the data you want to assign to fieldname

DescriptionUse mxSetField to assign the contents of pvalue to the field fieldname of elementindex

If you want to replace the contents of fieldname first free the memory of the existingdata Use the mxGetField function to get a pointer to the field call mxDestroyArray onthe pointer then call mxSetField to assign the new value

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then call mxSetFieldon each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

1 API Reference

1-570

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldmxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetFieldByNumber mxDestroyArray mxCalcSingleSubscript

Alternatives

C Language

In C you can replace the statements

field_num = mxGetFieldNumber(pa fieldname)mxSetFieldByNumber(pa index field_num new_value_pa)

with a call to mxSetField

mxSetField(pa index fieldname new_value_pa)

Fortran Language

In Fortran you can replace the statements

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

with a call to mxSetField

mxSetField(pm index fieldname newvalue)

Introduced before R2006a

mxSetField (C and Fortran)

1-571

mxSetFieldByNumber (C and Fortran)Set field value in structure array given index and field number

C Syntaxinclude matrixhvoid mxSetFieldByNumber(mxArray pm mwIndex index int fieldnumber mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetFieldByNumber(pm index fieldnumber pvalue)mwPointer pm pvaluemwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an indexfieldnumber

Position of the field in the structure The field must exist in the structure

1 API Reference

1-572

In C the first field within each element has a fieldnumber of 0 The fieldnumberof the last is N-1 where N is the number of fields

In Fortran the first field within each element has a fieldnumber of 1 Thefieldnumber of the last is N where N is the number of fields

pvaluePointer to the mxArray containing the data you want to assign

DescriptionUse mxSetFieldByNumber to assign the contents of pvalue to the field specified byfieldnumber of element index mxSetFieldByNumber is like mxSetField howeverthe function identifies the field by position number not by name

If you want to replace the contents at fieldnumber first free the memory of the existingdata Use the mxGetFieldByNumber function to get a pointer to the field callmxDestroyArray on the pointer then call mxSetFieldByNumber to assign the newvalue

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then callmxSetFieldByNumber on each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

mxSetFieldByNumber (C and Fortran)

1-573

Alternatives

C Language

In C calling

mxSetField(pa index field_name new_value_pa)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxSetFieldByNumber(pa index field_num new_value_pa)

Fortran Language

In Fortran calling

mxSetField(pm index fieldname newvalue)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldByNumbermxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxDestroyArray mxCalcSingleSubscript

Introduced before R2006a

1 API Reference

1-574

mxSetImagData (C and Fortran)Set pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxSetImagData(mxArray pm void pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetImagData(pm pi)mwPointer pm pi

Argumentspm

Pointer to an mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory errors will result when the array is destroyed

DescriptionmxSetImagData is like mxSetPi except that in C its pi argument is a void Usethis function on numeric arrays with contents other than double

mxSetImagData (C and Fortran)

1-575

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetImagData beforeyou call mxSetImagData

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxCalloc mxFree mxGetImagData mxSetPi

Introduced before R2006a

1 API Reference

1-576

mxSetIr (C and Fortran)IR array of sparse array

C Syntaxinclude matrixhvoid mxSetIr(mxArray pm mwIndex ir)

Fortran Syntaxinclude fintrfhsubroutine mxSetIr(pm ir)mwPointer pm ir

Argumentspm

Pointer to a sparse mxArrayir

Pointer to the ir array The ir array must be sorted in column-major order

DescriptionUse mxSetIr to specify the ir array of a sparse mxArray The ir array is an array ofintegers the length of the ir array equals the value of nzmax the storage allocated forthe sparse array or nnz the number of nonzero matrix elements

Each element in the ir array indicates a row (offset by 1) at which a nonzero elementcan be found (The jc array is an index that indirectly specifies a column where nonzeroelements can be found See mxSetJc for more details on jc)

mxSetIr (C and Fortran)

1-577

For example suppose that you create a 7-by-3 sparse mxArray named Sparrowcontaining six nonzero elements by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The pr array holds the real data for the sparse matrix which in Sparrow is the five 1sand the one 2 If there is any nonzero imaginary data it is in a pi arraySubscript ir pr jc Comments(21) 1 1 0 Column 1 ir is 1 because row is 2(51) 4 1 2 Column 1 ir is 4 because row is 5(32) 2 1 3 Column 2 ir is 2 because row is 3(23) 1 2 6 Column 3 ir is 1 because row is 2(53) 4 1 Column 3 ir is 4 because row is 5(63) 5 1 Column 3 ir is 5 because row is 6

Notice how each element of the ir array is always 1 less than the row of thecorresponding nonzero element For instance the first nonzero element is in row 2therefore the first element in ir is 1 (that is 2 ndash 1) The second nonzero element is inrow 5 therefore the second element in ir is 4 (5 ndash 1)

The ir array must be in column-major order The ir array must define the row positionsin column 1 (if any) first then the row positions in column 2 (if any) second and so onthrough column N Within each column row position 1 must appear before row position2 and so on

mxSetIr does not sort the ir array for you you must specify an ir array that is alreadysorted

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetIr before you callmxSetIr

1 API Reference

1-578

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateSparse mxGetIr mxGetJc mxSetJc mxFree nzmax nnz

Introduced before R2006a

mxSetIr (C and Fortran)

1-579

mxSetJc (C and Fortran)JC array of sparse array

C Syntaxinclude matrixhvoid mxSetJc(mxArray pm mwIndex jc)

Fortran Syntaxinclude fintrfhsubroutine mxSetJc(pm jc)mwPointer pm jc

Argumentspm

Pointer to a sparse mxArrayjc

Pointer to the jc array

DescriptionUse mxSetJc to specify a new jc array for a sparse mxArray The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

If the jth column of the sparse mxArray has any nonzero elements

bull jc[j] is the index in ir pr and pi (if it exists) of the first nonzero element in thejth column

bull jc[j+1]-1 is the index of the last nonzero element in the jth column

1 API Reference

1-580

bull For the jth column of the sparse matrix jc[j] is the total number of nonzeroelements in all preceding columns

The number of nonzero elements in the jth column of the sparse mxArray is

jc[j+1] - jc[j]

For the jth column of the sparse mxArray jc[j] is the total number of nonzeroelements in all preceding columns The last element of the jc array jc[number ofcolumns] is equal to nnz which is the number of nonzero elements in the entire sparsemxArray

For example consider a 7-by-3 sparse mxArray named Sparrow containing six nonzeroelements created by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The following table lists the contents of the ir jc and pr arraysSubscript ir pr jc Comment(21) 1 1 0 Column 1 contains two nonzero

elements with rows designated byir[0] and ir[1]

(51) 4 1 2 Column 2 contains one nonzeroelement with row designated by ir[2]

(32) 2 1 3 Column 3 contains three nonzeroelements with rows designated byir[3]ir[4] and ir[5]

(23) 1 2 6 There are six nonzero elements in all(53) 4 1 (63) 5 1

mxSetJc (C and Fortran)

1-581

As an example of a much sparser mxArray consider a 1000-by-8 sparse mxArray namedSpacious containing only three nonzero elements The ir pr and jc arrays containthe values listed in this tableSubscript ir pr jc Comment(732) 72 1 0 Column 1 contains no nonzero

elements(503) 49 1 0 Column 2 contains one nonzero

element with row designated by ir[0](645) 63 1 1 Column 3 contains one nonzero

element with row designated by ir[1] 2 Column 4 contains no nonzero

elements 2 Column 5 contains one nonzero

element with row designated by ir[2] 3 Column 6 contains no nonzero

elements 3 Column 7 contains no nonzero

elements 3 Column 8 contains no nonzero

elements 3 There are three nonzero elements in all

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetJc before you callmxSetJc

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-582

See AlsomxCreateSparse mxGetIr mxGetJc mxSetIr mxFree

Introduced before R2006a

mxSetJc (C and Fortran)

1-583

mxSetM (C and Fortran)Set number of rows in array

C Syntaxinclude matrixhvoid mxSetM(mxArray pm mwSize m)

Fortran Syntaxinclude fintrfhsubroutine mxSetM(pm m)mwPointer pmmwSize m

Argumentspm

Pointer to an mxArraym

Number of rows

DescriptionCall mxSetM to set the number of rows in the specified mxArray The term rows meansthe first dimension of an mxArray regardless of the number of dimensions Call mxSetNto set the number of columns

You typically use mxSetM to change the shape of an existing mxArray The mxSetMfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So ifyour calls to mxSetM and mxSetN increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays Call mxRealloc to enlarge them

1 API Reference

1-584

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetN mxRealloc

Introduced before R2006a

mxSetM (C and Fortran)

1-585

mxSetN (C and Fortran)Set number of columns in array

C Syntaxinclude matrixhvoid mxSetN(mxArray pm mwSize n)

Fortran Syntaxinclude fintrfhsubroutine mxSetN(pm n)mwPointer pmmwSize n

Argumentspm

Pointer to an mxArrayn

Number of columns

DescriptionCall mxSetN to set the number of columns in the specified mxArray The term columnsalways means the second dimension of a matrix Calling mxSetN forces an mxArray tohave two dimensions For example if pm points to an mxArray having three dimensionscalling mxSetN reduces the mxArray to two dimensions

You typically use mxSetN to change the shape of an existing mxArray The mxSetNfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So if

1 API Reference

1-586

your calls to mxSetN and mxSetM increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetM

Introduced before R2006a

mxSetN (C and Fortran)

1-587

mxSetNzmax (C and Fortran)Set storage space for nonzero elements

C Syntaxinclude matrixhvoid mxSetNzmax(mxArray pm mwSize nzmax)

Fortran Syntaxinclude fintrfhsubroutine mxSetNzmax(pm nzmax)mwPointer pmmwSize nzmax

Argumentspm

Pointer to a sparse mxArraynzmax

Number of elements mxCreateSparse should allocate to hold the arrays pointed toby ir pr and pi (if it exists) Set nzmax greater than or equal to the number ofnonzero elements in the mxArray but set it to be less than or equal to the number ofrows times the number of columns If you specify an nzmax value of 0 mxSetNzmaxsets the value of nzmax to 1

DescriptionUse mxSetNzmax to assign a new value to the nzmax field of the specified sparsemxArray The nzmax field holds the maximum number of nonzero elements in the sparsemxArray

1 API Reference

1-588

The number of elements in the ir pr and pi (if it exists) arrays must be equal tonzmax Therefore after calling mxSetNzmax you must change the size of the ir pr andpi arrays To change the size of one of these arrays

1 Call mxRealloc with a pointer to the array setting the size to the new value ofnzmax

2 Call the appropriate mxSet routine (mxSetIr mxSetPr or mxSetPi) to establishthe new memory area as the current one

Ways to determine how large to make nzmax are

bull Set nzmax equal to or slightly greater than the number of nonzero elements in asparse mxArray This approach conserves precious heap space

bull Make nzmax equal to the total number of elements in an mxArray This approacheliminates (or at least reduces) expensive reallocations

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetNzmax mxRealloc

Introduced before R2006a

mxSetNzmax (C and Fortran)

1-589

mxSetPi (C and Fortran)Set new imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPi(mxArray pm double pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetPi(pm pi)mwPointer pm pi

Argumentspm

Pointer to a full (nonsparse) mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory leaks and other memory errors might result

DescriptionUse mxSetPi to set the imaginary data of the specified mxArray

Most mxCreate functions optionally allocate heap space to hold imaginary data If youtell an mxCreate function to allocate heap spacemdashfor example by setting theComplexFlag to mxCOMPLEX in C (1 in Fortran) or by setting pi to a non-NULL value in

1 API Reference

1-590

C (a nonzero value in Fortran)mdashyou do not ordinarily use mxSetPi to initialize thecreated mxArrays imaginary elements Rather you call mxSetPi to replace the initialimaginary values with new ones

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPi before you callmxSetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetImagData mxSetPr mxFree

Introduced before R2006a

mxSetPi (C and Fortran)

1-591

mxSetPr (C and Fortran)Set new real data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPr(mxArray pm double pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetPr(pm pr)mwPointer pm pr

Argumentspm

Pointer to a full (nonsparse) mxArraypr

Pointer to the first element of an array Each element in the array contains the realcomponent of a value The array must be in dynamic memory call mxCalloc toallocate this memory Do not use the ANSI C calloc function which can causememory alignment issues leading to program termination If pr points to staticmemory memory leaks and other memory errors can result

DescriptionUse mxSetPr to set the real data of the specified mxArray

All mxCreate calls allocate heap space to hold real data Therefore you do notordinarily use mxSetPr to initialize the real elements of a freshly created mxArrayRather you call mxSetPr to replace the initial real values with new ones

1 API Reference

1-592

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPr before you callmxSetPr

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

See the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetData mxSetPi mxFree

Introduced before R2006a

mxSetPr (C and Fortran)

1-593

mxSetProperty (C and Fortran)Set value of public property of MATLAB object

C Syntaxinclude matrixhvoid mxSetProperty(mxArray pa mwIndex index const char propname const mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetProperty(pa index propname value)mwPointer pa valuemwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you are assigning

valuePointer to the mxArray you are assigning

1 API Reference

1-594

DescriptionUse mxSetProperty to assign a value to the specified property In pseudo-Cterminology mxSetProperty performs the assignment

pa[index]propname = value

Property propname must be an existing public property and index must be within thebounds of the mxArray To test the index value use mxGetNumberOfElements ormxGetM and mxGetN functions

mxSetProperty makes a copy of the value before assigning it as the new property valueMaking a copy might be a concern if the property uses a large amount of memory Theremust be sufficient memory (in the heap) to hold the copy of the value

Limitationsbull mxSetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

See AlsomxGetProperty

Introduced in R2008a

mxSetProperty (C and Fortran)

1-595

Page 2: C and Fortran API Reference

How to Contact MathWorks

Latest news wwwmathworkscom

Sales and services wwwmathworkscomsales_and_services

User community wwwmathworkscommatlabcentral

Technical support wwwmathworkscomsupportcontact_us

Phone 508-647-7000

The MathWorks Inc3 Apple Hill DriveNatick MA 01760-2098

MATLABreg CC++ Fortran Javareg and Pythonreg API Referencecopy COPYRIGHT 1984ndash2017 by The MathWorks IncThe software described in this document is furnished under a license agreement The software may beused or copied only under the terms of the license agreement No part of this manual may be photocopiedor reproduced in any form without prior written consent from The MathWorks IncFEDERAL 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 ascommercial computer software or commercial computer software documentation as such terms are used ordefined in FAR 12212 DFARS Part 22772 and DFARS 252227-7014 Accordingly the terms andconditions of this Agreement and only those rights specified in this Agreement shall pertain to and governthe use modification reproduction release performance display and disclosure of the Program andDocumentation by the federal government (or other entity acquiring for or through the federalgovernment) and shall supersede any conflicting contractual terms or conditions If this License fails tomeet the governments needs or is inconsistent in any respect with federal procurement law thegovernment agrees to return the Program and Documentation unused to The MathWorks IncTrademarks

MATLAB and Simulink are registered trademarks of The MathWorks Inc Seewwwmathworkscomtrademarks for a list of additional trademarks Other product or brandnames may be trademarks or registered trademarks of their respective holdersPatents

MathWorks products are protected by one or more US patents Please seewwwmathworkscompatents for more information

Revision HistoryDecember 1996 First Printing New for MATLAB 5 (Release 8)May 1997 Online only Revised for MATLAB 51 (Release 9)January 1998 Online Only Revised for MATLAB 52 (Release 10)January 1999 Online Only Revised for MATLAB 53 (Release 11)September 2000 Online Only Revised for MATLAB 60 (Release 12)June 2001 Online only Revised for MATLAB 61 (Release 121)July 2002 Online only Revised for MATLAB 65 (Release 13)January 2003 Online only Revised for MATLAB 651 (Release 13SP1)June 2004 Online only Revised for MATLAB 70 (Release 14)October 2004 Online only Revised for MATLAB 701 (Release 14SP1)March 2005 Online only Revised for MATLAB 704 (Release 14SP2)September 2005 Online only Revised for MATLAB 71 (Release 14SP3)March 2006 Online only Revised for MATLAB 72 (Release 2006a)September 2006 Online only Revised for MATLAB 73 (Release 2006b)March 2007 Online only Revised and renamed for MATLAB 74

(Release 2007a)September 2007 Online only Revised and renamed for MATLAB 75

(Release 2007b)March 2008 Online only Revised and renamed for MATLAB 76

(Release 2008a)October 2008 Online only Revised and renamed for MATLAB 77

(Release 2008b)March 2009 Online only Revised for MATLAB 78 (Release 2009a)September 2009 Online only Revised for MATLAB 79 (Release 2009b)March 2010 Online only Revised and renamed for MATLAB 710

(Release 2010a)September 2010 Online only Revised for MATLAB 711 (Release 2010b)April 2011 Online only Revised for MATLAB 712 (Release 2011a)September 2011 Online only Revised for MATLAB 713 (Release 2011b)March 2012 Online only Revised for MATLAB 714 (Release 2012a)September 2012 Online only Revised for MATLAB 80 (Release 2012b)March 2013 Online only Revised for MATLAB 81 (Release 2013a)September 2013 Online only Revised for MATLAB 82 (Release 2013b)March 2014 Online only Revised for MATLAB 83 (Release 2014a)October 2014 Online only Revised for MATLAB 84 (Release 2014b)March 2015 Online only Revised for MATLAB 85 (Release 2015a)September 2015 Online only Revised for MATLAB 86 (Release 2015b)March 2016 Online only Revised for MATLAB 90 (Release 2016a)September 2016 Online only Revised for MATLAB 91 (Release 2016b)March 2017 Online only Revised for MATLAB 92 (Release 2017a)September 2017 Online only Revised for MATLAB 93 (Release 2017b)

API Reference1

v

Contents

API Reference

1

matlabdataArrayDimensionsType specifying array dimensions

DescriptionUse the ArrayDimensions type to specify the size of an array ArrayDimensions isspecified as

using ArrayDimensions = stdvectorltsize_tgt

Free Function

getNumElementsinline size_t getNumElements(const ArrayDimensionsamp dims)

Determine the number of elements based on the ArrayDimensions

const ArrayDimensionsampdims

Array dimensions

inline size_t Number of elements

None

See Also

TopicsldquoMATLAB Data API Typesrdquo

1 API Reference

1-2

Introduced in R2017b

matlabdataArrayDimensions

1-3

matlabdataArrayElementRefC++ class representing element of Array or ReferenceltArraygt object

DescriptionAn ArrayElementRef object is created when using operator[] into an Array or aReferenceltArraygt It is untyped since Array and ReferenceltArraygt do not havetype information It collects up the indexes specified by the user and can be cast to anelement if the array holds primitive data or can be used to create a ReferenceltTgtinstance

Indexing is zero-based

Class DetailsNamespace matlabdataInclude ArrayElementRefhpp

Template Parametersbool is_const_ref Indicates if this reference is const The non-const

version of this class supports assignment

Other Operatorsbull ldquooperator[]rdquo on page 1-4bull ldquooperator Trdquo on page 1-5bull ldquooperator=rdquo on page 1-6

operator[]ArrayElementRefltis_const_refgt operator[](size_t idx)

ArrayElementRefltis_const_refgt operator[](stdstring idx)

1 API Reference

1-4

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indices in anindexing operation

stdstring idx Index to add Array must support string indexing

TooManyIndicesProvidedException

Too many indices provided The number of size_tindices is more than the number of dimensions in thearray

StringIndexMustBeLastException

String index is not the last index A size_t index isprovided after a string index

StringIndexNotValidException

An stdstring index is not valid for this array

CanOnlyUseOneStringIndexException

More than one stdstring index provided

double val = arr[2][7][f1]

operator Ttemplate lttypename Tgtoperator T() const

Cast a value Throws an error if not arithmetic complex or stdstring

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain the type specifiedby T

Array dblArray_const = factorycreateArrayltdoublegt(22)double val = dblArray_const[1][2]

matlabdataArrayElementRef

1-5

operator=template lttypename TgtArrayElementRefltis_const_refgtamp operator= (T rhs)

Assign a primitive or complex type to an element of an Array The Array must be non-const

If the Array contains other Arrays then operator= can assign an Array into theelement

T rhs The value to assign to an element in the Array specifiedas a primitive or complex type or as an Array

ArrayElementRefltis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain a primitive orcomplex type or does not contain other Arrays

Assign numeric types to Array arr

Array arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55arr[1][2] = stdcomplexltdoublegt(54 31)

Assign an Array to cell_arr then create a ReferenceltArraygt ref to the element

Array cell_arr = factorycreateArrayltArraygt(13)cell_arr[2] = factorycreateScalar(true)ReferenceltArraygt ref = cell_arr[2]

See AlsoArray | ArrayElementTypedRef | Reference | TypedArrayRef

1 API Reference

1-6

Introduced in R2017b

matlabdataArrayElementRef

1-7

matlabdataArrayElementTypedRefC++ class representing element of TypedArray or TypedArrayRef object

DescriptionAn ArrayElementTypedRef object is created when using operator[] into aTypedArrayltTgt or a TypedArrayRefltTgt It collects up the indexes specified by theuser and can be cast to ltTgt without the added cost of type checking that exists whenusing ArrayElementRef Primitive types can be cast to Tamp which is not supported withArrayElementRef The non-const version of this class supports assignment

Class DetailsNamespace matlabdataInclude ArrayElementTypedRefhpp

Template ParametersT Element typesbool is_const_ref TBD

Other Operatorsbull ldquooperator[]rdquo on page 1-8bull ldquooperator referencerdquo on page 1-9bull ldquooperator=rdquo on page 1-10

operator[]ArrayElementTypedRefltT is_const_refgt operator[](size_t idx)

ArrayElementTypedRefltArray is_const_refgt operator[](stdstringidx)

1 API Reference

1-8

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indicesin an indexing operation

stdstring idx Index to add Array must support string indexing

ArrayElementTypedRefltArray is_const_refgt

New instance with the additional index

TooManyIndicesProvidedException

Too many indices provided

StringIndexMustBeLastException

String index is not the last index

double val = arr[2][7][3]

operator referenceoperator reference() const

operator stdstring() const

Cast to reference to its primitive value

T

stdstring

The value

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

double val = dblArray[1][2]

stdstring val = strArray[1][2]

matlabdataArrayElementTypedRef

1-9

operator=ArrayElementTypedRefltT is_const_refgtamp operator= (T rhs)

ArrayElementTypedRefltT is_const_refgtamp operator= (stdstring rhs)

Assign a value into an Array The Array must be non-const

T rhs

stdstring rhs

Value to assign to an element in the Array

ArrayElementTypedRefltTis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

arr[1][2] = stdcomplexltdoublegt(54 31)

arr[1][2] = MyString

ExamplesTBD

TypedArrayltdoublegt arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55doubleamp val = arr[0][0]CellArray cell_arr = factorycreateArrayltArraygt(12)cell_arr[0] = factorycreateScalar(105)cell_arr[1] = factorycreateScalar(false)ArrayRef ref_to_element = cell_arr[0]TypedArrayRefltdoublegt typed_ref_to_element = cell_arr[0]

1 API Reference

1-10

Array const shared_copy_of_element = cell_arr[1]TypedArrayltboolgt const typed_shared_copy_of_element = cell_arr[1]

See AlsoArray | ArrayElementRef | ArrayElementTypedRef | Reference |TypedArrayRef | TypedIterator

Introduced in R2017b

matlabdataArrayElementTypedRef

1-11

matlabdataArrayFactoryC++ class to create arrays

DescriptionUse ArrayFactory to create matlabdataArray objects

Class DetailsNamespace matlabdataInclude ArrayFactoryhpp

Constructors

Default Constructor

ArrayFactory()

FailedToLoadLibMatlabDataArrayException

Concrete implementation has not been loaded

Destructor~ArrayFactory()

Member Functionsbull ldquocreateArrayrdquo on page 1-13bull ldquocreateScalarrdquo on page 1-14bull ldquocreateCellArrayrdquo on page 1-15

1 API Reference

1-12

bull ldquocreateCharArrayrdquo on page 1-16bull ldquocreateStructArrayrdquo on page 1-17bull ldquocreateEnumArrayrdquo on page 1-18bull ldquocreateSparseArrayrdquo on page 1-19bull ldquocreateEmptyArrayrdquo on page 1-20bull ldquocreateBufferrdquo on page 1-21bull ldquocreateArrayFromBufferrdquo on page 1-21

createArraytemplate lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims)

template lttypename ItType typename TgtTypedArrayltTgt createArray(ArrayDimensions dims ItType begin ItType end)

template lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims const T const begin const T const end)

template lttypename Tgt TypedArrayltTgt createArray(ArrayDimensions dims stdinitializer_listltTgt data)

Creates a TypedArrayltTgt with the given dimensions Fills the array with data ifspecified Data is copied and must be in column major order

bull ItType - Iterator types specified as stditeratorbull T - Element types specified as one of the following C++ data types

bool int8_t int16_t int32_t int64_t uint8_tuint16_t uint32_t uint64_t float double char16_t

matlabdataArrayFactory

1-13

matlabdataString

stdcomplexltdoublegt

stdcomplexltfloatgt

stdcomplexltint8_tgt

stdcomplexltuint8_tgt

stdcomplexltint16_tgt

stdcomplexltuint16_tgt

stdcomplexltint32_tgt

stdcomplexltuint32_tgt

stdcomplexltint64_tgt

stdcomplexltuint64_tgt

matlabdataMATLABString

ArrayDimensionsdims

Dimensions for the array

ItType begin

ItType end

Start and end of the user supplied data The data type isdetermined by the value_type of the iterator

const T constbegin

const T const end

Start and end of the user supplied data specified as C-stylepointer Supports all primitive types complex types andstring types

stdinitializer_listltTgt

Initializer list containing the data

matlabOutOfMemoryException

The array could not be allocated

createScalartemplate lttypename TgtTypedArrayltTgt createScalar(const T val)

TypedArrayltStringgt createScalar(const String val)

TypedArrayltStringgt createScalar(const stdstring val)

Creates a scalar TypedArrayltTgt with the given value This method supports arithmetictypes complex types and string types

const T val Value to be inserted into the scalar If valis 7-bit ASCII data then the methodconverts it to UTF16

const String valconst stdstring val

1 API Reference

1-14

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory

Create a vector containing 2 scalar values stdvectorltmatlabdataArraygt args( factorycreateScalarltint16_tgt(100) factorycreateScalarltint16_tgt(60)) return 0

ldquoCall Function with Single Returned Argumentrdquo

createCellArrayCellArrayltArraygt createCellArray(ArrayDimensions dims)

template lttypename TargsgtCellArrayltArraygt createCellArray(ArrayDimensions dims Targs data)

Creates a CellArray with the specified data Data is specified in column major order

Targs Variadic template of

bull arithmetic typebull complex typebull matlabdataStringbull stdstringbull matlabdataArray

matlabdataArrayFactory

1-15

ArrayDimensionsdims

Dimensions of the cell array

Targs data Elements to be inserted into the cell array specified as aprimitive complex type string or Array

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f CellArray myArray = fcreateCellArray( 12 fcreateCharArray(MATLAB Cell Array) fcreateArrayltdoublegt( 22 12 22 32 42 ))

return 0

createCharArrayCharArray createCharArray(String str)

CharArray createCharArray(stdstring str)

Creates a 1xn CharArray from the specified input where n is the string length

matlabdataString str

Data to be filled into the array

stdstring str

matlabOutOfMemoryException

The array could not be allocated

1 API Reference

1-16

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) return 0

createStructArrayStructArray createStructArray(ArrayDimensions dims stdvectorltstdstringgt fieldNames)

Creates a StructArray with the given dimensions and field names

ArrayDimensions dims Dimensions for the arraystdvectorltstdstringgtfieldNames

Vector of the field names for the structure

matlabOutOfMemoryException

The array could not be allocated

DuplicateFieldNameInStructArrayException

Duplicate field names specified

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f

Create StructArray equivalent to MATLAB structure s s = struct(loc east west data [1 2 3] [4 5 6 7 8]) StructArray S = fcreateStructArray( 12 loc data ) S[0][loc] = fcreateCharArray(east) S[0][data] = fcreateArrayltuint8_tgt( 1 3 1 2 3 )

matlabdataArrayFactory

1-17

S[1][loc] = fcreateCharArray(west) S[1][data] = fcreateArrayltdoublegt( 1 5 4 5 6 7 8 )

Access the value defined by the MATLAB statement s(1)data ReferenceltArraygt val = S[0][data] return 0

createEnumArrayEnumArray createEnumArray(ArrayDimensions dims stdstring className stdvectorltstdstringgt enums)

EnumArray createEnumArray(ArrayDimensions dims stdstring className)

Creates an EnumArray of type className If specified the array is initialized with thelist of enumeration names

ArrayDimensionsdims

Dimensions for the array

stdstringclassName

Class name of the enumeration array

stdvectorltstdstringgt enums

List of the enumeration names

matlabOutOfMemoryException

The array could not be allocated

MustSpecifyClassNameException

Class name not specified

WrongNumberOfEnumsSuppliedException

The wrong number of enumerations provided

include MatlabDataArrayhppinclude ltvectorgt

1 API Reference

1-18

int main() using namespace matlabdata ArrayFactory f auto blue = fcreateEnumArray( 11 TextColor Blue )

Create an argument vector stdvectorltArraygt args( fcreateCharArray(My text) stdmove(blue) )

return 0

createSparseArraytemplate lttypename TgtSparseArrayltTgt createSparseArray(ArrayDimensions dims size_t nnz buffer_ptr_tltTgt data buffer_ptr_tltsize_tgt rows buffer_ptr_tltsize_tgt cols)

Creates a SparseArrayltTgt with rows-by-cols dimensions Only two dimensions areallowed for sparse arrays The buffer is not copied and the array takes ownership

T Element types specified as double bool orstdcomplexltdoublegt

ArrayDimensionsdims

Dimensions for the array

size_t nnz Number of nonzero elementsbuffer_ptr_tltTgtdata

Buffer containing the nonzero elements

buffer_ptr_tltsize_tgt rows

Buffer containing the row value for each element

buffer_ptr_tltsize_tgt cols

Buffer containing the column value for each element

matlabdataArrayFactory

1-19

matlabOutOfMemoryException

The array could not be allocated

InvalidDimensionsInSparseArrayException

More than two dimensions are specified

include MatlabDataArrayhpp

int main() stdvectorltdoublegt data = 35 1298 2176 stdvectorltsize_tgt rows = 001 stdvectorltsize_tgt cols = 048 size_t nnz = 3

matlabdataArrayFactory factory auto data_p = factorycreateBufferltdoublegt(nnz) auto rows_p = factorycreateBufferltsize_tgt(nnz) auto cols_p = factorycreateBufferltsize_tgt(nnz)

double dataPtr = data_pget() size_t rowsPtr = rows_pget() size_t colsPtr = cols_pget() stdfor_each(databegin() dataend() [amp](const doubleamp e) (dataPtr++) = e ) stdfor_each(rowsbegin() rowsend() [amp](const size_tamp e) (rowsPtr++) = e ) stdfor_each(colsbegin() colsend() [amp](const size_tamp e) (colsPtr++) = e )

matlabdataSparseArrayltdoublegt arr = factorycreateSparseArrayltdoublegt( 29 nnz stdmove(data_p) stdmove(rows_p) stdmove(cols_p)) return 0

createEmptyArrayArray createEmptyArray()

Creates an empty Array containing no elements

Array Empty array

1 API Reference

1-20

matlabOutOfMemoryException

The array could not be allocated

createBuffertemplate lttypename Tgtbuffer_ptr_tltTgt createBuffer(size_t numberOfElements)

Creates a buffer which can be passed into createArrayFromBuffer No data copies aremade when creating an array from a buffer Data must be in column major order

T Primitive types

size_t numberOfElements Number of elements not the actualbuffer size

buffer_ptr_tltTgt Unique_ptr containing the buffer

matlabOutOfMemoryException

The array could not be allocated

createArrayFromBuffertemplate lttypename TgtTypedArrayltTgt createArrayFromBuffer(ArrayDimensions dims buffer_ptr_tltTgt buffer)

Creates a TypedArrayltTgt using the given buffer

T Primitive types

ArrayDimensions dims Dimensions for the arraybuffer_ptr_tltTgt buffer Buffer containing the data The buffer is not

copied The TypedArrayltTgt object takesownership of the buffer Data must be in columnmajor order

matlabdataArrayFactory

1-21

matlabOutOfMemoryException

The array could not be allocated

See Also

Introduced in R2017b

1 API Reference

1-22

matlabdataReferenceltArraygtC++ class to get reference to Array

DescriptionUse the ReferenceltArraygt class to get a reference to an Array element of a containerobject such as a MATLAB structure or cell array The class is a base class for allreference types that refer to arrays and provides basic array information ArrayRef isdefined as

using ArrayRef = ReferenceltArraygt

Class DetailsNamespace matlabdataInclude ArrayReferenceExthpp

Member Functionsbull ldquogetTyperdquo on page 1-23bull ldquogetDimensionsrdquo on page 1-24bull ldquogetNumberOfElementsrdquo on page 1-24bull ldquoisEmptyrdquo on page 1-24

getTypeArrayType getType() const

ArrayType Type of the array

NotEnoughIndicesProvidedException

Not enough indices provided

matlabdataReferenceltArraygt

1-23

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

InvalidArrayTypeException

Array type not recognized

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Array dimensions vector

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

getNumberOfElementssize_t getNumberOfElements() const

size_t Number of elements in array

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

isEmptybool isEmpty() const

bool Returns true if array is empty otherwise returns false

NotEnoughIndicesProvidedException

Not enough indices provided

1 API Reference

1-24

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-25bull ldquogetWritableElementsrdquo on page 1-25

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are const

const ReferenceltArraygtampref

ReferenceltArraygt

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are non-const

ReferenceltArraygtamp ref ReferenceltArraygt

matlabdataReferenceltArraygt

1-25

RangeltTypedIterator Tgt Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayType

Introduced in R2017b

1 API Reference

1-26

matlabdataArrayTypeC++ array type enumeration class

DescriptionUse ArrayType objects to identify the data type and other attributes of a MATLABarray

Class DetailsNamespace matlabdataInclude ArrayTypehpp

Enumerationenum class ArrayType UNKNOWN LOGICAL CHAR DOUBLE SINGLE INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 COMPLEX_DOUBLE COMPLEX_SINGLE COMPLEX_INT8 COMPLEX_UINT8 COMPLEX_INT16 COMPLEX_UINT16 COMPLEX_INT32 COMPLEX_UINT32

matlabdataArrayType

1-27

COMPLEX_INT64 COMPLEX_UINT64 CELL STRUCT OBJECT VALUE_OBJECT HANDLE_OBJECT_REF ENUM SPARSE_LOGICAL SPARSE_DOUBLE SPARSE_COMPLEX_DOUBLE MATLAB_STRING

C++ Data Type ConversionMATLAB ArrayType Value C++ Type DescriptionDOUBLE double double-precision (64-bit)

floating-point numberSINGLE float single-precision (32-bit)

floating-point numberINT8 int8_t signed 8-bit integerUINT8 uint8_t unsigned 8-bit integerINT16 int16_t signed 16-bit integerUINT16 uint16_t unsigned 16-bit integerINT32 int32_t signed 32-bit integerUINT32 uint32_t unsigned 32-bit integerINT64 int64_t signed 64-bit integerUINT64 uint64_t unsigned 64-bit integerCHAR char16_t 16-bit characterLOGICAL bool logicalCOMPLEX_DOUBLE stdcomplexltdoublegt complex double-precision

(64-bit) floating-pointnumber

1 API Reference

1-28

MATLAB ArrayType Value C++ Type DescriptionCOMPLEX_SINGLE stdcomplexltfloatgt complex single precision

(32-bit) floating-pointnumber

COMPLEX_INT8 stdcomplexltint8_tgt complex signed 8-bitinteger

COMPLEX_UINT8 stdcomplexltuint8_tgt complex unsigned 8-bitinteger

COMPLEX_INT16 stdcomplexltint16_tgt complex signed 16-bitinteger

COMPLEX_UINT16 stdcomplexltuint16_tgt complex unsigned 16-bitinteger

COMPLEX_INT32 stdcomplexltint32_tgt complex signed 32-bitinteger

COMPLEX_UINT32 stdcomplexltuint32_tgt complex unsigned 32-bitinteger

COMPLEX_INT64 stdcomplexltint64_tgt complex signed 64-bitinteger

COMPLEX_UINT64 stdcomplexltuint64_tgt complex unsigned 64-bitinteger

CELL matlabdataArray Array containing otherArrays

STRUCT matlabdataStruct Array with named fieldsthat can contain data ofvarying types and sizes

OBJECT matlabdataObject MATLAB objectVALUE_OBJECT matlabdataObject MATLAB value objectHANDLE_OBJECT_REF matlabdataObject Reference to an existing

handle object in MATLABENUM matlabdataEnumerat

ionArray of enumerationvalues

SPARSE_LOGICAL bool Sparse array of logicalSPARSE_DOUBLE double Sparse array of double

matlabdataArrayType

1-29

MATLAB ArrayType Value C++ Type DescriptionSPARSE_COMPLEX_DOUBLE stdcomplexltdoublegt Sparse array of complex

doubleMATLAB_STRING matlabdataMATLABSt

ringMATLAB string

See AlsoArrayVisitors

Introduced in R2017b

1 API Reference

1-30

matlabdataArrayVisitorsFunctions for defining visitor pattern

DetailsNamespace matlabdataInclude ArrayVisitorshpp

Functionsbull ldquoapply_visitorrdquo on page 1-31bull ldquoapply_visitor_refrdquo on page 1-31

apply_visitorauto apply_visitor(Array a V visitor)

TBD

TBD

InvalidArrayTypeException

apply_visitor_refauto apply_visitor_ref(const ArrayRefamp a V visitor)

Apply functor V to Array a

Result of V

matlabdataArrayVisitors

1-31

InvalidArrayTypeException

See Also

Introduced in R2017b

1 API Reference

1-32

matlabdataCellArrayC++ class to access MATLAB cell arrays

DescriptionA CellArray is a TypedArray with Array as the element type Use CellArray objectsto access MATLAB cell arrays To create a CellArray call createCellArrayCellArray is defined as

using CellArray = TypedArrayltArraygt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

ExamplesCreate Cell Array

Create a cell array with two elements

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CellArray cellArray1 = factorycreateCellArray( 12 factorycreateCharArray(MATLAB Cell Array) factorycreateArrayltdoublegt( 22 12 22 32 42 ))

matlabdataCellArray

1-33

return 0

See AlsocreateCellArray

Introduced in R2017b

1 API Reference

1-34

matlabdataCharArrayC++ class to access MATLAB character arrays

DescriptionUse CharArray objects to work with MATLAB character arrays To create a CharArraycall createCharArray

Class DetailsNamespace matlabdataBase class TypedArrayltchar16_tgtInclude CharArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-35bull ldquoCopy Assignment Operatorsrdquo on page 1-36bull ldquoMove Constructorsrdquo on page 1-37bull ldquoMove Assignment Operatorsrdquo on page 1-37

Copy Constructors

CharArray(const CharArrayamp rhs)

CharArray(const Arrayamp rhs)

Creates a shared data copy of a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

matlabdataCharArray

1-35

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray B(A) return 0

createCharArray on page 1-16

Copy Assignment OperatorsCharArrayamp operator=(const CharArrayamp rhs)

CharArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray C = factorycreateCharArray()

1 API Reference

1-36

Arrays A and C refer to the same data C = A

return 0

Move Constructors

CharArray(CharArrayampamp rhs)

CharArray(Arrayampamp rhs)

Moves contents of a CharArray object to a new instance

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move constructor - Creates B copies data from A A not valid CharArray B(stdmove(A))

return 0

Move Assignment Operators

CharArrayamp operator=(CharArrayampamp rhs)

CharArrayamp operator=(Arrayampamp rhs)

matlabdataCharArray

1-37

Assigns the input to this CharArray object

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move assignment - Data from A moved to C A no longer valid CharArray C = factorycreateCharArray() C = stdmove(A)

return 0

Member Functionsbull ldquotoUTF16rdquo on page 1-38bull ldquotoAsciirdquo on page 1-39

toUTF16String toUTF16() const

matlabdataString Contents of CharArray as matlabdataString

None

1 API Reference

1-38

toAsciistdstring toAscii() const

stdstring Contents of CharArray as ASCII string

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f auto arr = fcreateCharArray(helloworld) stdstring s = arrtoAscii()

return 0

ldquoEvaluate Mathematical Function in MATLABrdquo

See AlsoldquocreateCharArrayrdquo on page 1-16 | TypedArray | matlabdataString

Introduced in R2017b

matlabdataCharArray

1-39

matlabdataReferenceltCharArraygtC++ class to get reference to CharArray

DescriptionThe CharArrayExt class extends the APIs available to a reference to a CharArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquotoUTF16rdquo on page 1-40bull ldquotoAsciirdquo on page 1-40

toUTF16String toUTF16() const

matlabdataString Contents of reference to CharArray as a utf16 string

None

toAsciistdstring toAscii() const

stdstring Contents of reference to CharArray asmatlabdataString

1 API Reference

1-40

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

See AlsoCharArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltCharArraygt

1-41

matlabdataEnumArrayC++ class to access MATLAB enumeration arrays

DescriptionUse EnumArray objects to access enumeration arrays To create an EnumArray callcreateEnumArray

Class DetailsNamespace matlabdataBase class TypedArrayltEnumerationgtInclude EnumArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-42bull ldquoCopy Assignment Operatorsrdquo on page 1-43bull ldquoMove Constructorsrdquo on page 1-43bull ldquoMove Assignment Operatorsrdquo on page 1-43

Copy Constructors

EnumArray(const EnumArrayamp rhs)

EnumArray(const Arrayamp rhs)

Creates a shared data copy of an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as EnumArray object

1 API Reference

1-42

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Copy Assignment OperatorsEnumArrayamp operator=(const EnumArrayamp rhs)

EnumArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move ConstructorsEnumArray(EnumArrayampamp rhs)

EnumArray(Arrayampamp rhs)

Moves contents of an EnumArray object to a new instance

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move Assignment OperatorsEnumArrayamp operator=(EnumArrayampamp rhs)

matlabdataEnumArray

1-43

EnumArrayamp operator=(Arrayampamp rhs)

Assigns the input to this EnumArray object

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Member Functions

getClassNamestdstring getClassName() const

Return class name for this EnumArray

stdstring The class name

None

See AlsoldquocreateEnumArrayrdquo on page 1-18 | TypedArray

Introduced in R2017b

1 API Reference

1-44

matlabdataReferenceltEnumArraygtC++ class to get reference to EnumArray

DescriptionThe EnumArrayExt class extends the APIs available to a reference to an EnumArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functions

getClassNamestdstring getClassName() const

Return class name for this reference to an EnumArray object

stdstring Class name

None

See AlsoEnumArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltEnumArraygt

1-45

matlabdataEnumerationElement type for MATLAB enumeration arrays

DescriptionEnumeration is the element type for an EnumArray object

Class DetailsNamespace matlabdataInclude Enumerationhpp

See AlsoEnumArray

TopicsldquoMATLAB Data API Typesrdquo

Introduced in R2017b

1 API Reference

1-46

matlabExceptionC++ base class for exceptions

DescriptionAll MATLAB C++ exceptions can be caught as matlabException

Class DetailsNamespace matlabInclude Exceptionhpp

See Also

TopicsldquoMATLAB Data API Exceptionsrdquo

Introduced in R2017b

matlabException

1-47

matlabdataForwardIteratorltTgtTemplated C++ class to provide forward iterator support for StructArray field names

DescriptionUse ForwardIterator objects to access a range of field name elements in aStructArray

Class DetailsNamespace matlabdataInclude ForwardIteratorhpp

Template ParametersT matlabdataMATLABFieldIdentifier

Constructorsbull ldquoCopy Constructorsrdquo on page 1-48bull ldquoCopy Assignment Operatorsrdquo on page 1-49

Copy Constructors

ForwardIterator(const ForwardIteratorltTgtamp rhs)

Creates a shared data copy of a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to copy

ForwardIterator New instance

1 API Reference

1-48

None

Copy Assignment Operators

ForwardIteratorltTgtamp operator=(const ForwardIteratorltTgtamp rhs)

Assigns a shared data copy to a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to assign

ForwardIteratorltTgt Updated instance

None

Other Operatorsbull ldquooperator++rdquo on page 1-49bull ldquooperator--rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperatorrdquo on page 1-51bull ldquooperator-gtrdquo on page 1-51bull ldquooperator[]rdquo on page 1-51

operator++ForwardIteratorltTgtamp operator++()

Pre-increment operator

ForwardIteratorltTgtamp Reference to updated value

matlabdataForwardIteratorltTgt

1-49

None

operator--ForwardIteratorltTgt operator--(int)

Post-increment operator

ForwardIteratorltTgt New object

None

operator=bool operator==(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if the iterators point to the same elementOtherwise returns false

None

operator=bool operator=(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if this iterator points to a differentelement Otherwise returns false

None

1 API Reference

1-50

operatorreference operator() const

reference Shared copy of element that iterator points to specifiedas

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataForwardIteratorltTgt

1-51

See AlsoMATLABFieldIdentifier | StructArray

Introduced in R2017b

1 API Reference

1-52

matlabdataGetArrayTypeC++ struct TBD

DescriptionUse GetArrayType objects to TBD

Class DetailsNamespace matlabdataInclude GetArrayTypehpp

See Also

Introduced in R2017b

matlabdataGetArrayType

1-53

matlabdataGetReturnTypeC++ struct TBD

DescriptionUse GetReturnType to convert a template argument to the appropriate templateargument when creating a TypedArray

Class DetailsNamespace matlabdataInclude GetReturnTypehpp

See Also

Introduced in R2017b

1 API Reference

1-54

matlabdataMATLABFieldIdentifierC++ class used to identify field names in MATLAB struct array

Description

Class DetailsNamespace matlabdataInclude MATLABFieldIdentifierhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-55bull ldquoConstructorrdquo on page 1-55bull ldquoDestructorrdquo on page 1-56bull ldquoCopy Constructorsrdquo on page 1-56bull ldquoCopy Assignment Operatorsrdquo on page 1-56bull ldquoMove Constructorsrdquo on page 1-57bull ldquoMove Assignment Operatorsrdquo on page 1-57

Default ConstructorMATLABFieldIdentifier()

Construct an empty MATLABFieldIdentifier

None

ConstructorMATLABFieldIdentifier(stdstring str)

matlabdataMATLABFieldIdentifier

1-55

Construct a MATLABFieldIdentifier from stdstring

stdstring str String that contains the field name

Destructor

~MATLABFieldIdentifier()

Destroy a MATLABFieldIdentifier

None

Copy Constructors

MATLABFieldIdentifier(const MATLABFieldIdentifieramp rhs)

Creates a shared data copy of a MATLABFieldIdentifier object

constMATLABFieldIdentifieramprhs

Value to copy

None

Copy Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifier constamp rhs)

Assigns a shared data copy to a MATLABFieldIdentifier object

MATLABFieldIdentifierconstamp rhs

Value to move

1 API Reference

1-56

MATLABFieldIdentifieramp Updated instance

None

Move Constructors

MATLABFieldIdentifier(MATLABFieldIdentifierampamp rhs)

Moves contents a MATLABFieldIdentifier object to a new instance

MATLABFieldIdentifierampamprhs

Value to move

None

Move Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifierampamp rhs)

MATLABFieldIdentifierampamprhs

Value to move

MATLABFieldIdentifieramp Updated instance

None

Destructor~MATLABFieldIdentifier()

Description

Destroy a MATLABFieldIdentifier

matlabdataMATLABFieldIdentifier

1-57

Other Operators

operator stdstringoperator stdstring() const

stdstring Representation of the MATLABFieldIdentifier object

None

Free Functions

operator==bool operator==(const MATLABFieldIdentifieramp rhs) const

Check if two MATLABFieldIdentifier objects are identical

constMATLABFieldIdentifieramprhs

Value to be compared

bool Returns true if the objects are identical Otherwisereturns false

None

See AlsoForwardIterator | StructArray

Introduced in R2017b

1 API Reference

1-58

matlabdataMATLABStringElement type for MATLAB string arrays

DescriptionMATLABString is defined as

using MATLABString = OptionalltStringgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataString

Introduced in R2017b

matlabdataMATLABString

1-59

matlabdataReferenceltMATLABStringgtC++ class to get reference to element of StringArray

DescriptionA ReferenceltMATLABStringgt object is created when using operator[] into anStringArray or dereferenceing a String arrary iterator

Class DetailsNamespace matlabdataInclude MATLABStringReferenceExthpp

Cast

String()operator String() const

matlabdataString Element of a MATLABString array converted toString

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

stdruntime_error Array element does not have a value

1 API Reference

1-60

Member Functionsbull ldquoboolrdquo on page 1-61bull ldquohas_valuerdquo on page 1-61

booloperator bool() const

Check whether string contains a value

operator True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

has_valuebool has_value() const

Check whether string contains a value

bool True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

matlabdataReferenceltMATLABStringgt

1-61

See Also

Introduced in R2017b

1 API Reference

1-62

matlabdataArrayC++ base class for all array types

DescriptionUse Array objects to represent single and multi-dimensional arrays The Array classprovides methods for users to be able to query generic information about all arrays suchas dimensions and type and has methods to create deep copies and shared data copiesUse ArrayFactory methods to construct Arrays Once an Array has been constructedit can be moved or cloned (deep-copied) or a shared-data copy can be created Arrayssupport copy-on-write semantics

Class DetailsNamespace matlabdataInclude MDArrayhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-63bull ldquoCopy Constructorsrdquo on page 1-64bull ldquoCopy Assignment Operatorsrdquo on page 1-64bull ldquoMove Constructorsrdquo on page 1-64bull ldquoMove Assignment Operatorsrdquo on page 1-65

Default Constructor

Array()

None

matlabdataArray

1-63

Copy Constructors

Array(const Arrayamp rhs)

Creates a shared data copy of an Array object

const Arrayamp rhs Value to copy

None

Copy Assignment Operators

Arrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an Array object

const Arrayamp rhsrhs Value to copy

Arrayamp Updated instance

None

Move Constructors

Array(Arrayampamp rhs)

Moves contents of an Array object to a new instance

Arrayampamp rhs Value to move

None

1 API Reference

1-64

Move Assignment Operators

Arrayamp operator=(Arrayampamp rhs)

Assigns the input to this Array object

Arrayampamp rhs Value to move

Arrayamp Updated instance

None

Destructorvirtual ~Array()

Indexing Operators

operator[]ArrayElementRefltfalsegt operator[](size_t idx)

ArrayElementReflttruegt operator[](size_t idx) const

Enables [] indexing on const and non-const arrays Indexing is 0-based

size_t idx First array index

ArrayElementRefltfalsegt Temporary object containing the index specified Thereturn value allows the element of the array to bemodified or retrieved

matlabdataArray

1-65

ArrayElementReflttruegt Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Member Functionsbull ldquogetTyperdquo on page 1-66bull ldquogetDimensionsrdquo on page 1-66bull ldquogetNumberOfElementsrdquo on page 1-66bull ldquoisEmptyrdquo on page 1-67

getTypeArrayType getType() const

ArrayType Array type

None

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Vector of each dimension in the array

None

getNumberOfElementssize_t getNumberOfElements() const

size_t The number of elements in the array

1 API Reference

1-66

None

isEmptybool isEmpty() const

bool True if array is empty False if array is not empty

None

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-67bull ldquogetWritableElementsrdquo on page 1-67

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const Arrayamp arr)

Get a range containing the elements of the Array Iterators contained in the range areconst

const Arrayamp arr Array

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(Arrayamp arr)

matlabdataArray

1-67

Get a range containing the elements of the Array Iterators contained in the range arenon-const

Arrayamp arr Array

RangeltTypedIterator Tgt Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayFactory

Introduced in R2017b

1 API Reference

1-68

matlabdataObjectElement type for MATLAB object arrays

DescriptionObject is the element type for an ObjectArray

Class DetailsNamespace matlabdataInclude Objecthpp

See AlsoObjectArray

Introduced in R2017b

matlabdataObject

1-69

matlabdataObjectArrayC++ class to access MATLAB object arrays

DescriptionUse ObjectArray objects to access MATLAB object arrays You do not create anObjectArray only MATLAB functions create ObjectArrays You can pass anObjectArray to a MATLAB function

ObjectArray is defined as

using ObjectArray = TypedArrayltObjectgt

Class DetailsNamespace matlabdataInclude ObjectArrayhpp

See AlsoObject

Introduced in R2017b

1 API Reference

1-70

matlabdataOptionalltTgtTemplated C++ class representing optional values

DescriptionUse Optional objects to represent values that might or might not exist

Class DetailsNamespace matlabdataInclude Optionalhpp

Template ParametersT Array type specified as matlabdataString

Constructorsbull ldquoDefault Constructorsrdquo on page 1-71bull ldquoCopy Constructorsrdquo on page 1-71bull ldquoCopy Assignment Operatorsrdquo on page 1-72bull ldquoMove Constructorsrdquo on page 1-72bull ldquoMove Assignment Operatorsrdquo on page 1-72

Default Constructors

optional()

Copy Constructors

optional(const optionalamp other)

matlabdataOptionalltTgt

1-71

Creates a shared data copy

const optionalamp other Value to copy

None

Copy Assignment OperatorsoptionalltTgtamp operator=(const optionalltTgtamp other)

Assigns a shared data copy

const optionalltTgtamp other Value to copy

optionalltTgtamp Updated instance

None

Move Constructorsoptional(optionalampamp other)

optional(Tampamp value)

Moves contents of an Optional object to a new instance

optionalampamp other Value to moveTampamp value Value of type T to move

None

Move Assignment OperatorsoptionalltTgtamp operator=(optionalltTgtampamp other)

1 API Reference

1-72

optionalltTgtamp operator=(Tampamp value)

Assigns the input to this instance

optionalltTgtampamp other

Tampamp value

Value to move

optionalltTgtamp Updated instance

None

Other Operatorsbull ldquooperator=rdquo on page 1-73bull ldquooperator-gtrdquo on page 1-74bull ldquooperatorrdquo on page 1-74bull ldquooperator Trdquo on page 1-74

operator=optionalltTgtamp operator=(nullopt_t)

optionalltTgtamp operator=(const optionalltTgtamp other)

optionalltTgtamp operator=(optionalltTgtampamp other)

optionalltTgtamp operator=(Tampamp value)

optionalltTgtamp operator=(const Tamp value)

Assignment operators

optionalltTgtamp Updated instance

None

matlabdataOptionalltTgt

1-73

operator-gtconst T operator-gt() const

T operator-gt()

const T

T

Pointer to the element

stdruntime_error Optional object does not contain a value

operatorconst Tamp operator() const

Tamp operator()

const Tamp

Tamp

Reference to the element

stdruntime_error Optional object does not contain a value

operator Toperator T() const

Cast optionalltTgt value to T

operator Value contained in optionalltTgt if it exists

stdruntime_error There is no value

1 API Reference

1-74

Member Functionsbull ldquoboolrdquo on page 1-75bull ldquohas_valuerdquo on page 1-75bull ldquoswaprdquo on page 1-75bull ldquoresetrdquo on page 1-76

boolexplicit operator bool() const

Check whether object contains a value

operator True if object contains a value

None

has_valuebool has_value() const

Check whether object contains a value

bool True if object contains a value

None

swapvoid swap(optional ampother)

Swap value of this optional instance with value contained in the parameter

optional ampother Value to swap

matlabdataOptionalltTgt

1-75

None

resetvoid reset()

Reset optional value to missing

None

See Also

Introduced in R2017b

1 API Reference

1-76

matlabdataRangeltItTypeElemTypegtTemplated C++ class to provide range-based operation support

DescriptionRange objects wrap begin and end functions to enable range-based operations

Class DetailsNamespace matlabdataInclude Rangehpp

Template ParametersIteratorType Iterator typeElementType Element type

Constructorsbull ldquoConstructorrdquo on page 1-77bull ldquoMove Constructorsrdquo on page 1-78bull ldquoMove Assignment Operatorsrdquo on page 1-78

Constructor

Range(IteratorTypeltElementTypegt begin IteratorTypeltElementTypegtend)

Creates a Range object

matlabdataRangeltItTypeElemTypegt

1-77

IteratorTypeltElementTypegt begin

IteratorTypeltElementTypegt end

First and last elements of range

Range New instance

None

Move Constructors

Range(Rangeampamp rhs)

Moves contents of a Range object to a new instance

Rangeampamp rhs Range to move

Range New instance

None

Move Assignment Operators

Rangeamp operator=(Rangeampamp rhs)

Assigns the input to this Range object

Rangeampamp rhs Range to move

Rangeamp Updated instance

None

1 API Reference

1-78

beginIteratorTypeltElementTypegtamp begin()

ReturnsIteratorTypeltElementTypegtamp

First element in range

None

endIteratorTypeltElementTypegtamp end()

ReturnsIteratorTypeltElementTypegtamp

End of range

None

See Also

Introduced in R2017b

matlabdataRangeltItTypeElemTypegt

1-79

matlabdataReferenceltTgtTemplated C++ class to get references to Array elements

DescriptionA Reference object is a reference to an element of an Array without making a copy AReference is

bull Not a shared copybull Valid as long as the array that contains the reference is validbull Not thread-safe

Class DetailsNamespace matlabdataInclude Referencehpp

Template ParametersT Type of element referred to specified as

bull Arraybull Structbull Enumerationbull MATLABStringbull All stdcomplex types

Constructorsbull ldquoCopy Constructorrdquo on page 1-81bull ldquoCopy Assignment Operatorsrdquo on page 1-81bull ldquoMove Assignment Operatorsrdquo on page 1-81

1 API Reference

1-80

bull ldquoMove Constructorsrdquo on page 1-81

Copy ConstructorReference(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

Copy Assignment OperatorsReferenceltTgtamp operator=(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

ReferenceltTgtamp Updated instance

Move Assignment OperatorsReferenceltTgtamp operator=(ReferenceltTgtampamp rhs)

ReferenceltTgtampamp rhs Value to move

ReferenceltTgtamp Updated instance

None

Move ConstructorsReference(ReferenceltTgtampamp rhs)

Moves contents of a Reference object to a new instance

ReferenceltTgtampamp rhs Value to move

None

matlabdataReferenceltTgt

1-81

Other Operatorsbull ldquooperator=rdquo on page 1-82bull ldquooperatorltltrdquo on page 1-82bull ldquooperator T()rdquo on page 1-83bull ldquooperator stdstring()rdquo on page 1-83

operator=ReferenceltTgtamp operator=(T rhs)

ReferenceltTgtamp operator=(stdstring rhs)

ReferenceltTgtamp operator=(String rhs)

T rhs Value to assign The array being indexed must be non-const

stdstring rhs String to assign The array must be non-const andallow strings to be assigned

String rhs String to assign to StringArray The array beingindexed must be non-const

ReferenceltTgtamp Updated instance

None

operatorltlt

stdostreamamp operator ltlt(stdostreamamp os ReferenceltTgt constamp rhs)

stdostreamamp os ReferenceltTgt constamp rhs

stdostreamamp

1 API Reference

1-82

operator T()operator T() const

Cast to element from the array

T Shared copy of element from the array

None

operator stdstring()operator stdstring() const

Cast to stdstring from the array Makes a copy of the stdstring Only valid fortypes that can be cast to a stdstring

stdstring The string

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

stdruntime_error MATLABString is missing

Free Functions

operator==inline bool operator ==(ReferenceltMATLABStringgt constamp lhsstdstring constamp rhs)

inline bool operator ==(stdstring constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhs Stringconstamp rhs)

matlabdataReferenceltTgt

1-83

inline bool operator ==(String constamp lhs ReferenceltMATLABStringgtconstamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsMATLABString constamp rhs)

inline bool operator ==(MATLABString constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsReferenceltMATLABStringgt constamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhs Tconstamp rhs)

templatelttypename Tgt bool operator ==(T constamp lhs ReferenceltTgtconstamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhsReferenceltTgt constamp rhs)

ReferenceltMATLABStringgtconstamp lhs

stdstring constamp rhs Values tocompare

stdstring constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

String constamp rhs

String constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

MATLABString constamp rhs

MATLABString constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

ReferenceltMATLABStringgtconstamp rhs

ReferenceltTgt constamp lhs T constamp rhsT constamp lhs ReferenceltTgt constamp rhsReferenceltTgt constamp lhs ReferenceltTgt constamp rhs

1 API Reference

1-84

bool Returns true if values are equal

stdruntime_error Cannot compare argument to MATLABString

See Also

TopicsldquoAccess C++ Data Array Container Elementsrdquo

Introduced in R2017b

matlabdataReferenceltTgt

1-85

matlabdataSparseArrayltTgtTemplated C++ class to access data in MATLAB sparse arrays

DescriptionUse SparseArray objects to work with sparse MATLAB arrays To create aSparseArray call createSparseArray

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude SparseArrayhpp

Template ParametersT Type of element referred to specified as

bull boolbull doublebull stdcomplexltdoublegt

Constructorsbull ldquoCopy Constructorsrdquo on page 1-86bull ldquoCopy Assignment Operatorsrdquo on page 1-87bull ldquoMove Constructorsrdquo on page 1-87bull ldquoMove Assignment Operatorsrdquo on page 1-88

Copy Constructors

SparseArray(const SparseArrayltTgtamp rhs)

1 API Reference

1-86

SparseArray(const Arrayamp rhs)

Creates a shared data copy of a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array ofArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Copy Assignment OperatorsSparseArrayamp operator=(const SparseArrayltTgtamp rhs)

SparseArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

Move ConstructorsSparseArray(SparseArrayampamp rhs)

matlabdataSparseArrayltTgt

1-87

SparseArray(Arrayampamp rhs)

Moves contents a SparseArray object to a new instance

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Move Assignment Operators

SparseArrayamp operator=(SparseArrayltTgtampamp rhs)

SparseArrayamp operator=(Arrayampamp rhs)

Assigns the input to this SparseArray object

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

1 API Reference

1-88

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-89bull ldquoEnd Iteratorsrdquo on page 1-89

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functionsbull ldquogetNumberOfNonZeroElementsrdquo on page 1-90

matlabdataSparseArrayltTgt

1-89

bull ldquogetIndexrdquo on page 1-90

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array

size_t Number of nonzero elements in the array

None

getIndexSparseIndex getIndex(const TypedIteratorltTgtamp it)

SparseIndex getIndex(const TypedIteratorltT constgtamp it)

Returns the row-column coordinates of the nonzero entry that the iterator is pointing to

const TypedIteratorltTgtampit

Iterator pointing to the current entry in the sparsematrix

const TypedIteratorltTconstgtamp it

SparseIndex Row-column coordinates of the nonzero entry that theiterator is pointing to SparseIndex is defined asstdpairltsize_t size_tgt

None

See AlsoArray | createSparseArray

1 API Reference

1-90

Introduced in R2017b

matlabdataSparseArrayltTgt

1-91

matlabdataReferenceltSparseArrayltTgtgtTemplated C++ class to get reference to SparseArray

DescriptionUse the ReferenceltSparseArraygt class to get a reference to a SparseArray elementof a container object such as a MATLAB structure or cell array

Class DetailsNamespace matlabdataInclude SparseArrayRefhpp

Template ParametersT Type of elements in SparseArray specified as bool

double or stdcomplexltdoublegt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-92bull ldquoEnd Interatorsrdquo on page 1-93

Begin Interatorsiterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array Iterates over non-zeroelements of the SparseArray

1 API Reference

1-92

None

End Interators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functions

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array Since sparse arrays only storenonzero elements this method returns the actual array size It is different from arraydimensions that specify the full array size

size_t Number of nonzero elements in the array

None

See Also

Introduced in R2017b

matlabdataReferenceltSparseArrayltTgtgt

1-93

matlabdataStringType representing strings as stdbasic_stringltchar16_tgt

DescriptionThe String class defines the element type of a StringArray String is defined as

using String = stdbasic_stringltchar16_tgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

1 API Reference

1-94

matlabdataStringArrayC++ class to access MATLAB string arrays

DescriptionUse StringArray objects to access MATLAB string arrays StringArray is defined as

using StringArray = TypedArrayltMATLABStringgt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

matlabdataStringArray

1-95

matlabdataStructArrayC++ class to access MATLAB struct arrays

DescriptionUse StructArray objects to work with MATLAB struct arrays To access a field for asingle element in the array use the field name To create a StructArray object callcreateStructArray

Class DetailsNamespace matlabdataBase class TypedArrayltStructgtInclude StructArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-96bull ldquoCopy Assignment Operatorsrdquo on page 1-97bull ldquoMove Constructorsrdquo on page 1-97bull ldquoMove Assignment Operatorsrdquo on page 1-98

Copy Constructors

StructArray(const StructArrayamp rhs)

StructArray(const Arrayamp rhs)

Creates a shared data copy of a StructArray object

const StructArrayamp rhs Value to copy

1 API Reference

1-96

const Arrayamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Copy Assignment Operators

StructArrayamp operator=(const StructArrayamp rhs)

StructArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a StructArray object

const StructArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeSTRUCT object

StructArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Move Constructors

StructArray(StructArrayampamp rhs)

StructArray(Arrayampamp rhs)

Moves contents of a StructArray object to a new instance

StructArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

matlabdataStructArray

1-97

Move Assignment OperatorsStructArrayamp operator=(StructArrayampamp rhs)

Assigns the input to this StructArray object

StructArrayampamp rhs Value to move

StructArrayamp Updated instance

None

Destructor~StructArray()

Description

Free memory for StructArray object

Member Functionsbull ldquogetFieldNamesrdquo on page 1-98bull ldquogetNumberOfFieldsrdquo on page 1-99

getFieldNamesRangeltForwardIterator MatlabFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enable access to allfields in StructArray object

None

1 API Reference

1-98

getNumberOfFieldssize_t getNumberOfFields() const

size_t Number of fields

None

ExamplesCreate StructArray

Suppose that you have the following MATLAB structure

s = struct(loc east west data [1 2 3] [4 5 6 7 8])

Create a variable containing the data for loc east

val = s(1)data

The following C++ code creates these variables

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory

StructArray S = factorycreateStructArray( 12 loc data ) S[0][loc] = factorycreateCharArray(east) S[0][data] = factorycreateArrayltuint8_tgt( 1 3 1 2 3 ) S[1][loc] = factorycreateCharArray(west) S[1][data] = factorycreateArrayltdoublegt( 1 5 4 5 6 7 8 )

ReferenceltArraygt val = S[0][data] return 0

bull ldquoCreate Structure Array and Send to MATLABrdquo

matlabdataStructArray

1-99

See AlsoMATLABFieldIdentifier | Range | createStructArray

TopicsldquoCreate Structure Array and Send to MATLABrdquo

Introduced in R2017b

1 API Reference

1-100

matlabdataReferenceltStructArraygtC++ class to get reference to StructArray

DescriptionThe StructArrayExt class extends the APIs available to a reference to a StructArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquogetFieldNamesrdquo on page 1-101bull ldquogetNumberOfFieldsrdquo on page 1-101

getFieldNamesRangeltForwardIterator MATLABFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enables access to allfields in StructArray object

None

getNumberOfFieldssize_t getNumberOfFields() const

matlabdataReferenceltStructArraygt

1-101

size_t Number of fields

None

See AlsoReferenceltTypedArrayltTgtgt | StructArray

Introduced in R2017b

1 API Reference

1-102

matlabdataStructElement type for MATLAB struct arrays

DescriptionStruct is the element type for a StructArray object

Class DetailsNamespace matlabdataInclude Structhpp

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-103bull ldquoEnd Iteratorsrdquo on page 1-103

Begin Iteratorsconst_iterator begin() const

const_iterator cbegin() const

const_iterator Iterator to beginning of list of fields specified asTypedIteratorltArray constgt

None

End Iteratorsconst_iterator end() const

const_iterator cend() const

matlabdataStruct

1-103

const_iterator Iterator to end of list of fields specified asTypedIteratorltArray constgt

None

Indexing Operators

operator[]Array operator[](stdstring idx) const

Enables [] indexing on a StructArray object Indexing is 0-based

stdstring idx Field name

Array Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in this StructArray

See AlsoldquocreateStructArrayrdquo on page 1-17 | StructArray

Introduced in R2017b

1 API Reference

1-104

matlabdataReferenceltStructgtC++ class to get reference to element of StructArray

DescriptionUse the ReferenceltStructgt class to access an element of a StructArray

Class DetailsNamespace matlabdataInclude StructRefhpp

Indexing Operators

operator[]ReferenceltArraygt operator[](stdstring idx)

Array operator[](stdstring idx) const

Index into the Struct with a field name

stdstring idx Field name

ReferenceltArraygt Reference to Array found at specified fieldArray Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in the struct

matlabdataReferenceltStructgt

1-105

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-106bull ldquoEnd Iteratorsrdquo on page 1-106

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

1 API Reference

1-106

Cast

Struct()operator Struct() const

Create a shared copy of the Struct

Struct Shared copy

None

See Also

Introduced in R2017b

matlabdataReferenceltStructgt

1-107

matlabdataTypedArrayltTgtTemplated C++ class to access array data

DescriptionThe templated TypedArray class provides typesafe APIs to handle all array types(except sparse arrays) inside an array This class defines the following iterator types

using iterator = TypedIteratorltTgt

using const_iterator = TypedIteratorltT constgt

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude TypedArrayhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_t

1 API Reference

1-108

uint64_tchar16_tboolstdcomplexltdoublegtstdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorrdquo on page 1-109bull ldquoCopy Assignment Operatorrdquo on page 1-110bull ldquoMove Constructorrdquo on page 1-110bull ldquoMove Assignment Operatorrdquo on page 1-111

Copy ConstructorTypedArray(const TypedArrayltTgtamp rhs)

TypedArray(const Arrayamp rhs)

Creates a shared data copy of the input

matlabdataTypedArrayltTgt

1-109

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Copy Assignment Operator

TypedArrayltTgtamp operator=(const TypedArrayltTgtamp rhs)

TypedArrayltTgtamp operator=(const Arrayamp rhs)

Assigns a shared data copy of the input to this TypedArrayltTgt

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Move Constructor

TypedArray(TypedArrayltTgtampamp rhs)

TypedArray(Arrayampamp rhs)

Moves contents of the input to a new instance

TypedArrayltTgtampamp rhs Value to be movedArrayampamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input does not match

1 API Reference

1-110

Move Assignment Operator

TypedArrayltTgtamp operator=(TypedArrayltTgtampamp rhs)

TypedArrayltTgtamp operator=(Arrayampamp rhs)

Moves the input to this TypedArrayltTgt object

TypedArrayltTgtampamp rhs Value to move

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Destructorvirtual ~TypedArray()

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-111bull ldquoEnd Iteratorsrdquo on page 1-112

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

matlabdataTypedArrayltTgt

1-111

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

Indexing Operators

operator[]ArrayElementTypedRefltT stdis_constltTgtvaluegt operator[](size_tidx)

ArrayElementTypedRefltT truegt operator[](size_t idx) const

Enables [] indexing on a TypedArray Indexing is 0-based

size_t idx First array index

1 API Reference

1-112

ArrayElementTypedRefltTstdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltTtruegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Suppose that you have a cell array c Assign a value to a ReferenceltArraygt object andcall the member function getType

ReferenceltArraygt r = c[0][0]auto t = c[0][0]getType

Member Functions

releasebuffer_ptr_tltTgt release()

Release the underlying buffer from the Array If the Array is shared a copy of the bufferis made otherwise no copy is made After the buffer is released the array contains noelements

buffer_ptr_tltTgt A unique_ptr with the data pointer

InvalidArrayTypeException

This TypedArray does not support releasing the buffer

matlabdataTypedArrayltTgt

1-113

ExamplesAssign Values to Array Elements

Create an array equivalent to the MATLAB array [1 2 3 4] then replace eachelement of the array with a single value

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory Create an array equivalent to the MATLAB array [1 2 3 4] matlabdataTypedArrayltdoublegt D = factorycreateArrayltdoublegt( 22 1324 ) Change the values for (autoamp elem D) elem = 55 return 0

bull ldquoBring Result of MATLAB Calculation Into C++rdquo

See AlsoArray | ArrayType

TopicsldquoBring Result of MATLAB Calculation Into C++rdquo

Introduced in R2017b

1 API Reference

1-114

matlabdataReferenceltTypedArrayltTgtgtC++ class to get reference to TypedArray

DescriptionThe ReferenceltTypedArrayltTgtgt class extends the APIs available to a reference to anArray It derives from the ReferenceltArraygt class and provides iterators and type-safe indexing ReferenceltTypedArrayltTgtgt is not thread-safe - do not pass referencesto TypedArray objects between threads

TypedArrayRef is defined in TypedArrayRefhpp as

template lttypename Tgtusing TypedArrayRef = ReferenceltTypedArrayltTgtgt

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

ConstructorReference(const ReferenceltArraygtamp rhs)

Description

Create a ReferenceltTypedArrayltTgtgt object from a ReferenceltArraygt object

Parametersconst ReferenceltArraygtamprhs

Value to copy

matlabdataReferenceltTypedArrayltTgtgt

1-115

ThrowsTypeMismatchException Element of Array does not match ltTgt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-116bull ldquoEnd Iteratorsrdquo on page 1-116

Begin Interators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

1 API Reference

1-116

None

Indexing Operators

operator[]ArrayElementTypedRefltarr_elem_type stdis_constltTgtvaluegtoperator[](size_t idx)

ArrayElementTypedRefltarr_elem_type truegt operator[](size_t idx)const

Enables [] indexing on a reference to an Array Indexing is 0-based

size_t idx First array index

ArrayElementTypedRefltarr_elem_typestdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltarr_elem_type truegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

InvalidFieldNameException

Field name is invalid for a struct

Other Operators

operator=ReferenceltTypedArrayltTgtgtamp operator= (TypedArrayltTgt rhs)

matlabdataReferenceltTypedArrayltTgtgt

1-117

Assign a TypedArray to an element of the referenced Array The Array being indexedmust be non-const

TypedArrayltTgt rhs Value to assign

ReferenceltTypedArrayltTgtgtamp

Updated instance

None

See Also

Introduced in R2017b

1 API Reference

1-118

matlabdataTypedIteratorltTgtTemplated C++ class to provide random access iterator

DescriptionTypedIterator is the return type of all begin and end functions that support randomaccess

Class DetailsNamespace matlabdataInclude TypedIteratorhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tchar16_tboolstdcomplexltdoublegt

matlabdataTypedIteratorltTgt

1-119

stdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorsrdquo on page 1-120bull ldquoCopy Assignment Operatorsrdquo on page 1-121bull ldquoMove Constructorsrdquo on page 1-121bull ldquoMove Assignment Operatorsrdquo on page 1-121

Copy Constructors

TypedIterator(const TypedIteratorltTgtamp rhs)

Creates a shared data copy of a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

None

1 API Reference

1-120

Copy Assignment OperatorsTypedIteratorltTgtamp operator=(const TypedIteratorltTgtamp rhs)

Assigns a shared data copy to a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

TypedIteratorltTgtamp Updated instance

None

Move ConstructorsTypedIterator(TypedIteratorltTgt ampamprhs)

Moves contents of a TypedIterator object to a new instance

TypedIteratorltTgtampamp rhs Value to move

None

Move Assignment OperatorsTypedIteratorltTgtamp operator=(TypedIteratorltTgtampamp rhs)

Assigns the input to this TypedIterator object

TypedIteratorltTgtampamp rhs Value to move

TypedIteratorltTgtamp Updated instance

None

matlabdataTypedIteratorltTgt

1-121

Other Operatorsbull ldquooperator++rdquo on page 1-122bull ldquooperator--rdquo on page 1-122bull ldquooperator++rdquo on page 1-123bull ldquooperator--rdquo on page 1-123bull ldquooperator+=rdquo on page 1-123bull ldquooperator-=rdquo on page 1-124bull ldquooperator=rdquo on page 1-124bull ldquooperatorltrdquo on page 1-124bull ldquooperatorgtrdquo on page 1-125bull ldquooperatorlt=rdquo on page 1-125bull ldquooperatorgt=rdquo on page 1-125bull ldquooperator+rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperatorrdquo on page 1-127bull ldquooperator-gtrdquo on page 1-127bull ldquooperator[]rdquo on page 1-127

operator++TypedIteratorltTgtamp operator++()

Pre-increment operator

TypedIteratorltTgtamp Original iterator

None

operator--TypedIteratorltTgtamp operator--()

1 API Reference

1-122

Pre-decrement operator

TypedIteratorltTgtamp Original iterator

None

operator++TypedIteratorltTgt operator++(int)

Post-increment operator

TypedIteratorltTgt Copy of original iterator

None

operator--TypedIteratorltTgt operator--(int)

Post-decrement operator

TypedIteratorltTgt Copy of original iterator

None

operator+=TypedIteratorltTgtamp operator+=(difference_type d)

Addition assignment operator

difference_type d Amount to add specified as stdptrdiff_t

matlabdataTypedIteratorltTgt

1-123

TypedIteratorltTgtamp Updated instance

None

operator-=TypedIteratorltTgtamp operator-=(difference_type d)

Subtraction assignment operator

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgtamp Updated instance

None

operator=bool operator=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if iterators do not point to same element

None

operatorltbool operatorlt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

1 API Reference

1-124

bool Returns true if left-side iterator is less than right-sideiterator

operatorgtbool operatorgt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than right-side iterator

operatorlt=bool operatorlt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is less than or equal toright-side iterator

None

operatorgt=bool operatorgt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than orequal to right-side iterator

None

matlabdataTypedIteratorltTgt

1-125

operator+TypedIteratorltTgt operator+(difference_type d) const

Creates an iterator that is added to this one by the amount passed in

difference_type d Amount to add specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-TypedIteratorltTgt operator-(difference_type d) const

Creates an iterator that is decremented from this one by the amount passed in

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-difference_type operator-(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

difference_type Difference between iterators specified asstdptrdiff_t

None

1 API Reference

1-126

operatorreference operator() const

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataTypedIteratorltTgt

1-127

Free Function

operator==bool operator==(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if both iterators point to same element

None

See Also

Introduced in R2017b

1 API Reference

1-128

matlabdataapply_visitorCall Visitor class on arrays

Descriptionauto apply_visitor(Array a V visitor) dispatch to visitor class operationsbased on array type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersmatlabdataArray a

The matlabdataArray to operate on with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

matlabdataapply_visitor

1-129

matlabdataapply_visitor_refCall Visitor class on array references

Descriptionauto apply_visitor_ref(const ArrayRefamp a V visitor) dispatch to visitorclass operations based on array reference type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersconstmatlabdataArrayRefamp a

A matlabdataArrayRef reference to the array to operateon with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

1 API Reference

1-130

matlabengineMATLABEngineEvaluate MATLAB functions from C++ program

DescriptionThe matlabengineMATLABEngine class uses a MATLAB process as acomputational engine for C++ This class provides an interface between the C++language and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom C++ programs

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Factory MethodsThe matlabengineMATLABEngine class provides methods to start MATLAB and toconnect to a shared MATLAB session synchronously or asynchronously

bull matlabenginestartMATLAB mdash Start MATLAB synchronouslybull matlabenginestartMATLABAsync mdash Start MATLAB asynchronouslybull matlabengineconnectMATLAB mdash Connect to shared MATLAB session

synchronouslybull matlabengineconnectMATLABAsync mdash Connect to shared MATLAB session

asynchronously

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -h

matlabengineMATLABEngine

1-131

bull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup OptionsrdquoFor an example of how to use MATLAB startup options when starting engineapplications see ldquoStart MATLAB with Startup Optionsrdquo

Method Summary

Member Functionsldquofevalrdquo on page 1-133

Evaluate MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-136

Evaluate MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-138 Evaluate MATLAB statement as a string synchronouslyldquoevalAsyncrdquo on page1-139

Evaluate MATLAB statement as a string asynchronously

ldquogetVariablerdquo onpage 1-140

Get variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-141

Get variable from the MATLAB base workspace asynchronously

ldquosetVariablerdquo onpage 1-142

Put variable into the MATLAB base workspace synchronously

ldquosetVariableAsyncrdquoon page 1-142

Put variable into the MATLAB base workspace asynchronously

ldquogetPropertyrdquo onpage 1-143

Get object property value

ldquogetPropertyAsyncrdquoon page 1-144

Get object property value asynchronously

1 API Reference

1-132

ldquosetPropertyrdquo onpage 1-145

Set object property value

ldquosetPropertyAsyncrdquoon page 1-146

Set object property value asynchronously

Member Function Details

fevalstdvectorltmatlabdataArraygt feval(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

ResultType feval(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs )

ResultType feval(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB functions with input arguments synchronously Use feval when youwant to pass arguments from C++ to MATLAB and when you want to return a resultfrom MATLAB to C++

Inputs and outputs can be types defined by the MATLAB Data Array API or can benative C++ types

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

matlabengineMATLABEngine

1-133

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

stdvectorltmatlabdataArraygt

Outputs returned from MATLAB function

matlabdataArray Single output returned from MATLAB functionResultType Output returned from MATLAB function as a user-specified

type Can be a stdtuple if returning multiple arguments

matlabengineMATLABNotAvailableException

The MATLAB session is not available

1 API Reference

1-134

matlabengineMATLABExecutionException

There is a MATLAB runtime error in the function

matlabengineTypeConversionException

The result of a MATLAB function cannot be converted tothe specified type

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

This example passes an array of numeric values to a MATLAB function The codeperforms these steps

bull Creates a matlabdataArray with the dimensions 2-by-3 from a vector ofnumeric values of type double

bull Starts a shared MATLAB sessionbull Passes the data array to the MATLAB sqrt function and returns the result to C++

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabengine

stdvectorltdoublegt cppData 4 8 12 16 20 24

Create a 2-by-3 matlab data array matlabdataArrayFactory factory auto inputArray = factorycreateArray( 2 3 cppDatacbegin() cppDatacend())

Start MATLAB engine stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Pass data array to MATLAB sqrt function And return results auto result = matlabPtr-gtfeval(usqrt inputArray)

When calling feval using native C++ types the input arguments are restricted to scalarvalues For example this code returns the square root of a scalar value

include MatlabEnginehppusing namespace matlabengine

Start MATLAB engine synchronously stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Call sqrt function double result = matlabPtr-gt fevalltdoublegt(usqrt double(27))

matlabengineMATLABEngine

1-135

For functions that return multiple output arguments you can use the MATLAB data APIor if using C++ types a stdtuple For an example see ldquoCall Function with Native C++ Typesrdquo

ldquoCall MATLAB Functions from C++rdquo

ldquoMATLAB Data APIrdquo

fevalAsyncFutureResultltstdvectorltmatlabdataArraygtgt fevalAsync(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt amp output = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amp error = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs)

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB function with input arguments and returned values asynchronously

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

1 API Reference

1-136

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

FutureResult A FutureResult object used to get the result of calling theMATLAB function

None

This example passes the scalar double 127 to the MATLAB sqrt functionasynchronously The FutureResult is then used to get the result

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() matlabdataArrayFactory factory matlabdataArray argument = factorycreateScalarltdoublegt(127) FutureResultltmatlabdataArraygt future = matlabPtr-gt fevalAsync(convertUTF8StringToUTF16String(sqrt) stdmove(argument))

matlabengineMATLABEngine

1-137

matlabdataTypedArrayltdoublegt result = futureget()

ldquoCall Function Asynchronouslyrdquo

evalvoid eval(const matlabengineString ampstatement const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string synchronously

constmatlabengineString ampstatement

MATLAB statement to evaluate

conststdshared_ptrltmatlabengineStreamBuffergtampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergtamperror

Stream buffer used to store the error message from theMATLAB command

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

There is a runtime error in the MATLAB statement

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB statement

This example evaluates the following MATLAB statement

a = sqrt(127)

1 API Reference

1-138

The statement creates the variable a in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

evalAsyncFutureResultltvoidgt evalAsync(const matlabengineString ampstr const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string asynchronously

const Stringamp str MATLAB statement to evaluateconststdshared_ptrltmatlabengineStreamBuffergt ampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergt amperror

Stream buffer used to store the error message from theMATLAB command

FutureResult A FutureResult object used to wait for the completion of theMATLAB statement

None

This example evaluates the following MATLAB statement asynchronouslya = sqrt(127)

The statement creates the variable a in the MATLAB base workspace

matlabengineMATLABEngine

1-139

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltvoidgt future = matlabPtr-gt evalAsync(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

getVariablematlabdataArray getVariable(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace

constmatlabengineStringamp varName

Name of a variable in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variablefrom For more information see global

matlabdataArray

Variable obtained from the MATLAB base or global workspace

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The requested variable does not exist in the specifiedMATLAB base or global workspace

This example gets a variable named varName from the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray varName = matlabPtr-gtgetVariable(convertUTF8StringToUTF16String(varName))

1 API Reference

1-140

ldquoPass Variables from MATLAB to C++rdquo

getVariableAsyncFutureResultltmatlabdataArraygt getVariableAsync(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace asynchronously

constmatlabengineStringamp varName

Name of the variable in MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variable fromFor more information see global

FutureResult A FutureResult object that you can use to get the variableobtained from the MATLAB workspace as amatlabdataArray

None

This example gets a variable named varName from the MATLAB base workspaceasynchronously

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltmatlabdataArraygt future = matlabPtr-gt getVariableAsync(convertUTF8StringToUTF16String(varName))matlabdataArray varName = futureget()

ldquoPass Variables from MATLAB to C++rdquo

matlabengineMATLABEngine

1-141

setVariablevoid setVariable(const matlabengineString ampvarName const matlabdataArray ampvar WorkspaceType workspaceType = WorkspaceTypeBASE)

Put a variable into the MATLAB base or global workspace If a variable with the samename exists in the MATLAB workspace setVariable overwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

matlabengineMATLABNotAvailableException

The MATLAB session is not available

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from C++ to MATLABrdquo

setVariableAsyncFutureResultltvoidgt setVariableAsync(const matlabengineString ampvarName const matlabdataArray var WorkspaceType workspaceType = WorkspaceTypeBASE)

1 API Reference

1-142

Put a variable into the MATLAB base or global workspace asynchronously If a variablewith the same name exists in the MATLAB base workspace setVariableAsyncoverwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

None

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )FutureResultltvoidgt future = matlabPtr-gt setVariableAsync(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from MATLAB to C++rdquo

getPropertymatlabdataArray getProperty(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property

matlabengineMATLABEngine

1-143

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

matlabdataArray

Value of the named property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetProperty returns the exception messageproperty value as a matlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(try surf(4) catch me end))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))matlabdataCharArray message = matlabPtr-gt getProperty(mException convertUTF8StringToUTF16String(message))stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

getPropertyAsyncFutureResultltmatlabdataArraygt getPropertyAsync(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property asynchronously

1 API Reference

1-144

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

FutureResult FutureResult object that is used to synchronize the operation

None

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetPropertyAsync returns a FutureResultthat you use to get the exception message property value as amatlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(trysurf(4)catch meend))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))FutureResultltmatlabdataArraygt future = matlabPtr-gt getPropertyAsync(mException convertUTF8StringToUTF16String(message))matlabdataCharArray message = futureget()stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

setPropertyvoid setProperty(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property

matlabdataArray ampobject

MATLAB object

matlabengineMATLABEngine

1-145

const StringamppropertyName

Name of the property to set

constmatlabdataArray amppropertyValue

Value assigned to the property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example shows how to set a MATLAB object property It creates a MATLAB graphand returns the line handle object Setting the value of the line LineStyle property tothe character changes the property value of the line object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray()matlabPtr-gtsetProperty(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

setPropertyAsyncFutureResultltvoidgt setPropertyAsync(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property asynchronously

matlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property to set

1 API Reference

1-146

constmatlabdataArray amppropertyValue

Value assigned to the property

None

This example shows how to set a MATLAB object property asynchronously It creates aMATLAB graph and returns the line handle object Setting the line LineStyle propertyto the character changes the property value of the object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray() FutureResultltvoidgt future = matlabPtr-gt setPropertyAsync(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

See Also

Introduced in R2017b

matlabengineMATLABEngine

1-147

matlabengineconnectMATLABConnect to shared MATLAB session synchronously

Descriptionstdunique_ptrltMATLABEnginegt connectMATLAB()

stdunique_ptrltMATLABEnginegt connectMATLAB(constmatlabengineStringamp name)

Connect synchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-148

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to a MATLABEngine object

ExceptionsmatlabengineEngineException

Throws exception if function fails to connect to the specified MATLABsession

Examples

Connect to Shared MATLAB Session

Connect to a shared MATLAB session named my_matlab

stdunique_ptrltMATLABEnginegt matlabPrt = connectMATLAB(convertUTF8StringToUTF16String(my_matlab))

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineconnectMatlabAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

matlabengineconnectMATLAB

1-149

matlabengineconnectMATLABAsyncConnect to shared MATLAB session asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync()

FutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync(constmatlabengineStringamp name)

Connect asynchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-150

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object that you can use to get the pointer to theMATLABEngine

Examples

Connect to Shared MATLAB Session Asynchronously

Connect to a shared MATLAB session named my_matlab asynchronously Use theFutureResult get method to retrieve the pointer to the MATLABEngine objectFutureResultsltstdunique_ptrltMATLABEnginegtgt future = connectMATLABAsync(convertUTF8StringToUTF16String(my_matlab))stdunique_ptrltMATLABEnginegt matlabPtr = futureget()

bull ldquoConnect C++ to Running MATLAB Sessionrdquo

See AlsomatlabengineconnectMatlab

TopicsldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

matlabengineconnectMATLABAsync

1-151

matlabengineconvertUTF8StringToUTF16StringConvert UTF-8 string to UTF-16 string

Descriptionstdbasic_stringltchar16_tgt convertUTF8StringToUTF16String(conststdstringamp utf8string)

Convert a UTF-8 string to a UTF-16 string Use this function to convert ASCII strings tomatlabengineString strings which are required by MATLAB C++ Enginefunctions

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdstringamputf8string

A UTF-8 string

Return Valuestdbasic_stringltchar16_tgt

A UTF-16 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-152

matlabengineTypeConversionException

The input type cannot be converted tostdbasic_stringltchar16_tgt

Examples

Convert String

Convert a UTF-8 string to a matlabengineString (UTF-16 string)

matlabengineString matlabStatement = convertUTF8StringToUTF16String(sqrt(127))

See AlsomatlabengineString |matlabengineconvertUTF16StringToUTF8String

Introduced in R2017b

matlabengineconvertUTF8StringToUTF16String

1-153

matlabengineconvertUTF16StringToUTF8StringConvert UTF-16 string to UTF-8 string

Descriptionstdstring convertUTF16StringToUTF8String(conststdbasic_stringltchar16_tgtamp utf16string)

Convert a UTF-16 string to a UTF-8 string

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdbasic_stringltchar16_tgtamputf16string

A UTF-16 string

Return Valuestdstring A UTF-8 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-154

matlabengineTypeConversionException

The input type cannot be converted to stdstring

Examples

Convert String

Convert a matlabengineString (UTF-16 string) to a stdstring (UTF-8string)

matlabengineString matlabStatement = (usqrt(127))stdstring cmdString = convertUTF16StringToUTF8String(matlabStatement)

See AlsomatlabengineString |matlabengineconvertUTF8StringToUTF16String

Introduced in R2017b

matlabengineconvertUTF16StringToUTF8String

1-155

matlabenginefindMATLABFind shared MATLAB sessions synchronously

DescriptionstdvectorltStringgt findMATLAB()

Find all shared MATLAB sessions on the local machine

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValuestdvectorltStringgt

A vector of the names of all shared MATLAB sessions on the localmachine or an empty vector if no shared MATLAB sessions areavailable

ExceptionsmatlabengineEngineException

Throws exception if the call fails while searching for shared MATLABsessions

Examples

1 API Reference

1-156

Find Shared MATLAB Session Synchronously

stdvectorltStringgt names = findMATLAB()

See AlsomatlabenginefindMATLABAsync

Introduced in R2017b

matlabenginefindMATLAB

1-157

matlabenginefindMATLABAsyncFind shared MATLAB sessions asynchronously

DescriptionFutureResultltstdvectorltStringgtgt findMATLABAsync()

Find all shared MATLAB sessions on the local machine asynchronously

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValueFutureResultltstdvectorltStringgtgt

A FutureResult object that you can use to get the names of sharedMATLAB sessions on the local machine

Examples

Find Shared MATLAB Session Asynchronously

Find the names of all shared MATLAB sessions on the local machine asynchronouslyUse the FutureResult get method to retrieve the names

1 API Reference

1-158

FutureResultltstdvectorltStringgtgt futureNames = findMATLABAsync()stdvectorltStringgt matlabSessions = futureNamesget()

See AlsomatlabenginefindMATLAB

Introduced in R2017b

matlabenginefindMATLABAsync

1-159

matlabengineFutureResultRetrieve result from asynchronous operation

DescriptionA future result is an object that you can use to retrieve the result of MATLAB functionsor statements The FutureResult class provides all member functions of the C++stdfuture class

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Functions Delegated to stdfutureoperator= share get wait wait_for wait_until

1 API Reference

1-160

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement You cannot cancelasynchronous operations that use matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution had already begun

bool Was command canceled if execution had already begun

bool flag = futurecancel()

No exceptions thrown

matlabengineFutureResult

1-161

See Also

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

1 API Reference

1-162

matlabenginestartMATLABStart MATLAB synchronously

Descriptionstdunique_ptrltMATLABEnginegt startMATLAB(const stdvectorltStringgtampoptions = stdvectorltStringgt())

Start MATLAB synchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtampoptions

Options used to start MATLAB See ldquoSpecify Startup Optionsrdquo

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to the MATLABEngine object

matlabenginestartMATLAB

1-163

ExceptionsmatlabengineEngineException

MATLAB failed to start

Examples

Start MATLAB Synchronously

Start MATLAB synchronously and return a unique pointer to the MATLABEngine object

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Start MATLAB with Startup Options

Start MATLAB with the -nojvm option and return a unique pointer to theMATLABEngine object

stdvectorltStringgt optionVecoptionVecpush_back(convertUTF8StringToUTF16String(-nojvm))stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB(optionVec)

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineMATLABEngine | matlabenginestartMATLABAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

1 API Reference

1-164

matlabenginestartMATLABAsyncStart MATLAB asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt startMATLABAsync(conststdvectorltStringgtamp options = stdvectorltStringgt())

Start MATLAB asynchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtamp options

Startup options used to launch MATLAB

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object used to get the pointer to theMATLABEngine

Examples

matlabenginestartMATLABAsync

1-165

Start MATLAB Asynchronously

Start MATLAB asynchronously and return a FutureResult object Use theFutureResult to get a pointer to the MATLABEngine objectFutureResultltstdunique_ptrltMATLABEnginegtgt matlabFuture = startMATLAB()stdunique_ptrltMATLABEnginegt matlabPtr = matlabFutureget()

bull ldquoSpecify Startup Optionsrdquo

See AlsomatlabenginestartMATLAB

TopicsldquoSpecify Startup Optionsrdquo

Introduced in R2017b

1 API Reference

1-166

matlabengineterminateEngineClientFree engine resources during runtime

Descriptionvoid matlabengineterminateEngineClient releases all MATLAB engineresources during runtime when you no longer need the MATLAB engine in yourapplication program

Note Programs cannot start a new MATLAB engine or connect to a shared MATLABsession after calling terminateEngineClient

IncludeNamespace matlabengineInclude MatlabEnginehpp

ExamplesTerminate the engine session to free resources Start MATLAB sessionstdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Terminate MATLAB sessionmatlabengineterminateEngineClient()

See AlsomatlabenginestartMATLAB

Introduced in R2017b

matlabengineterminateEngineClient

1-167

matlabengineWorkspaceTypeType of MATLAB workspace

DescriptionThe matlabengineWorkspaceType enum class specifies the MATLAB workspaceto pass variables to or get variables fromBASE Variables scoped to the MATLAB base workspace

(command line and nonfunction scripts)GLOBAL Variables scoped to the MATLAB global workspace

(command line functions and scripts)

MATLAB scopes variables by workspace Variables that are scoped to the baseworkspace must be passed to functions as arguments Variables scoped to the globalworkspace can be accessed by any function that defines the specific variable name asglobal

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

ExamplesThis example

bull Connects to a shared MATLAB sessionbull Creates a matlabdataArray containing numeric values of type doublebull Puts the array in the MATLAB global workspaceinclude MatlabDataArrayhppinclude MatlabEnginehppinclude ltiostreamgt

static void putGlobalVar()

1 API Reference

1-168

using namespace matlabengine

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

Create matlab data array factory matlabdataArrayFactory factory

Create data variable matlabdataArray data = factorycreateArrayltdoublegt ( 1 5 40 110 47 362 723 )

Put data variable in MATLAB global workspace matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data WorkspaceTypeGLOBAL)

See AlsomatlabdataArrayFactory | matlabengineMATLABEngine |matlabengineconvertUTF8StringToUTF16String

TopicsldquoPass Variables from C++ to MATLABrdquoldquoPass Variables from MATLAB to C++rdquo

Introduced in R2017b

matlabengineWorkspaceType

1-169

matlabengineStringDefine UTF16 string

DescriptionType definition for stdbasic_stringltchar16_tgt

ExamplesThis example defines a variable containing the name of a shared MATLAB session Passthis string to the matlabengineconnectMATLAB function to connect to the namedsessionmatlabengineString session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

See AlsomatlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoMATLAB Engine API for C++rdquoldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

1 API Reference

1-170

matlabengineStreamBufferDefine stream buffer

DescriptionType definition for stdbasic_streafbufltchar16_tgt

ExamplesThis example defines string buffers to return output from the evaluation of a MATLABfunction by the MATLABEngineeval member function This function uses a bufferderived from matlabengineStreamBuffer to return output from MATLAB to C++include MatlabEnginehppinclude MatlabDataArrayhppinclude ltiostreamgt

using namespace matlabengineusing SBuf = stdbasic_stringbufltchar16_tgt

void printFromBuf(const stdshared_ptrltSBufgt buf) Get text from buf auto text_ = buf-gtstr() stdcout ltlt ltlt convertUTF16StringToUTF8String(text_) ltlt ltlt stdendl

int main()

Create Array factory matlabdataArrayFactory factory

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

auto outBuf = stdmake_sharedltSBufgt() auto errBuf = stdmake_sharedltSBufgt()

matlabPtr-gteval(convertUTF8StringToUTF16String(matlabengineengineName) outBuf errBuf) printFromBuf(outBuf) printFromBuf(errBuf) return 0

matlabengineStreamBuffer

1-171

See AlsomatlabengineconnectMATLAB |matlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoRedirect MATLAB Command Window Output to C++rdquo

Introduced in R2017b

1 API Reference

1-172

matlabengineSharedFutureResultRetrieve result from asynchronous operation as shared future

DescriptionA shared future result is an object that you use to retrieve the result of MATLABfunctions or statements any number of times

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using one of these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Function Delegated to stdshared_futureoperator= get valid wait wait_for wait_until

matlabengineSharedFutureResult

1-173

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement

Note that you cannot cancel asynchronous start connection or find operations which areinitiated using these functions matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution has already begun

bool True if the MATLAB command can be canceled

bool flag = futurecancel()

None

1 API Reference

1-174

See AlsomatlabengineFutureResult

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

matlabengineSharedFutureResult

1-175

commathworksengineMatlabEngine classPackage commathworksengine

Java class using MATLAB as a computational engine

DescriptionThe commathworksengineMatlabEngine class uses a MATLAB process as acomputational engine for Javareg This class provides an interface between the Javalanguage and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom Java

Constructor SummaryThe MatlabEngine class provides static methods to start MATLAB and to connect to ashared MATLAB session synchronously or asynchronously Only these static methodscan instantiate this class

bull Start MATLAB synchronously mdash ldquostartMatlabrdquo on page 1-178bull Connect to shared MATLAB session synchronously mdash ldquoconnectMatlabrdquo on page 1-180bull Start MATLAB asynchronously mdash ldquostartMatlabAsyncrdquo on page 1-179bull Connect to shared MATLAB session asynchronously mdash ldquoconnectMatlabAsyncrdquo on

page 1-181

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -n

1 API Reference

1-176

bull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup Optionsrdquo

Method Summary

Static MethodsldquostartMatlabrdquo onpage 1-178

Start MATLAB synchronously

ldquostartMatlabAsyncrdquoon page 1-179

Start MATLAB asynchronously

ldquofindMatlabrdquo onpage 1-179

Find all available shared MATLAB sessions from a local machinesynchronously

ldquofindMatlabAsyncrdquoon page 1-180

Find all available shared MATLAB sessions from a local machineasynchronously

ldquoconnectMatlabrdquo onpage 1-180

Connect to a shared MATLAB session on a local machinesynchronously

ldquoconnectMatlabAsyncrdquo on page 1-181

Connect to a shared MATLAB session on a local machineasynchronously

Member VariableNULL_WRITER Use a writer that ignores the contents from the MATLAB

command window

Member Functionsldquofevalrdquo on page 1-182

Evaluate a MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-183

Evaluate a MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-184 Evaluate a MATLAB expression as a string synchronously

commathworksengineMatlabEngine class

1-177

ldquoevalAsyncrdquo on page1-185

Evaluate a MATLAB expression as a string asynchronously

ldquogetVariablerdquo onpage 1-186

Get a variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-187

Get a variable from the MATLAB base workspace asynchronously

ldquoputVariablerdquo onpage 1-187

Put a variable into the MATLAB base workspace synchronously

ldquoputVariableAsyncrdquoon page 1-188

Put a variable into the MATLAB base workspace asynchronously

ldquodisconnectrdquo on page1-188

Disconnect from the current MATLAB session synchronously

ldquodisconnectAsyncrdquoon page 1-189

Disconnect from the current MATLAB session asynchronously

ldquoquitrdquo on page 1-189 Force the shutdown of the current MATLAB sessionsynchronously

ldquoquitAsyncrdquo on page1-189

Force the shutdown of the current MATLAB sessionasynchronously

ldquocloserdquo on page 1-190

Disconnect or terminate the current MATLAB session

Method Details

startMatlabstatic MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Start MATLAB synchronously

String[] options Startup options used to start MATLAB engine For options seeldquoStartup and Shutdownrdquo

1 API Reference

1-178

Instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start

MatlabEngine engine = MatlabEnginestartMatlab()

ldquoStart and Close MATLAB Session from Javardquo

startMatlabAsyncstatic FutureltMatlabEnginegt startMatlabAsync(String[] options)

static FutureltMatlabEnginegt startMatlabAsync()

Start MATLAB asynchronously

String[] options Startup options used to start MATLAB For options seeldquoStartup and Shutdownrdquo

Instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEnginestartMatlabAsync()

ldquoStart and Close MATLAB Session from Javardquo

findMatlabstatic String[] findMatlab()

Find all shared MATLAB sessions on the local machine synchronously

commathworksengineMatlabEngine class

1-179

An array of the names of all shared MATLAB sessions on the local machine or an emptyvector if there are no shared MATLAB sessions available on the local machine

commathworksengineEngineException

If there is a failure during the search for MATLAB sessions

String[] engines = MatlabEnginefindMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

findMatlabAsyncstatic FutureltSting[]gt findMatlabAsync()

Find all shared MATLAB sessions on local machine asynchronously

An instance of FutureltString[]gt

FutureltString[]gt future = MatlabEnginefindMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabstatic MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Connect to a shared MATLAB session on local machine synchronously

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session with default options

1 API Reference

1-180

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

String name Name of the shared MATLAB session Use ldquofindMatlabrdquo on page1-179 to get the names of shared MATLAB sessions

An instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start or connect

MatlabEngine engine = MatlabEngineconnectMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabAsyncstatic FutureltMatlabEnginegt connectMatlabAsync(String name)

static FutureltMatlabEnginegt connectMatlabAsync

Connect to a shared MATLAB session on local machine asynchronously The behavior isthe same as that of connectMatlab except the mechanism is asynchronous

String name Name of the shared MATLAB session

An instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEngineconnectMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

commathworksengineMatlabEngine class

1-181

fevalltTgt T feval(int nlhs String func Writer output Writer errorObjecthellip args)

ltTgt T feval(int nlhs String func Objecthellip args)

ltTgt T feval(String func Writer output Writer error Objecthellip args)

ltTgt T feval(String func Objecthellip args)

Evaluate MATLAB functions with input arguments synchronously

String func Name of the MATLAB function or script to evaluateint nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

Result of executing the MATLAB function

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

1 API Reference

1-182

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is a MATLAB runtime error in the function

commathworksengineUnsupportedTypeExeption

There is an unsupported data type

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB function

double result = enginefeval(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

fevalAsyncltTgt FutureltTgt fevalAsync(int nlhs String func Writer outputWriter error Objecthellip args)

ltTgt FutureltTgt fevalAsync(int nlhs String func Objecthellip args)

ltTgt FutureltTgt fevalAsync(String func Writer output Writer errorObjecthellip args)

ltTgt FutureltTgt fevalAsync(String func Objecthellip args)

Evaluate MATLAB functions with input arguments asynchronously

String func Name of the MATLAB function or script to evaluate

commathworksengineMatlabEngine class

1-183

int nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginefevalAsync(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

evalvoid eval(String command Writer output Writer error)

void eval(String command)

Evaluate a MATLAB statement as a string synchronously

1 API Reference

1-184

String command MATLAB statement to evaluateWriter output Stream used to store the standard output from the MATLAB

statement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABstatement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is an error in the MATLAB statement duringruntime

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB statement

engineeval(result = sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

evalAsyncFutureltVoidgt evalAsync(String command Writer output Writer error)

FutureltVoidgt evalAsync(String command)

Evaluate a MATLAB statement as a string asynchronously

String command MATLAB statement to evaluate

commathworksengineMatlabEngine class

1-185

Writer output Stream used to store the standard output from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the output from the MATLABcommand window

Writer error Stream used to store the standard error from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the error message from theMATLAB command window

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineevalAsync(sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

getVariableltTgt T getVariable(String varName)

Get a variable from the MATLAB base workspace

String varName Name of a variable in the MATLAB base workspace

Variable passed from the MATLAB base workspace

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

1 API Reference

1-186

javalangIllegalStateException

The MATLAB session is not available

double myVar = enginegetVariable(myVar)

ldquoPass Variables from MATLAB to Javardquo

getVariableAsyncltTgt FutureltTgt getVariableAsync(String varName)

Get a variable from the MATLAB base workspace asynchronously

String varName Name of a variable in MATLAB base workspace

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginegetVariableAsync(myVar)

ldquoPass Variables from MATLAB to Javardquo

putVariablevoid putVariable(String varName T varData)

Put a variable into the MATLAB base workspace

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

commathworksengineMatlabEngine class

1-187

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

javalangIllegalStateException

The MATLAB session is not available

engineputVariable(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

putVariableAsyncFutureltVoidgt putVariableAsync(String varName T varData)

Put a variable into the MATLAB base workspace asynchronously

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineputVariableAsync(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

disconnectvoid disconnect()

Disconnect from the current MATLAB session

1 API Reference

1-188

commathworksengineEngineException

The current MATLAB session cannot be disconnected

enginedisconnect()

ldquoClose MATLAB Engine Sessionrdquo

disconnectAsyncFutureltVoidgt disconnectAsync()

Disconnect from the current MATLAB session

FutureltVoidgt future = enginedisconnectAsync()

ldquoClose MATLAB Engine Sessionrdquo

quitviod quit()

Force the shutdown of the current MATLAB session

commathworksengineEngineException

The current MATLAB session cannot be shut down

enginequit()

ldquoClose MATLAB Engine Sessionrdquo

quitAsyncFutureltVoidgt quitAsync()

commathworksengineMatlabEngine class

1-189

Force the shutdown of the current MATLAB session asynchronously without waiting fortermination

An instance of FutureltVoidgt

FutureltVoidgt future = enginequitAsync()

ldquoClose MATLAB Engine Sessionrdquo

closevoid close()

MatlabEngine provides the close() method to implement thejavalangAutoCloseable interface for MatlabEngine objects This close()method enables you to use a try-with-resources statement to automatically disconnect orterminate the MATLAB session at the end of the statement

The MatlabEngine close() method disconnects or terminates the current MATLABsession depending on the context

bull If a Java process starts the MATLAB session as a default non-shared sessionclose() terminates MATLAB

bull If the MATLAB session is a shared session close() disconnects MATLAB from thisJava process MATLAB terminates when there are no other connections

To force the shutdown or disconnection of the current MATLAB session explicitly callMatlabEnginequit() MatlabEnginedisconnect() or their asynchronouscounterparts

engineclose()

ldquoClose MATLAB Engine Sessionrdquo

1 API Reference

1-190

Examples

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously The workflowis

bull Open a MATLAB sessionbull Invoke the MATLAB sqrt function with arguments asynchronouslybull Get the result of the MATLAB functionbull Close the MATLAB engine

import commathworksengineMatlabEngine

FutureltMatlabEnginegt engFuture = MatlabEnginestartMatlabAsync()MatlabEngine engine = engFutureget()double myVar = 4FutureltDoublegt future = enginefevalAsync(sqrt myVar)double result = futureget()Systemoutprintln(result)

See AlsomatlabengineengineName | matlabengineisEngineShared |matlabengineshareEngine

TopicsldquoBuild Java Engine ProgramsrdquoldquoStart and Close MATLAB Session from Javardquo

Introduced in R2016b

commathworksengineMatlabEngine class

1-191

commathworksmatlabtypesComplex classPackage commathworksmatlabtypes

Java class to pass complex data to and from MATLAB

DescriptionThe Complex class provides Java support for MATLAB complex arrays Use this class topass complex data to MATLAB The MATLAB engine passes complex data to Java as aninstance of Complex

All MATLAB numeric types are converted to double in Java

Constructor SummaryComplex(double real double imag) constructs an instance of Complex with thespecified real and imaginary values

Field Summarydouble real The real part of the complex datadouble imag The imaginary part of the complex data

Examples

Pass Complex Variable to MATLAB Function

import commathworksengineMatlabEngine

MatlabEngine engine = MatlabEnginestartMatlab()

1 API Reference

1-192

Complex c = new Complex(23)Complex cj = enginefeval(conjc)

bull ldquoUsing Complex Variables in Javardquo

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoUsing Complex Variables in Javardquo

Introduced in R2016b

commathworksmatlabtypesComplex class

1-193

commathworksmatlabtypesHandleObject classPackage commathworksmatlabtypes

Java class to represent MATLAB handle objects

DescriptionJava represents handle objects that are passed from MATLAB as instances of theHandleObject class When passing a handle object back to MATLAB Java passes areference to the HandleObject instance This reference can be either an array or ascalar depending on the original handle object passed to Java from MATLAB

You can pass a handle object only to the MATLAB session in which it was originallycreated You cannot construct a HandleObject in Java

Examples

Get Handle Object from MATLAB

This example starts a shared MATLAB session and creates a containersMap object inthe MATLAB workspace The statement evaluated in the MATLAB workspace returns ahandle variable that refers to the Map object

The engine getVariable function returns the MATLAB handle variable as aHandleObject instance This instance is used to call the MATLABcontainersMapkeys function to obtain the Map keys

import commathworksengineMatlabEngineimport commathworksmatlabtypes

MatlabEngine engine = MatlabEnginestartMatlab()engineeval(cm = containersMap(idname11mw))

1 API Reference

1-194

HandleObject handle = enginegetVariable(cm)String[] cells = enginefeval(keys handle)

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex | commathworksmatlabtypesStruct

TopicsldquoUsing MATLAB Handle Objects in Javardquo

Introduced in R2016b

commathworksmatlabtypesHandleObject class

1-195

commathworksmatlabtypesStruct classPackage commathworksmatlabtypes

Java class to pass MATLAB struct to and from MATLAB

DescriptionThe Struct class provides support for passing data between MATLAB and Java as aMATLAB struct The Struct class implements the javautilMap interface

The Struct class is designed as an immutable type Attempting to change the mappingskeys or values of the returned Struct causes an UnsupportedOperationExceptionCalling these methods can cause the exception put() putAll() remove()entrySet() keySet() and values()

For an example see ldquoUsing MATLAB Structures in Javardquo

Constructor SummaryStruct s = new Struct(field1value1field2value2 ) creates aninstance of Struct with the specified field names and values

Method SummarycontainsKey(Object key) Returns true if this map contains a

mapping for the specified keycontainsValue(Object value) Returns true if this map maps one or more

keys to the specified valueentrySet() Returns a Set view of the mappings

contained in this mapequals(Object o) Compares the specified object with this

map for equality

1 API Reference

1-196

get(Object key) Returns the value to which the specifiedkey is mapped or null if this map containsno mapping for the key

hashCode() Returns the hash code value for this mapisEmpty() Returns true if this map contains no key-

value mappingskeySet() Returns a Set view of the keys contained

in this mapsize() Returns the number of key-value mappings

in this mapvalues() Returns a Collection view of the values

contained in this map

Examples

Create Struct for MATLAB Function Argument

Create a Struct and assign a key and value

import commathworksengineimport commathworksmatlabtypes

class StructProperties public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() int[] y = 12345 double[] color = 100507 Struct s = new Struct(ColorcolorLineWidth2) engfeval(plotys)

bull ldquoUsing MATLAB Structures in Javardquo

commathworksmatlabtypesStruct class

1-197

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject

TopicsldquoUsing MATLAB Structures in Javardquo

Introduced in R2016b

1 API Reference

1-198

commathworksmatlabtypesCellStr classPackage commathworksmatlabtypes

Java class to represent MATLAB cell array of char vectors

DescriptionThe CellStr class provides support for passing data from Java to MATLAB as aMATLAB cell array of char vectors (called a cellstr in MATLAB see cellstr) Thereare MATLAB functions that require cell arrays of char vectors as inputs To passarguments from Java to a MATLAB function requiring cellst inputs use the JavaCellStr class to create a compatible type

A MATLAB cellstr is mapped to a Java String array

Constructor SummaryCellStr(Object stringArray) creates a CellStr using a String or String arrayThe String array can have multiple dimensions

Method SummaryObject getStringArray() Get the String or String array used to

create the CellStrboolean equals(CellStr1CellStr2) Compare one CellStr instance with

another Two CellStr instances are equalif the String or String array they containare the same

commathworksmatlabtypesCellStr class

1-199

Examples

Construct CellStrThis example constructs a CellStr named keySet and puts the variable in theMATLAB base workspaceimport commathworksengineimport commathworksmatlabtypes

class javaCellstr public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() CellStr keySet = new CellStr(new String[]JanFebMarApr) engputVariable(mapKeyskeySet) engclose()

Construct CellStr Array

This example creates a CellStr array and passes it to the MATLAB plot function tochange the appearance of the graph produced by MATLAB The call to the MATLABprint function exports the figure as a jpeg file named myPlotjpg

import commathworksengineimport commathworksmatlabtypes

class CellStrArray public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() String[][] strArray = new String[2][2] strArray[0][0] = MarkerFaceColor strArray[0][1] = MarkerEdgeColor strArray[1][0] = green strArray[1][1] = red CellStr markerCellStr = new CellStr(strArray) engputVariable(MmarkerCellStr) engeval(plot(110--bsM)) engeval(print(myPlot-djpeg)) engclose()

1 API Reference

1-200

See AlsocommathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoPass Java CellStr to MATLABrdquo

Introduced in R2016b

commathworksmatlabtypesCellStr class

1-201

engClose (C and Fortran)Quit MATLAB engine session

C Syntaxinclude enginehint engClose(Engine ep)

Fortran Syntaxinclude enginehinteger4 engClose(ep)mwPointer ep

Argumentsep

Engine pointer

Returns0 on success and 1 otherwise Possible failure includes attempting to terminate analready-terminated MATLAB engine session

DescriptionThis routine sends a quit command to the MATLAB engine session and closes theconnection

1 API Reference

1-202

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIXreg operating systemsbull engwindemoc for a C example on Microsoftreg Windowsreg operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen

Introduced before R2006a

engClose (C and Fortran)

1-203

engEvalString (C and Fortran)Evaluate expression in string

C Syntaxinclude enginehint engEvalString(Engine ep const char string)

Fortran Syntaxinclude enginehinteger4 engEvalString(ep string)mwPointer epcharacter() string

Argumentsep

Engine pointerstring

String to execute

Returns1 if the engine session is no longer running or the engine pointer is invalid or NULLOtherwise returns 0 even if the MATLAB engine session cannot evaluate the command

DescriptionengEvalString evaluates the expression contained in string for the MATLAB enginesession ep previously started by engOpen

1 API Reference

1-204

UNIX Operating Systems

On UNIX systems engEvalString sends commands to the MATLAB workspace bywriting down a pipe connected to the MATLAB stdin process MATLAB reads back fromstdout any output resulting from the command that ordinarily appears on the screeninto the buffer defined by engOutputBuffer

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Microsoft Windows Operating Systems

On a Windows system engEvalString communicates with MATLAB software using aComponent Object Model (COM) interface

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engOutputBuffer

Introduced before R2006a

engEvalString (C and Fortran)

1-205

engGetVariable (C and Fortran)Copy variable from MATLAB engine workspace

C Syntaxinclude enginehmxArray engGetVariable(Engine ep const char name)

Fortran Syntaxinclude enginehmwPointer engGetVariable(ep name)mwPointer epcharacter() name

Argumentsep

Engine pointername

Name of mxArray to get from MATLAB workspace

ReturnsPointer to a newly allocated mxArray structure or NULL if the attempt failsengGetVariable fails if the named variable does not exist

DescriptionengGetVariable reads the named mxArray from the MATLAB engine sessionassociated with ep

1 API Reference

1-206

The limit for the size of data transferred is 2 GB

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengPutVariable mxDestroyArray

Introduced before R2006a

engGetVariable (C and Fortran)

1-207

engGetVisible (C)Determine visibility of MATLAB engine session

C Syntaxinclude enginehint engGetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Pointer to value returned from engGetVisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengGetVisible returns the current visibility setting for MATLAB engine session ep Avisible engine session runs in a window on the Windows desktop thus making the engineavailable for user interaction MATLAB removes an invisible session from the desktop

ExamplesThe following code opens engine session ep and disables its visibility

1 API Reference

1-208

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengSetVisible

engGetVisible (C)

1-209

Engine (C)Type for MATLAB engine

DescriptionA handle to a MATLAB engine object

Engine is a C language opaque type

You can call MATLAB software as a computational engine by writing C and Fortranprograms that use the MATLAB engine library Engine is the link between yourprogram and the separate MATLAB engine process

The header file containing this type is

include engineh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc shows how to call the MATLAB engine functions from a C programbull engwindemoc show how to call the MATLAB engine functions from a C program for

Windows systemsbull fengdemoF shows how to call the MATLAB engine functions from a Fortran

program

See AlsoengOpen

1 API Reference

1-210

engOpen (C and Fortran)Start MATLAB engine session

C Syntaxinclude enginehEngine engOpen(const char startcmd)

Fortran Syntaxinclude enginehmwPointer engOpen(startcmd)character() startcmd

Argumentsstartcmd

String to start the MATLAB process On Windows systems the startcmd stringmust be NULL

ReturnsPointer to an engine handle or NULL if the open fails

DescriptionThis routine allows you to start a MATLAB process for using MATLAB as acomputational engine

engOpen starts a MATLAB process using the command specified in the stringstartcmd establishes a connection and returns an engine pointer

engOpen (C and Fortran)

1-211

On UNIX systems if startcmd is NULL or the empty string engOpen starts a MATLABprocess on the current host using the command matlab If startcmd is a hostnameengOpen starts a MATLAB process on the designated host by embedding the specifiedhostname string into the larger string

rsh hostname bincsh -c setenv DISPLAY hostname0 matlab

If startcmd is any other string (has white space in it or nonalphanumeric characters)MATLAB executes the string literally

On UNIX systems engOpen performs the following steps

1 Creates two pipes2 Forks a new process Sets up the pipes to pass stdin and stdout from MATLAB

(parent) software to two file descriptors in the engine program (child)3 Executes a command to run MATLAB software (rsh for remote execution)

On Windows systems engOpen opens a COM channel to MATLAB The MATLABsoftware you registered during installation starts If you did not register duringinstallation enter the following command at the MATLAB prompt

matlab -regserver

See ldquoMATLAB COM Integrationrdquo for additional details

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

Introduced before R2006a

1 API Reference

1-212

engOpenSingleUse (C)Start MATLAB engine session for single nonshared use

C Syntaxinclude enginehEngine engOpenSingleUse(const char startcmd void dcom int retstatus)

Argumentsstartcmd

String to start MATLAB process On Microsoft Windows systems the startcmdstring must be NULL

dcomReserved for future use must be NULL

retstatusReturn status possible cause of failure

Returns

Microsoft Windows Operating Systems Only

Pointer to an engine handle or NULL if the open fails

UNIX Operating Systems

Not supported on UNIX systems

engOpenSingleUse (C)

1-213

DescriptionThis routine allows you to start multiple MATLAB processes using MATLAB as acomputational engine

engOpenSingleUse starts a MATLAB process establishes a connection and returns aunique engine identifier or NULL if the open fails Each call to engOpenSingleUsestarts a new MATLAB process

engOpenSingleUse opens a COM channel to MATLAB This starts the MATLABsoftware you registered during installation If you did not register during installationenter the following command at the MATLAB prompt

matlab -regserver

engOpenSingleUse allows single-use instances of an engine serverengOpenSingleUse differs from engOpen which allows multiple applications to use thesame engine server

See ldquoMATLAB COM Integrationrdquo for additional details

1 API Reference

1-214

engOutputBuffer (C and Fortran)Specify buffer for MATLAB output

C Syntaxinclude enginehint engOutputBuffer(Engine ep char p int n)

Fortran Syntaxinclude enginehinteger4 engOutputBuffer(ep p)mwPointer epcharactern p

Argumentsep

Engine pointerp

Pointer to character buffern

Length of buffer p

Returns1 if you pass it a NULL engine pointer Otherwise returns 0

engOutputBuffer (C and Fortran)

1-215

DescriptionengOutputBuffer defines a character buffer for engEvalString to return any outputthat ordinarily appears on the screen

The default behavior of engEvalString is to discard any standard output caused by thecommand it is executing A call to engOutputBuffer with a buffer of nonzero lengthtells any subsequent calls to engEvalString to save output in the character bufferpointed to by p

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Note The buffer returned by engEvalString is not NULL terminated

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engEvalString

Introduced before R2006a

1 API Reference

1-216

engPutVariable (C and Fortran)Put variable into MATLAB engine workspace

C Syntaxinclude enginehint engPutVariable(Engine ep const char name const mxArray pm)

Fortran Syntaxinclude enginehinteger4 engPutVariable(ep name pm)mwPointer ep pmcharacter() name

Argumentsep

Engine pointername

Name of mxArray in the engine workspacepm

mxArray pointer

Returns0 if successful and 1 if an error occurs

DescriptionengPutVariable writes mxArray pm to the engine ep giving it the variable name name

engPutVariable (C and Fortran)

1-217

If the mxArray does not exist in the workspace the function creates it If an mxArraywith the same name exists in the workspace the function replaces the existing mxArraywith the new mxArray

The limit for the size of data transferred is 2 GB

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The engine application owns the original mxArray and is responsible for freeing itsmemory Although the engPutVariable function sends a copy of the mxArray to theMATLAB workspace the engine application does not need to account for or free memoryfor the copy

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengGetVariable

Introduced before R2006a

1 API Reference

1-218

engSetVisible (C)Show or hide MATLAB engine session

C Syntaxinclude enginehint engSetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Value to set the Visible property to Set value to 1 to make the engine windowvisible or to 0 to make it invisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengSetVisible makes the window for the MATLAB engine session ep either visible orinvisible on the Windows desktop You can use this function to enable or disable userinteraction with the MATLAB engine session

engSetVisible (C)

1-219

ExamplesThe following code opens engine session ep and disables its visibility

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengGetVisible

1 API Reference

1-220

matClose (C and Fortran)Close MAT-file

C Syntaxinclude mathint matClose(MATFile mfp)

Fortran Syntaxinclude mathinteger4 matClose(mfp)mwPointer mfp

Argumentsmfp

Pointer to MAT-file information

ReturnsEOF in C (-1 in Fortran) for a write error and 0 if successful

DescriptionmatClose closes the MAT-file associated with mfp

ExamplesSee the following examples in matlabrootexternexampleseng_mat

matClose (C and Fortran)

1-221

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen

Introduced before R2006a

1 API Reference

1-222

matDeleteVariable (C and Fortran)Delete array from MAT-file

C Syntaxinclude mathint matDeleteVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathinteger4 matDeleteVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to delete

Returns0 if successful and nonzero otherwise

DescriptionmatDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp

matDeleteVariable (C and Fortran)

1-223

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

Introduced before R2006a

1 API Reference

1-224

MATFile (C and Fortran)Type for MAT-file

DescriptionA handle to a MAT-file object A MAT-file is the data file format MATLAB software usesfor saving data to your disk

MATFile is a C language opaque type

The MAT-file interface library contains routines for reading and writing MAT-files Callthese routines from your own CC++ and Fortran programs using MATFile to accessyour data file

The header file containing this type is

include math

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen matClose matPutVariable matGetVariable mxDestroyArray

MATFile (C and Fortran)

1-225

matGetDir (C and Fortran)List of variables in MAT-file

C Syntaxinclude mathchar matGetDir(MATFile mfp int num)

Fortran Syntaxinclude mathmwPointer matGetDir(mfp num)mwPointer mfpinteger4 num

Argumentsmfp

Pointer to MAT-file informationnum

Pointer to the variable containing the number of mxArrays in the MAT-file

ReturnsPointer to an internal array containing pointers to the names of the mxArrays in theMAT-file pointed to by mfp In C each name is a NULL-terminated string The numoutput argument is the length of the internal array (number of mxArrays in the MAT-file) If num is zero mfp contains no arrays

matGetDir returns NULL in C (0 in Fortran) If matGetDir fails sets num to a negativenumber

1 API Reference

1-226

DescriptionThis routine provides you with a list of the names of the mxArrays contained within aMAT-file

matGetDir allocates memory for the internal array of strings using a mxCalloc Freethe memory using mxFree when you are finished with the array

MATLAB variable names can be up to length mxMAXNAM defined in the C header filematrixh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo2F

Introduced before R2006a

matGetDir (C and Fortran)

1-227

matGetFp (C)File pointer to MAT-file

C Syntaxinclude mathFILE matGetFp(MATFile mfp)

Argumentsmfp

Pointer to MAT-file information

ReturnsC file handle to the MAT-file with handle mfp Returns NULL if mfp is a handle to aMAT-file in HDF5-based format

DescriptionUse matGetFp to obtain a C file handle to a MAT-file Standard C library routines likeferror and feof use file handle to investigate errors

Introduced before R2006a

1 API Reference

1-228

matGetNextVariable (C and Fortran)Next array in MAT-file

C Syntaxinclude mathmxArray matGetNextVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing the next mxArray from theMAT-file pointed to by mfp The function returns the name of the mxArray in name

matGetNextVariable returns NULL in C (0 in Fortran) for end of file or if there is anerror condition In C use feof and ferror from the Standard C Library to determinestatus

matGetNextVariable (C and Fortran)

1-229

DescriptionmatGetNextVariable allows you to step sequentially through a MAT-file and readevery mxArray in a single pass The function reads and returns the next mxArray fromthe MAT-file pointed to by mfp

Use matGetNextVariable immediately after opening the MAT-file with matOpen andnot with other MAT-file routines Otherwise the concept of the next mxArray isundefined

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariable is notguaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariableInfo matGetVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-230

matGetNextVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetNextVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing header information for thenext mxArray from the MAT-file pointed to by mfp The function returns the name of themxArray in name

matGetNextVariableInfo returns NULL in C (0 in Fortran) when the end of file isreached or if there is an error condition In C use feof and ferror from the Standard CLibrary to determine status

matGetNextVariableInfo (C and Fortran)

1-231

DescriptionmatGetNextVariableInfo loads only the array header information includingeverything except pr pi ir and jc from the current file offset

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetNextVariableInfo sets them to -1 instead These headers are forinformational use only Never pass this data back to the MATLAB workspace or save it toMAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariableInfo isnot guaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariable matGetVariableInfo

Introduced before R2006a

1 API Reference

1-232

matGetVariable (C and Fortran)Array from MAT-file

C Syntaxinclude mathmxArray matGetVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing the mxArray named byname from the MAT-file pointed to by mfp

matGetVariable returns NULL in C (0 in Fortran) if the attempt to return the mxArraynamed by name fails

matGetVariable (C and Fortran)

1-233

DescriptionThis routine allows you to copy an mxArray out of a MAT-file

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-234

matGetVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing header information for themxArray named by name from the MAT-file pointed to by mfp

matGetVariableInfo returns NULL in C (0 in Fortran) if the attempt to return headerinformation for the mxArray named by name fails

matGetVariableInfo (C and Fortran)

1-235

DescriptionmatGetVariableInfo loads only the array header information including everythingexcept pr pi ir and jc It recursively creates the cells and structures through theirleaf elements but does not include pr pi ir and jc

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetVariableInfo sets them to -1 instead These headers are for informational useonly Never pass this data back to the MATLAB workspace or save it to MAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomatGetVariable

Introduced before R2006a

1 API Reference

1-236

matlabengineconnect_matlabConnect shared MATLAB session to MATLAB Engine for Python

Syntaxeng = matlabengineconnect_matlab(name=None)eng = matlabengineconnect_matlab( ___ async)

Descriptioneng = matlabengineconnect_matlab(name=None) connects to the sharedMATLAB session name and returns a MatlabEngine object as eng The inputargument name specifies the name of a MATLAB session that is already running on yourlocal machine

bull If you specify name and the engine cannot find a shared MATLAB session of the samename then you receive an EngineError exception

bull If you do not specify name and the engine cannot find any shared MATLAB sessionsthen it starts a new shared MATLAB session If there are shared MATLAB sessionsrunning the engine connects to the first available session

bull If you do not specify name and the engine finds multiple shared MATLAB sessionsrunning then it connects to the first available session

eng = matlabengineconnect_matlab( ___ async) connects asynchronously ifasync is True

Examples

Connect to MATLAB Session

Connect to a shared MATLAB session that is already running on your local machine

matlabengineconnect_matlab

1-237

import matlabengineeng = matlabengineconnect_matlab()engsqrt(40)

20

matlabengineconnect_matlab connects to the first available shared MATLABsession If no MATLAB sessions are shared matlabengineconnect_matlab starts anew session

Connect to MATLAB Sessions by Name

When there are multiple shared MATLAB sessions on your local machine connect to twodifferent sessions one at a time by specifying their names

Connect to the first shared MATLAB session

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

Connect to the second shared MATLAB session

eng = matlabengineconnect_matlab(MATLAB_7090)engsqrt(40)

20

bull ldquoConnect Python to Running MATLAB Sessionrdquo

Input Argumentsname mdash Name of shared MATLAB sessioncharacter array

Name of the shared MATLAB session specified as a character array

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

1 API Reference

1-238

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

Output Argumentseng mdash Pythonreg variable for communicating with MATLABMatlabEngine object

Python variable for communicating with MATLAB returned as a MatlabEngine objecteng communicates with a shared MATLAB session that is already running on your localmachine

Limitationsbull Do not connect the engine multiple times to the same shared MATLAB session

See AlsomatlabengineMatlabEngine | matlabenginefind_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabengineconnect_matlab

1-239

matlabenginefind_matlabFind shared MATLAB sessions to connect to MATLAB Engine for Python

Syntaxnames = matlabenginefind_matlab()

Descriptionnames = matlabenginefind_matlab() finds all shared MATLAB sessions on yourlocal machine and returns their names in a tuple Any name in names can be the inputargument to matlabengineconnect_matlab If there are no shared sessionsrunning on your local machine matlabenginefind_matlab returns an emptytuple

Examples

Find Shared MATLAB Sessions

Identify the shared MATLAB sessions running on your local machine and connect to oneof them

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

There are two shared MATLAB sessions running so matlabenginefind_matlabreturns two names in a tuple

Connect to the first shared MATLAB session

1 API Reference

1-240

eng = matlabengineconnect_matlab(MATLAB_6830)

bull ldquoConnect Python to Running MATLAB Sessionrdquo

See Alsomatlabengineconnect_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabenginefind_matlab

1-241

matlabengineFutureResult classPackage matlabengine

Results of asynchronous call to MATLAB function stored in Python object

DescriptionThe FutureResult class stores results of an asynchronous call to a MATLAB function ina Python object

ConstructionThe MATLAB Engine for Python creates a FutureResult object when a MATLABfunction is called asynchronously There is no need to callmatlabengineFutureResult() to create FutureResult objects of your own

Methods

cancel Cancel asynchronous call to MATLAB function from Pythoncancelled Cancellation status of asynchronous call to MATLAB function from Pythondone Completion status of asynchronous call to MATLAB function from Pythonresult Result of asynchronous call to MATLAB function from Python

ExceptionsSyntaxError Python exception syntax error in function

callTypeError Python exception data type of output

argument not supported

1 API Reference

1-242

matlabengineCancelledError MATLAB engine cannot cancel functioncall

matlabengineInterruptedError Function call interruptedmatlabengineMatlabExecutionError

Function call fails to execute

matlabengineRejectedExecutionError

Engine terminated

matlabengineTimeoutError Result cannot be returned within thetimeout period

Examples

Get Result of Asynchronous MATLAB Call from Python

Call the MATLAB sqrt function from Python Set async to True to make the functioncall asynchronously

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquo

See AlsomatlabengineMatlabEngine

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from Pythonrdquo

matlabengineFutureResult class

1-243

Introduced in R2014b

1 API Reference

1-244

cancelClass matlabengineFutureResultPackage matlabengine

Cancel asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancel()

Descriptiontf = FutureResultcancel() cancels a call to a MATLAB function calledasynchronously from Python FutureResultcancel returns True if it successfullycancels the function and False if it cannot cancel the function

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status returned as either True or False The status tf is True ifFutureResultcancel successfully cancels the asynchronous function call and isFalse otherwise

Examples

Cancel an Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval function Thencancel it

cancel

1-245

import matlabengineeng = matlabenginestart_matlab()ret = engeval(while 1 endnargout=0async=True)tf = retcancel()print(tf)

True

See Also

1 API Reference

1-246

cancelledClass matlabengineFutureResultPackage matlabengine

Cancellation status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancelled()

Descriptiontf = FutureResultcancelled() returns the cancellation status of a call to aMATLAB function called asynchronously from Python FutureResultcancelledreturns True if a previous call to FutureResultcancel succeeded and Falseotherwise

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status of an asynchronous function call returned as either True or False

Examples

Check Cancellation Status of Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval functionCancel it and check that the engine stopped the loopimport matlabengineeng = matlabenginestart_matlab()

cancelled

1-247

ret = engeval(while 1 endnargout=0async=True)eval_stop = retcancel()tf = retcancelled()print(tf)

True

See Also

1 API Reference

1-248

doneClass matlabengineFutureResultPackage matlabengine

Completion status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultdone()

Descriptiontf = FutureResultdone() returns the completion status of a MATLAB functioncalled asynchronously from Python FutureResultdone returns True if the functionhas finished and False if it has not finished

Output Argumentstf mdash Completion status of asynchronous function callTrue | False

Completion status of an asynchronous function call returned as either True or False

Examples

Check If Asynchronous Call Finished

Call the MATLAB sqrt function with async = True Check the status of ret to learn ifsqrt is finished

import matlabengineeng = matlabenginestart_matlab()

done

1-249

ret = engsqrt(40async=True)tf = retdone()print(tf)

True

When retdone() returns True then you can call retresult() to return the squareroot

See Also

1 API Reference

1-250

resultClass matlabengineFutureResultPackage matlabengine

Result of asynchronous call to MATLAB function from Python

Syntaxret = FutureResultresult(timeout=None)

Descriptionret = FutureResultresult(timeout=None) returns the actual result of a call to aMATLAB function called asynchronously from Python

Input Argumentstimeout mdash Timeout value in secondsNone (default) | Python float

Timeout value in seconds specified as Python data type float to wait for result of thefunction call If timeout = None the FutureResultresult function waits until thefunction call finishes and then returns the result

Output Argumentsret mdash Result of asynchronous function callPython object

Result of an asynchronous function call returned as a Python object that is the actualoutput argument of a call to a MATLAB function

result

1-251

Examples

Get MATLAB Output Argument from Asynchronous Call

Call the MATLAB sqrt function from Python Set async to True and get the squareroot from the FutureResult object

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

See Also

1 API Reference

1-252

matlabengineMatlabEngine classPackage matlabengine

Python object using MATLAB as computational engine within Python session

DescriptionThe MatlabEngine class uses a MATLAB process as a computational engine for PythonYou can call MATLAB functions as methods of a MatlabEngine object because thefunctions are dynamically invoked when you call them You also can call functions andscripts that you define You can send data to and retrieve data from the MATLABworkspace associated with a MatlabEngine object

ConstructionThe matlabenginestart_matlab function creates a MatlabEngine object each timeit is called There is no need to call matlabengineMatlabEngine() to createMatlabEngine objects of your own

MethodsYou can call any MATLAB function as a method of a MatlabEngine object The enginedynamically invokes a MATLAB function when you call it The syntax shows positionalkeyword and output arguments of a function call

ret =MatlabEnginematlabfunc(argsnargout=1async=Falsestdout=sysstsdoutstderr=sysstderr)

Replace matlabfunc with the name of any MATLAB function (such as isprime orsqrt) Replace args with input arguments for the MATLAB function you call Thekeyword arguments specify

matlabengineMatlabEngine class

1-253

bull The number of output arguments the function returnsbull Whether the engine calls the function asynchronouslybull Where the engine sends standard output and standard error coming from the function

Specify keyword arguments only when specifying values that are not the default valuesshown in the syntax

Input Arguments to MATLAB FunctionArgument Description Python Typeargs Input arguments to

MATLAB function specifiedas positional arguments

Any Python types that theengine can convert toMATLAB types

Keyword Arguments to EngineArgument Description Python Typenargout Number of output

arguments from MATLABfunction

intDefault 1

async Flag to call MATLABfunction asynchronously

boolDefault False

stdout Standard output StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstdout

stderr Standard error StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstderr

1 API Reference

1-254

Output ArgumentsOutput Type Description Required Keyword

ArgumentsPython variable One output argument from

MATLAB functionDefault values

tuple Multiple output argumentsfrom MATLAB function

nargout=n (where n gt 1)

None No output argument fromMATLAB function

nargout=0

FutureResult object A placeholder for outputarguments fromasynchronous call toMATLAB function

async=True

ExceptionsMatlabExecutionError Function call fails to executeRejectedExecutionError MATLAB engine terminatedSyntaxError Syntax error in a function callTypeError Data type of an input or output argument

not supported

Attributesworkspace Python dictionary containing references to

MATLAB variables You can assign data toand get data from a MATLAB variablethrough the workspace The name of eachMATLAB variable you create becomes akey in the workspace dictionary The keysin workspace must be valid MATLABidentifiers (for example you cannot usenumbers as keys)

matlabengineMatlabEngine class

1-255

Examples

Call MATLAB Functions from Python

Call the MATLAB sqrt function from Python using the engine

import matlabengineeng = matlabenginestart_matlab()ret = engsqrt(40)print(ret)

20

Put Array Into MATLAB Workspace

Create an array in Python and put it into the MATLAB workspace

import matlabengineeng = matlabenginestart_matlab()px = englinspace(006281000)

px is a MATLAB array but englinspace returned it to Python To use it in MATLABput the array into the MATLAB workspace

engworkspace[mx] = px

When you add an entry to the engine workspace dictionary you create a MATLABvariable as well The engine converts the data to a MATLAB data type

Get Data from MATLAB Workspace

Get pi from the MATLAB workspace and copy it to a Python variable

import matlabengineeng = matlabenginestart_matlab()engeval(a = pinargout=0)mpi = engworkspace[a]print(mpi)

1 API Reference

1-256

314159265359

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquobull ldquoRedirect Standard Output and Error to Pythonrdquo

See AlsomatlabengineFutureResult | matlabenginestart_matlab

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from PythonrdquoldquoRedirect Standard Output and Error to Pythonrdquo

Introduced in R2014b

matlabengineMatlabEngine class

1-257

matlabenginestart_matlabStart MATLAB Engine for Python

Syntaxeng = matlabenginestart_matlab()

eng = matlabenginestart_matlab(option)eng = matlabenginestart_matlab(async)eng = matlabenginestart_matlab(background)eng = matlabenginestart_matlab( ___ )

Descriptioneng = matlabenginestart_matlab() starts a new MATLAB process and returnsPython variable eng which is a MatlabEngine object for communicating with theMATLAB process

If MATLAB cannot be started the engine raises an EngineError exception

eng = matlabenginestart_matlab(option) uses startup options specified byoption

For example call matlabenginestart_matlab(-desktop) to start the MATLABdesktop from Python

eng = matlabenginestart_matlab(async) starts MATLAB asynchronously ifasync is True

eng = matlabenginestart_matlab(background) starts MATLABasynchronously if background is True

eng = matlabenginestart_matlab( ___ ) can include any of the input argumentsin previous syntaxes

1 API Reference

1-258

Examples

Start MATLAB Engine from Python

Start an engine and a new MATLAB process from the Python command line

import matlabengineeng = matlabenginestart_matlab()

Start Multiple Engines

Start a different MATLAB process from each engine

import matlabengineeng1 = matlabenginestart_matlab()eng2 = matlabenginestart_matlab()

Start MATLAB Desktop with Engine

Start an engine with the MATLAB desktop

import matlabengineeng = matlabenginestart_matlab(-desktop)

You also can start the desktop after you start the engineimport matlabengineeng = matlabenginestart_matlab()engdesktop(nargout=0)

Note You can call MATLAB functions from both the desktop and Python

Start Engine Asynchronously

Start the engine with async=True While MATLAB starts you can enter commands atthe Python command line

matlabenginestart_matlab

1-259

import matlabenginefuture = matlabenginestart_matlab(async=True)eng = futureresult()engsqrt(4)

20

bull ldquoStart and Stop MATLAB Engine for Pythonrdquo

Input Argumentsoption mdash Startup options for MATLAB process-nodesktop (default) | string

Startup options for the MATLAB process specified as a string You can specify multiplestartup options with option

The engine supports -desktop to start MATLAB with the desktop In addition theengine supports all MATLAB startup options except for the options listed inldquoLimitationsrdquo on page 1-261Example matlabenginestart_matlab(-desktop -r format short) startsthe desktop from Python The engine passes -r format short to MATLAB

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

background mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargument background is an alias for async and will be removed in a future releaseExample matlabenginestart_matlab(background=True)

1 API Reference

1-260

Output Argumentseng mdash Python variable for communicating with MATLABMatlabEngine object | FutureResult object

Python variable for communicating with MATLAB returned as a MatlabEngine objectif async or background is set to False or a FutureResult object if async orbackground is set to True

Each time you call matlabenginestart_matlab it starts a new MATLAB process

LimitationsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

See AlsomatlabengineMatlabEngine

TopicsldquoStart and Stop MATLAB Engine for PythonrdquoldquoSpecify Startup OptionsrdquoldquoCommonly Used Startup Optionsrdquo

Introduced in R2014b

matlabenginestart_matlab

1-261

matOpen (C and Fortran)Open MAT-file

C Syntaxinclude mathMATFile matOpen(const char filename const char mode)

Fortran Syntaxinclude mathmwPointer matOpen(filename mode)character() filename mode

Argumentsfilename

Name of file to openmode

File opening mode The following table lists valid values for moder Opens file for reading only determines the current version of the MAT-

file by inspecting the files and preserves the current versionu Opens file for update both reading and writing If the file does not exist

does not create a file (equivalent to the r+ mode of fopen) Determinesthe current version of the MAT-file by inspecting the files and preservesthe current version

w Opens file for writing only deletes previous contents if anyw4 Creates a MAT-file compatible with MATLAB Versions 4 software and

earlierw6 Creates a MAT-file compatible with MATLAB Version 5 (R8) software or

earlier Equivalent to wL mode

1 API Reference

1-262

wL Opens file for writing character data using the default character set foryour system Use MATLAB Version 6 or 65 software to read theresulting MAT-file

If you do not use the wL mode switch MATLAB writes character data tothe MAT-file using Unicodereg character encoding by default

Equivalent to w6 modew7 Creates a MAT-file compatible with MATLAB Version 70 (R14) software

or earlier Equivalent to wz modewz Opens file for writing compressed data By default the MATLAB save

function compresses workspace variables as they are saved to a MAT-fileTo use the same compression ratio when creating a MAT-file with thematOpen function use the wz option

Equivalent to w7 modew73 Creates a MAT-file in an HDF5-based format that can store objects that

occupy more than 2 GB

ReturnsFile handle or NULL in C (0 in Fortran) if the open fails

DescriptionThis routine opens a MAT-file for reading and writing

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1F

matOpen (C and Fortran)

1-263

bull matdemo2F

See AlsomatClose save

Introduced before R2006a

1 API Reference

1-264

matPutVariable (C and Fortran)Array to MAT-file

C Syntaxinclude mathint matPutVariable(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariable(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library along with matGetFp to determine status

matPutVariable (C and Fortran)

1-265

DescriptionThis routine puts an mxArray into a MAT-file

matPutVariable writes mxArray pm to the MAT-file mfp If the mxArray does notexist in the MAT-file the function appends it to the end If an mxArray with the samename exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatGetVariable matGetFp

Introduced before R2006a

1 API Reference

1-266

matPutVariableAsGlobal (C and Fortran)Array to MAT-file as originating from global workspace

C Syntaxinclude mathint matPutVariableAsGlobal(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariableAsGlobal(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library with matGetFp to determine status

matPutVariableAsGlobal (C and Fortran)

1-267

DescriptionThis routine puts an mxArray into a MAT-file matPutVariableAsGlobal is likematPutVariable except that MATLAB software loads the array into the globalworkspace and sets a reference to it in the local workspace If you write to a MATLAB 4format file matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable

matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp If the mxArraydoes not exist in the MAT-file the function appends it to the end If an mxArray with thesame name exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable matGetFp

Introduced before R2006a

1 API Reference

1-268

mexAtExit (C and Fortran)Register function to call when MEX function clears or MATLAB terminates

C Syntaxinclude mexhint mexAtExit(void (ExitFcn)(void))

Fortran Syntaxinclude fintrfhinteger4 mexAtExit(ExitFcn)subroutine ExitFcn()

ArgumentsExitFcn

Pointer to function you want to run on exit

ReturnsAlways returns 0

DescriptionUse mexAtExit to register a function to call just before clearing the MEX function orterminating MATLAB mexAtExit gives your MEX function a chance to perform taskssuch as freeing persistent memory and closing files Other typical tasks include closingstreams or sockets

mexAtExit (C and Fortran)

1-269

Each MEX function can register only one active exit function at a time If you callmexAtExit more than once MATLAB uses the ExitFcn from the more recentmexAtExit call as the exit function

If a MEX function is locked you cannot clear the MEX file Therefore if you attempt toclear a locked MEX file MATLAB does not call the ExitFcn

In Fortran declare the ExitFcn as external in the Fortran routine that callsmexAtExit if it is not within the scope of the file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See AlsomexLock mexUnlock

Introduced before R2006a

1 API Reference

1-270

mexCallMATLAB (C and Fortran)Call MATLAB function user-defined function or MEX file

C Syntaxinclude mexhint mexCallMATLAB(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhinteger4 mexCallMATLAB(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

Argumentsnlhs

Number of output arguments Must be less than or equal to 50plhs

Array of pointers to output argumentsnrhs

Number of input arguments Must be less than or equal to 50prhs

Array of pointers to input argumentsfunctionName

Character string containing name of the MATLAB built-in function operator user-defined function or MEX file you are calling

mexCallMATLAB (C and Fortran)

1-271

If functionName is an operator place the operator inside a pair of single quotes forexample +

Returns0 if successful and a nonzero value if unsuccessful

DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions MATLABoperators user-defined functions or other MEX files Both mexCallMATLAB andmexEvalString execute MATLAB commands Use mexCallMATLAB for returningresults (left side arguments) back to the MEX file The mexEvalString function cannotreturn values to the MEX file

For a complete description of the input and output arguments passed to functionNamesee mexFunction

Error HandlingIf functionName detects an error MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt To trap errors use the mexCallMATLABWithTrapfunction

Limitationsbull Avoid using the mexCallMATLAB function in Simulinkreg S-functions If you do do not

store the resulting plhs mxArray pointers in any S-function block state that persistsafter the MEX function finishes Outputs of mexCallMATLAB have temporary scopeand are automatically destroyed at the end of the MEX function call

bull It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLABFor example this function returns two variables but only assigns one of them a value

function [ab] = foo(c)a = 2c

1 API Reference

1-272

If you then call foo using mexCallMATLAB the unassigned output variable is nowtype mxUNKNOWN_CLASS

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexevalstringcbull mexcallmatlabwithtrapc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxisclassc

See AlsomexFunction mexCallMATLABWithTrap mexEvalString mxDestroyArray

Tipsbull MATLAB allocates dynamic memory to store the arrays in plhs for mexCallMATLAB

MATLAB automatically deallocates the dynamic memory when you exit the MEX fileHowever if heap space is at a premium call mxDestroyArray when you are finishedwith the arrays in plhs

Note The plhs argument for mexCallMATLAB is not the same as the plhs formexFunction Do not destroy an mxArray returned in plhs for mexFunction

mexCallMATLAB (C and Fortran)

1-273

Introduced before R2006a

1 API Reference

1-274

mexCallMATLABWithTrap (C and Fortran)Call MATLAB function user-defined function or MEX-file and capture error information

C Syntaxinclude mexhmxArray mexCallMATLABWithTrap(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhmwPointer mexCallMATLABWithTrap(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

ArgumentsFor more information about arguments see mexCallMATLAB

nlhsNumber of desired output arguments

plhsArray of pointers to output arguments

nrhsNumber of input arguments

prhsArray of pointers to input arguments

functionNameCharacter string containing the name of the MATLAB built-in function operatorfunction or MEX-file that you are calling

mexCallMATLABWithTrap (C and Fortran)

1-275

ReturnsNULL if no error occurred otherwise a pointer to an mxArray of class MException

DescriptionThe mexCallMATLABWithTrap function performs the same function as mexCallMATLABHowever if MATLAB detects an error when executing functionName MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexCallMATLABWithTrap For information about MException see ldquoRespond to anExceptionrdquo

See AlsomexCallMATLAB MException

Introduced in R2008b

1 API Reference

1-276

mexErrMsgIdAndTxt (C and Fortran)Display error message with identifier and return to MATLAB prompt

C Syntaxinclude mexhvoid mexErrMsgIdAndTxt(const char errorid const char errormsg )

Fortran Syntaxinclude fintrfhsubroutine mexErrMsgIdAndTxt(errorid errormsg)character() errorid errormsg

Argumentserrorid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

errormsgString to display In C the string can include conversion specifications used by theANSIreg C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexErrMsgIdAndTxt function writes an error message to the MATLAB windowFor more information see the error function syntax statement using a message

mexErrMsgIdAndTxt (C and Fortran)

1-277

identifier After the error message prints MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt

Calling mexErrMsgIdAndTxt does not clear the MEX file from memory SomexErrMsgIdAndTxt does not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgIdAndTxt automatically frees the allocated memory

Note If you get warnings when using mexErrMsgIdAndTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errorid and errormsg the mexErrMsgIdAndTxt functiondetermines where the error occurred and displays the following information Forexample in the function foo mexErrMsgIdAndTxt displays

Error using foo

If you compile your MEX file with the MinGW-w64 compiler see the limitations withexception handling topic in ldquoTroubleshooting and Limitations Compiling CC++ MEXFiles with MinGW-w64rdquo

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrcbull matrixDividecbull timestwoFbull xtimesyF

1 API Reference

1-278

Validate char Input

The following code snippet checks if input argument prhs[0] is a string If not thecode displays a warning If there is an error reading the input string the code displaysan error message and terminates the MEX file

char bufint buflen

if (mxIsChar(prhs[0])) if (mxGetString(prhs[0] buf buflen) == 0) mexPrintf(The input string is sn buf) else mexErrMsgIdAndTxt(MyProgConvertString Could not convert string data) exit MEX file else mexWarnMsgIdAndTxt(MyProgInputString Input should be a string to print properly)

continue with processing

See Alsoerror | mexWarnMsgIdAndTxt

TopicsldquoMemory Considerations for Class DestructorsrdquoldquoTroubleshooting and Limitations Compiling CC++ MEX Files with MinGW-w64rdquo

Introduced before R2006a

mexErrMsgIdAndTxt (C and Fortran)

1-279

mexErrMsgTxt (C and Fortran)Display error message and return to MATLAB prompt

Note mexErrMsgTxt is not recommended Use mexErrMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexErrMsgTxt(const char errormsg)

Fortran Syntaxsubroutine mexErrMsgTxt(errormsg)character() errormsg

Argumentserrormsg

String containing the error message to display

DescriptionmexErrMsgTxt writes an error message to the MATLAB window After the errormessage prints MATLAB terminates the MEX-file and returns control to the MATLABprompt

Calling mexErrMsgTxt does not clear the MEX-file from memory So mexErrMsgTxtdoes not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgTxt automatically frees the allocated memory

1 API Reference

1-280

Note If you get warnings when using mexErrMsgTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errormsg the mexerrmsgtxt function determines where the erroroccurred and displays the following information If an error labeled Print my errormessage occurs in the function foo mexerrmsgtxt displays

Error using fooPrint my error message

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexErrMsgTxt (C and Fortran)

1-281

mexEvalString (C and Fortran)Execute MATLAB command in caller workspace

C Syntaxinclude mexhint mexEvalString(const char command)

Fortran Syntaxinclude fintrfhinteger4 mexEvalString(command)character() command

Argumentscommand

String containing MATLAB command to execute

Returns0 if successful and 1 if an error occurs

DescriptionCall mexEvalString to invoke a MATLAB command in the workspace of the caller

mexEvalString and mexCallMATLAB both execute MATLAB commands UsemexCallMATLAB for returning results (left side arguments) back to the MEX file ThemexEvalString function cannot return values to the MEX file

1 API Reference

1-282

All arguments that appear to the right of an equal sign in the command string must becurrent variables of the caller workspace

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction For more information see ldquoVariable Namesrdquo

Error HandlingIf command detects an error MATLAB returns control to the MEX-file andmexEvalString returns 1 If you want to trap errors use themexEvalStringWithTrap function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexevalstringc

See AlsomexCallMATLAB mexEvalStringWithTrap

Introduced before R2006a

mexEvalString (C and Fortran)

1-283

mexEvalStringWithTrap (C and Fortran)Execute MATLAB command in caller workspace and capture error information

C Syntaxinclude mexhmxArray mexEvalStringWithTrap(const char command)

Fortran Syntaxinclude fintrfhmwPointer mexEvalStringWithTrap(command)character() command

Argumentscommand

String containing the MATLAB command to execute

ReturnsObject ME of class MException

DescriptionThe mexEvalStringWithTrap function performs the same function as mexEvalStringHowever if MATLAB detects an error when executing command MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexEvalStringWithTrap

1 API Reference

1-284

See AlsomexEvalString MException mexCallMATLAB

Introduced before R2006a

mexEvalStringWithTrap (C and Fortran)

1-285

mexFunction (C and Fortran)Entry point to CC++ or Fortran MEX file

C Syntaxinclude mexhvoid mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

Fortran Syntaxinclude fintrfhsubroutine mexFunction(nlhs plhs nrhs prhs)integer nlhs nrhsmwPointer plhs() prhs()

Argumentsnlhs

Number of expected output mxArraysplhs

Array of pointers to the expected output mxArraysnrhs

Number of input mxArraysprhs

Array of pointers to the input mxArrays Do not modify any prhs values in yourMEX file Changing the data in these read-only mxArrays can produce undesiredside effects

1 API Reference

1-286

DescriptionmexFunction is not a routine you call Rather mexFunction is the name of the gatewayfunction in C (subroutine in Fortran) which every MEX file requires When you invoke aMEX function MATLAB software finds and loads the corresponding MEX file of thesame name MATLAB then searches for a symbol named mexFunction within the MEXfile If it finds one it calls the MEX function using the address of the mexFunctionsymbol MATLAB displays an error message if it cannot find a routine namedmexFunction inside the MEX file

When you invoke a MEX file MATLAB automatically seeds nlhs plhs nrhs and prhswith the calling arguments In the syntax of the MATLAB language functions have thegeneral form

[abc] = fun(def)

where the denotes more items of the same format The abc are left-sideoutput arguments and the def are right-side input arguments The argumentsnlhs and nrhs contain the number of left side and right side arguments respectivelyprhs is an array of mxArray pointers whose length is nrhs plhs is an array whoselength is nlhs where your function must set pointers for the output mxArrays

Note It is possible to return an output value even if nlhs = 0 which corresponds toreturning the result in the ans variable

To experiment with passing input arguments build the mexfunctionc examplefollowing the instructions in ldquoTable of MEX File Source Code Filesrdquo

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctioncbull mexlockfF

mexFunction (C and Fortran)

1-287

See Also

TopicsldquoIntroducing MEX Filesrdquo

Introduced before R2006a

1 API Reference

1-288

mexFunctionName (C and Fortran)Name of current MEX function

C Syntaxinclude mexhconst char mexFunctionName(void)

Fortran Syntaxinclude fintrfhcharacter() mexFunctionName()

ReturnsName of the current MEX function

DescriptionmexFunctionName returns the name of the current MEX function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

Introduced before R2006a

mexFunctionName (C and Fortran)

1-289

mexGet (C)Value of specified graphics property

Note Do not use mexGet Use mxGetProperty instead

C Syntaxinclude mexhconst mxArray mexGet(double handle const char property)

Argumentshandle

Handle to a particular graphics objectproperty

Graphics property

ReturnsValue of the specified property in the specified graphics object on success Returns NULLon failure Do not modify the return argument from mexGet Changing the data in aconst (read-only) mxArray can produce undesired side effects

DescriptionCall mexGet to get the value of the property of a certain graphics object mexGet is theAPI equivalent of the MATLAB get function To set a graphics property value callmexSet

1 API Reference

1-290

See AlsomxGetProperty mxSetProperty

mexGet (C)

1-291

mexGetVariable (C and Fortran)Copy of variable from specified workspace

C Syntaxinclude mexhmxArray mexGetVariable(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariable(workspace varname)character() workspace varname

Argumentsworkspace

Specifies where mexGetVariable searches for array varname The possible valuesarebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of the variable to copy

ReturnsCopy of the variable on success Returns NULL in C (0 on Fortran) on failure A commoncause of failure is specifying a variable that is not currently in the workspace Perhapsthe variable was in the workspace at one time but has since been cleared

1 API Reference

1-292

DescriptionCall mexGetVariable to get a copy of the specified variable The returned mxArraycontains a copy of all the data and characteristics that the variable had in the otherworkspace Modifications to the returned mxArray do not affect the variable in theworkspace unless you write the copy back to the workspace with mexPutVariable

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

See AlsomexGetVariablePtr mexPutVariable mxDestroyArray

mexGetVariable (C and Fortran)

1-293

mexGetVariablePtr (C and Fortran)Read-only pointer to variable from another workspace

C Syntaxinclude mexhconst mxArray mexGetVariablePtr(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariablePtr(workspace varname)character() workspace varname

Argumentsworkspace

Specifies which workspace you want mexGetVariablePtr to search The possiblevalues arebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of a variable in another workspace This is a variable name not an mxArraypointer

ReturnsRead-only pointer to the mxArray on success Returns NULL in C (0 in Fortran) onfailure

1 API Reference

1-294

DescriptionCall mexGetVariablePtr to get a read-only pointer to the specified variable varnameinto your MEX-file workspace This command is useful for examining an mxArrays dataand characteristics If you want to change data or characteristics use mexGetVariable(along with mexPutVariable) instead of mexGetVariablePtr

If you simply want to examine data or characteristics mexGetVariablePtr offerssuperior performance because the caller wants to pass only a pointer to the array

See AlsomexGetVariable

Introduced before R2006a

mexGetVariablePtr (C and Fortran)

1-295

mexIsLocked (C and Fortran)Determine if MEX-file is locked

C Syntaxinclude mexhbool mexIsLocked(void)

Fortran Syntaxinclude fintrfhinteger4 mexIsLocked()

ReturnsLogical 1 (true) if the MEX-file is locked logical 0 (false) if the file is unlocked

DescriptionCall mexIsLocked to determine if the MEX-file is locked By default MEX-files areunlocked meaning you can clear the MEX-file at any time

To unlock a MEX-file call mexUnlock

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-296

See AlsomexLock mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexIsLocked (C and Fortran)

1-297

mexLock (C and Fortran)Prevent clearing MEX-file from memory

C Syntaxinclude mexhvoid mexLock(void)

Fortran Syntaxinclude fintrfhsubroutine mexLock()

DescriptionBy default MEX files are unlocked meaning you can clear them at any time CallmexLock to prohibit clearing a MEX file

To unlock a MEX file call mexUnlock Do not use the munlock function

mexLock increments a lock count If you call mexLock n times call mexUnlock n timesto unlock your MEX file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-298

See AlsomexIsLocked mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexLock (C and Fortran)

1-299

mexMakeArrayPersistent (C and Fortran)Make array persist after MEX file completes

C Syntaxinclude mexhvoid mexMakeArrayPersistent(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mexMakeArrayPersistent(pm)mwPointer pm

Argumentspm

Pointer to an mxArray created by an mxCreate function

DescriptionBy default an mxArray allocated by an mxCreate function is not persistent TheMATLAB memory management facility automatically frees a nonpersistent mxArraywhen the MEX function finishes If you want the mxArray to persist through multipleinvocations of the MEX function call the mexMakeArrayPersistent function

Do not assign an array created with the mexMakeArrayPersistent function to theplhs output argument of a MEX file

Note If you create a persistent mxArray you are responsible for destroying it usingmxDestroyArray when the MEX file is cleared If you do not destroy a persistentmxArray MATLAB leaks memory See mexAtExit to see how to register a function that

1 API Reference

1-300

gets called when the MEX file is cleared See mexLock to see how to lock your MEX fileso that it is never cleared

See AlsomexAtExit mxDestroyArray mexLock mexMakeMemoryPersistent and themxCreate functions

Introduced before R2006a

mexMakeArrayPersistent (C and Fortran)

1-301

mexMakeMemoryPersistent (C and Fortran)Make memory allocated by MATLAB software persist after MEX-function completes

C Syntaxinclude mexhvoid mexMakeMemoryPersistent(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mexMakeMemoryPersistent(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of memory allocated by one of the MATLAB memoryallocation routines

DescriptionBy default memory allocated by MATLAB is nonpersistent so it is freed automaticallywhen the MEX function finishes If you want the memory to persist callmexMakeMemoryPersistent

Note If you create persistent memory you are responsible for freeing it when the MEXfunction is cleared If you do not free the memory MATLAB leaks memory To freememory use mxFree See mexAtExit to see how to register a function that gets calledwhen the MEX function is cleared See mexLock to see how to lock your MEX function sothat it is never cleared

1 API Reference

1-302

See AlsomexAtExit mexLock mexMakeArrayPersistent mxCalloc mxFree mxMallocmxRealloc

Introduced before R2006a

mexMakeMemoryPersistent (C and Fortran)

1-303

mexPrintf (C and Fortran)ANSI C PRINTF-style output routine

C Syntaxinclude mexhint mexPrintf(const char message )

Fortran Syntaxinclude fintrfhinteger4 mexPrintf(message)character() message

Argumentsmessage

String to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

ReturnsNumber of characters printed including characters specified with backslash codes suchas n and b

1 API Reference

1-304

DescriptionThis routine prints a string on the screen and in the diary (if the diary is in use) Itprovides a callback to the standard C printf routine already linked inside MATLABsoftware which avoids linking the entire stdio library into your MEX file

In a C MEX file call mexPrintf instead of printf to display a string

Note If you want the literal in your message use in the message string since hasspecial meaning to printf Failing to do so causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See Alsosprintf mexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexPrintf (C and Fortran)

1-305

mexPutVariable (C and Fortran)Array from MEX-function into specified workspace

C Syntaxinclude mexhint mexPutVariable(const char workspace const char varname const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mexPutVariable(workspace varname pm)character() workspace varnamemwPointer pm

Argumentsworkspace

Specifies scope of the array you are copying Values for workspace arebase Copy mxArray to the base workspacecaller Copy mxArray to the caller workspaceglobal Copy mxArray to the list of global variables

varnameName of mxArray in the workspace

pmPointer to the mxArray

1 API Reference

1-306

Returns0 on success 1 on failure A possible cause of failure is that pm is NULL in C (0 inFortran)

DescriptionCall mexPutVariable to copy the mxArray at pointer pm from your MEX-function intothe specified workspace MATLAB software gives the name varname to the copiedmxArray in the receiving workspace

mexPutVariable makes the array accessible to other entities such as MATLAB user-defined functions or other MEX-functions

If a variable of the same name exists in the specified workspace mexPutVariableoverwrites the previous contents of the variable with the contents of the new mxArrayFor example suppose the MATLAB workspace defines variable Peaches as

Peaches1 2 3 4

and you call mexPutVariable to copy Peaches into the same workspace

mexPutVariable(base Peaches pm)

The value passed by mexPutVariable replaces the old value of Peaches

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

mexPutVariable (C and Fortran)

1-307

See AlsomexGetVariable

1 API Reference

1-308

mexSet (C)Set value of specified graphics property

Note Do not use mexSet Use mxSetProperty instead

C Syntaxinclude mexhint mexSet(double handle const char property mxArray value)

Argumentshandle

Handle to a particular graphics objectproperty

String naming a graphics propertyvalue

Pointer to an mxArray holding the new value to assign to the property

Returns0 on success 1 on failure Possible causes of failure include

bull Specifying a nonexistent propertybull Specifying an illegal value for that property for example specifying a string value for

a numerical property

mexSet (C)

1-309

DescriptionCall mexSet to set the value of the property of a certain graphics object mexSet is theAPI equivalent of the MATLAB set function To get the value of a graphics property callmexGet

See AlsomxGetProperty mxSetProperty

1 API Reference

1-310

mexSetTrapFlag (C and Fortran)Control response of MEXCALLMATLAB to errors

C Syntaxinclude mexhvoid mexSetTrapFlag(int trapflag)

Note mexSetTrapFlag will be removed in a future version UsemexCallMATLABWithTrap instead

Fortran Syntaxsubroutine mexSetTrapFlag(trapflag)integer4 trapflag

Argumentstrapflag

Control flag Possible values are0 On error control returns to the MATLAB prompt1 On error control returns to your MEX-file

DescriptionCall mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB

If you do not call mexSetTrapFlag then whenever MATLAB detects an error in a call tomexCallMATLAB MATLAB automatically terminates the MEX-file and returns controlto the MATLAB prompt Calling mexSetTrapFlag with trapflag set to 0 is equivalentto not calling mexSetTrapFlag at all

mexSetTrapFlag (C and Fortran)

1-311

If you call mexSetTrapFlag and set the trapflag to 1 then whenever MATLABdetects an error in a call to mexCallMATLAB MATLAB does not automatically terminatethe MEX-file Rather MATLAB returns control to the line in the MEX-file immediatelyfollowing the call to mexCallMATLAB The MEX-file is then responsible for taking anappropriate response to the error

If you call mexSetTrapFlag the value of the trapflag you set remains in effect untilthe next call to mexSetTrapFlag within that MEX-file or if there are no more calls tomexSetTrapFlag until the MEX-file exits If a routine defined in a MEX-file callsanother MEX-file MATLAB

1 Saves the current value of the trapflag in the first MEX-file2 Calls the second MEX-file with the trapflag initialized to 0 within that file3 Restores the saved value of trapflag in the first MEX-file when the second MEX-

file exits

See AlsomexCallMATLAB mexCallMATLABWithTrap mexAtExit mexErrMsgTxt

Introduced in R2008b

1 API Reference

1-312

mexUnlock (C and Fortran)Allow clearing MEX-file from memory

C Syntaxinclude mexhvoid mexUnlock(void)

Fortran Syntaxinclude fintrfhsubroutine mexUnlock()

DescriptionBy default MEX-files are unlocked meaning you can clear them at any time CallingmexLock locks a MEX-file so that you cannot clear it from memory Call mexUnlock toremove the lock

mexLock increments a lock count If you called mexLock n times call mexUnlock ntimes to unlock your MEX-file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

mexUnlock (C and Fortran)

1-313

See AlsomexIsLocked mexLock mexMakeArrayPersistent mexMakeMemoryPersistentclear

1 API Reference

1-314

mexWarnMsgIdAndTxt (C and Fortran)Warning message with identifier

C Syntaxinclude mexhvoid mexWarnMsgIdAndTxt(const char warningid const char warningmsg )

Fortran Syntaxinclude fintrfhsubroutine mexWarnMsgIdAndTxt(warningid warningmsg)character() warningid warningmsg

Argumentswarningid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

warningmsgString to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexWarnMsgIdAndTxt function writes a warning message to the MATLABcommand prompt The warnings displayed are the same as warnings issued by the

mexWarnMsgIdAndTxt (C and Fortran)

1-315

MATLAB warning function To control the information displayed or suppressed call thewarning function with the desired settings before calling your MEX-file

Unlike mexErrMsgIdAndTxt calling mexWarnMsgIdAndTxt does not terminate theMEX-file

See AlsomexErrMsgIdAndTxt warning

Introduced before R2006a

1 API Reference

1-316

mexWarnMsgTxt (C and Fortran)Warning message

Note mexWarnMsgTxt is not recommended Use mexWarnMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexWarnMsgTxt(const char warningmsg)

Fortran Syntaxsubroutine mexWarnMsgTxt(warningmsg)character() warningmsg

Argumentswarningmsg

String containing the warning message to display

DescriptionmexWarnMsgTxt causes MATLAB software to display the contents of warningmsgmexWarnMsgTxt does not terminate the MEX-file

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexWarnMsgTxt (C and Fortran)

1-317

mwIndex (C and Fortran)Type for index values

DescriptionmwIndex is a type that represents index values such as indices into arrays Use thisfunction for cross-platform flexibility By default mwIndex is equivalent to int in CWhen using the mex -largeArrayDims switch mwIndex is equivalent to size_t in CIn Fortran mwIndex is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwIndex is a preprocessor macro The Fortran header file containing thistype is

include fintrfh

See Alsomex mwSize mwSignedIndex

Introduced before R2006a

1 API Reference

1-318

mwPointer (Fortran)Platform-independent pointer type

DescriptionmwPointer is a preprocessor macro that declares the appropriate Fortran typerepresenting a pointer to an mxArray or to other data that is not of a native Fortrantype such as memory allocated by mxMalloc On 32-bit platforms the Fortran type thatrepresents a pointer is INTEGER4 on 64-bit platforms it is INTEGER8 The Fortranpreprocessor translates mwPointer to the Fortran declaration that is appropriate for theplatform on which you compile your file

If your Fortran compiler supports preprocessing you can use mwPointer to declarefunctions arguments and variables that represent pointers If you cannot usemwPointer ensure that your declarations have the correct size for the platform on whichyou are compiling Fortran code

The Fortran header file containing this type is

include fintrfh

ExamplesThis example declares the arguments for mexFunction in a Fortran MEX file

subroutine mexFunction(nlhs plhs nrhs prhs)mwPointer plhs() prhs()integer nlhs nrhs

For additional examples see the Fortran files with names ending in F in thematlabrootexternexamples folder

Introduced in R2006a

mwPointer (Fortran)

1-319

mwSignedIndex (C and Fortran)Signed integer type for size values

DescriptionmwSignedIndex is a signed integer type that represents size values such as arraydimensions Use this function for cross-platform flexibility By default mwSignedIndexis equivalent to ptrdiff_t in C++ In Fortran mwSignedIndex is similarly equivalentto INTEGER4 or INTEGER8 based on platform and compilation flags

The C header file containing this type is

include matrixh

The Fortran header file containing this type is

include fintrfh

See AlsomwSize mwIndex

Introduced in R2009a

1 API Reference

1-320

mwSize (C and Fortran)Type for size values

DescriptionmwSize is a type that represents size values such as array dimensions Use this functionfor cross-platform flexibility By default mwSize is equivalent to size_t in C mwSize isan unsigned type meaning a nonnegative integer

When using the mex -compatibleArrayDims switch mwSize is equivalent to int in CIn Fortran mwSize is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwSize is a preprocessor macro The Fortran header file containing this typeis

include fintrfh

See Alsomex mwIndex mwSignedIndex

Introduced before R2006a

mwSize (C and Fortran)

1-321

mxAddField (C and Fortran)Add field to structure array

C Syntaxinclude matrixhextern int mxAddField(mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxAddField(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of the field you want to add

ReturnsField number on success or -1 if inputs are invalid or an out-of-memory conditionoccurs

1 API Reference

1-322

DescriptionCall mxAddField to add a field to a structure array Create the values with themxCreate functions and use mxSetFieldByNumber to set the individual values for thefield

See AlsomxRemoveField mxSetFieldByNumber

Introduced before R2006a

mxAddField (C and Fortran)

1-323

mxArray (C)Type for MATLAB array

DescriptionThe fundamental type underlying MATLAB data For information on how the MATLABarray works with MATLAB-supported variables see ldquoMATLAB Datardquo

mxArray is a C language opaque type

All C MEX-files start with a gateway routine called mexFunction which requiresmxArray for both input and output parameters For information about the C MEX-filegateway routine see ldquoComponents of MEX Filerdquo

Once you have MATLAB data in your MEX-file use functions in the Matrix Library tomanipulate the data and functions in the MEX Library to perform operations in theMATLAB environment You use mxArray to pass data to and from these functions

Use any of the mxCreate functions to create data and the correspondingmxDestroyArray function to free memory

The header file containing this type is

include matrixh

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomexFunction mxClassID mxCreateDoubleMatrix mxCreateNumericArraymxCreateString mxDestroyArray mxGetData mxSetData

1 API Reference

1-324

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquobull For troubleshooting mxArray errors in other MathWorks products search the

documentation for that product or see MATLAB Answerstrade topic Subscripting intoan mxArray is not supported

Introduced before R2006a

mxArray (C)

1-325

mxArrayToString (C)Array to string

C Syntaxinclude matrixhchar mxArrayToString(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string Returns NULL on failure Possible reasons for failure include out ofmemory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToString to copy the character data of an mxCHAR array into a C-stylestring The C-style string is always terminated with a NULL character and stored incolumn-major order

If the array contains multiple rows the rows are copied column-wise into a single array

This function is similar to mxGetString except that

bull It does not require the length of the string as an inputbull It supports both multi-byte and single-byte encoded characters On Windows and

Linuxreg platforms the default encoding is specified by the user locale setting

1 API Reference

1-326

mxArrayToString does not free the dynamic memory that the char pointer points toTherefore you typically free the C-style string (using mxFree) immediately after youhave finished using it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxArrayToUTF8String mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetString

Introduced before R2006a

mxArrayToString (C)

1-327

mxArrayToUTF8String (C)Array to string in UTF-8 encoding

C Syntaxinclude matrixhchar mxArrayToUTF8String(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string in UTF-8 encoding Returns NULL on failure Possible reasons for failureinclude out of memory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToUTF8String to copy the character data of an mxCHAR array into a C-style string The data is stored in column-major order If the array contains multiplerows the rows are copied column-wise into a single array

mxArrayToUTF8String does not free the dynamic memory that the char pointer pointsto Use mxFree to free memory

See AlsomxArrayToString mxFree mxCreateCharArray mxCreateString mxGetString

1 API Reference

1-328

Introduced in R2015a

mxArrayToUTF8String (C)

1-329

mxAssert (C)Check assertion value for debugging purposes

C Syntaxinclude matrixhvoid mxAssert(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionLike the ANSI C assert macro mxAssert checks the value of an assertion andcontinues execution only if the assertion holds If expr evaluates to logical 1 (true)mxAssert does nothing If expr evaluates to logical 0 (false) mxAssert terminates theMEX file and prints an error to the MATLAB command window The error contains theexpression of the failed assertion the file name and line number where the failedassertion occurred and the error_message text The error_message allows you tospecify a better description of why the assertion failed Use an empty string if you do notwant a description to follow the failed assertion message

The mex script turns off these assertions when building optimized MEX functions so useassertions for debugging purposes only To use mxAssert build the MEX file using themex -g filename syntax

Assertions are a way of maintaining internal consistency of logic Use them to keepyourself from misusing your own code and to prevent logical errors from propagating

1 API Reference

1-330

before they are caught Do not use assertions to prevent users of your code from misusingit

Assertions can be taken out of your code by the C preprocessor You can use these checksduring development and then remove them when the code works properly letting youuse them for troubleshooting during development without slowing down the finalproduct

See AlsomxAssertS mexErrMsgIdAndTxt

Introduced before R2006a

mxAssert (C)

1-331

mxAssertS (C)Check assertion value without printing assertion text

C Syntaxinclude matrixhvoid mxAssertS(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionmxAssertS is like mxAssert except mxAssertS does not print the text of the failedassertion

See AlsomxAssert

Introduced before R2006a

1 API Reference

1-332

mxCalcSingleSubscript (C and Fortran)Offset from first element to desired element

C Syntaxinclude matrixhmwIndex mxCalcSingleSubscript(const mxArray pm mwSize nsubs mwIndex subs)

Fortran Syntaxinclude fintrfhmwIndex mxCalcSingleSubscript(pm nsubs subs)mwPointer pmmwSize nsubsmwIndex subs

Argumentspm

Pointer to an mxArraynsubs

Number of elements in the subs array Typically you set nsubs equal to the numberof dimensions in the mxArray that pm points to

subsAn array of integers Each value in the array specifies that dimensions subscript InC syntax the value in subs[0] specifies the row subscript and the value insubs[1] specifies the column subscript Use zero-based indexing for subscripts Forexample to express the starting element of a two-dimensional mxArray in subs setsubs[0] to 0 and subs[1] to 0

In Fortran syntax the value in subs(1) specifies the row subscript and the value insubs(2) specifies the column subscript Use 1-based indexing for subscripts For

mxCalcSingleSubscript (C and Fortran)

1-333

example to express the starting element of a two-dimensional mxArray in subs setsubs(1) to 1 and subs(2) to 1

ReturnsThe number of elements or index between the start of the mxArray and the specifiedsubscript This number is the linear index equivalent of the subscripts Many MatrixLibrary routines (for example mxGetField) require an index as an argument

If subs describes the starting element of an mxArray mxCalcSingleSubscriptreturns 0 If subs describes the final element of an mxArray mxCalcSingleSubscriptreturns N-1 (where N is the total number of elements)

DescriptionCall mxCalcSingleSubscript to determine how many elements there are between thebeginning of the mxArray and a given element of that mxArray The function convertssubscripts to linear indices

For example given a subscript like (57) mxCalcSingleSubscript returns thedistance from the first element of the array to the (57) element Remember that themxArray data type internally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have For examplesshowing the internal representation see ldquoData Storagerdquo

Avoid using mxCalcSingleSubscript to traverse the elements of an array In C it ismore efficient to find the starting address of the array and then use pointerautoincrementing to access successive elements For example to find the startingaddress of a numerical array call mxGetPr or mxGetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

1 API Reference

1-334

See AlsomxGetCell mxSetCell

Introduced before R2006a

mxCalcSingleSubscript (C and Fortran)

1-335

mxCalloc (C and Fortran)Allocate dynamic memory for array initialized to 0 using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxCalloc(mwSize n mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxCalloc(n size)mwSize n size

Argumentsn

Number of elements to allocate This must be a nonnegative numbersize

Number of bytes per element (The C sizeof operator calculates the number of bytesper element)

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxCalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxCalloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-336

DescriptionmxCalloc allocates contiguous heap space sufficient to hold n elements of size byteseach and initializes this newly allocated memory to 0 Use mxCalloc instead of theANSI C calloc function to allocate memory in MATLAB applications

In MEX files but not MAT or engine applications mxCalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatacbull phonebookcbull revordc

mxCalloc (C and Fortran)

1-337

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxsetdimensionsc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistentmxDestroyArray mxFree mxMalloc mxRealloc

Introduced before R2006a

1 API Reference

1-338

mxChar (C)Type for string array

DescriptionMATLAB stores an mxArray string as type mxChar to represent the C-style char typeMATLAB uses 16-bit unsigned integer character encoding for Unicode characters

The header file containing this type is

include matrixh

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxcreatecharmatrixfromstrc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCharArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

mxChar (C)

1-339

Introduced before R2006a

1 API Reference

1-340

mxClassID (C)Enumerated value identifying class of array

C Syntaxtypedef enum mxUNKNOWN_CLASS mxCELL_CLASS mxSTRUCT_CLASS mxLOGICAL_CLASS mxCHAR_CLASS mxVOID_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_CLASS

Undetermined class You cannot specify this category for an mxArray however ifmxGetClassID cannot identify the class it returns this value

mxCELL_CLASSIdentifies a cell mxArray

mxSTRUCT_CLASSIdentifies a structure mxArray

mxClassID (C)

1-341

mxLOGICAL_CLASSIdentifies a logical mxArray an mxArray of mxLogical data

mxCHAR_CLASSIdentifies a string mxArray an mxArray whose data is represented as mxChar

mxVOID_CLASSReserved

mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

1 API Reference

1-342

mxINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxFUNCTION_CLASSIdentifies a function handle mxArray

DescriptionVarious Matrix Library functions require or return an mxClassID argumentmxClassID identifies how the mxArray represents its data elements

The following table shows MATLAB types with their equivalent C types Use the typefrom the right-most column for reading mxArrays with the mxClassID value shown inthe left columnMATLAB Primitive Types

mxClassID Value MATLAB Type MEX Type C Primitive TypemxINT8_CLASS int8 int8_T char bytemxUINT8_CLASS uint8 uint8_T unsigned char bytemxINT16_CLASS int16 int16_T shortmxUINT16_CLASS uint16 uint16_T unsigned shortmxINT32_CLASS int32 int32_T intmxUINT32_CLASS uint32 uint32_T unsigned intmxINT64_CLASS int64 int64_T long longmxUINT64_CLASS uint64 uint64_T unsigned long longmxSINGLE_CLASS single float floatmxDOUBLE_CLASS double double double

mxClassID (C)

1-343

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetClassID mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-344

mxClassIDFromClassName (Fortran)Identifier corresponding to class

Fortran Syntaxinclude fintrfhinteger4 mxClassIDFromClassName(classname)character() classname

Argumentsclassname

character array specifying a MATLAB class name For a list of valid classnamechoices see the mxIsClass reference page

ReturnsNumeric identifier used internally by MATLAB software to represent the MATLAB classclassname Returns unknown if classname is not a recognized MATLAB class

DescriptionUse mxClassIDFromClassName to obtain an identifier for any MATLAB class Thisfunction is most commonly used to provide a classid argument tomxCreateNumericArray and mxCreateNumericMatrix

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matsqint8F

mxClassIDFromClassName (Fortran)

1-345

See AlsomxGetClassName mxCreateNumericArray mxCreateNumericMatrix mxIsClass

Introduced before R2006a

1 API Reference

1-346

mxComplexity (C)Flag specifying whether array has imaginary components

C Syntaxtypedef enum mxComplexity mxREAL=0 mxCOMPLEX

ConstantsmxREAL

Identifies an mxArray with no imaginary componentsmxCOMPLEX

Identifies an mxArray with imaginary components

DescriptionVarious Matrix Library functions require an mxComplexity argument You can set anmxComplex argument to either mxREAL or mxCOMPLEX

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

See AlsomxCreateNumericArray mxCreateDoubleMatrix mxCreateSparse

mxComplexity (C)

1-347

Introduced before R2006a

1 API Reference

1-348

mxCopyCharacterToPtr (Fortran)CHARACTER values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyCharacterToPtr(y px n)character() ymwPointer pxmwSize n

Argumentsy

character Fortran arraypx

Pointer to character or name arrayn

Number of elements to copy

DescriptionmxCopyCharacterToPtr copies n character values from the Fortran characterarray y into the MATLAB character vector pointed to by px This subroutine is essentialfor copying character data between MATLAB pointer arrays and ordinary Fortrancharacter arrays

See AlsomxCopyPtrToCharacter mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

mxCopyCharacterToPtr (Fortran)

1-349

Introduced before R2006a

1 API Reference

1-350

mxCopyComplex16ToPtr (Fortran)COMPLEX16 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex16ToPtr(y pr pi n)complex16 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX16 Fortran arraypr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex16ToPtr copies n COMPLEX16 values from the Fortran COMPLEX16array y into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex16ToPtr (Fortran)

1-351

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyPtrToComplex16 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-352

mxCopyComplex8ToPtr (Fortran)COMPLEX8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex8ToPtr(y pr pi n)complex8 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX8 Fortran arraypr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex8ToPtr copies n COMPLEX8 values from the Fortran COMPLEX8 arrayy into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex8ToPtr (Fortran)

1-353

See AlsomxCopyPtrToComplex8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-354

mxCopyInteger1ToPtr (Fortran)INTEGER1 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger1ToPtr(y px n)integer1 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER1 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger1ToPtr copies n INTEGER1 values from the Fortran INTEGER1 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyInteger1ToPtr (Fortran)

1-355

bull matsqint8F

See AlsomxCopyPtrToInteger1 mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-356

mxCopyInteger2ToPtr (Fortran)INTEGER2 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger2ToPtr(y px n)integer2 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER2 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger2ToPtr copies n INTEGER2 values from the Fortran INTEGER2 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger2 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger2ToPtr (Fortran)

1-357

Introduced before R2006a

1 API Reference

1-358

mxCopyInteger4ToPtr (Fortran)INTEGER4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger4ToPtr(y px n)integer4 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER4 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger4ToPtr copies n INTEGER4 values from the Fortran INTEGER4 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger4 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger4ToPtr (Fortran)

1-359

Introduced before R2006a

1 API Reference

1-360

mxCopyPtrToCharacter (Fortran)CHARACTER values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToCharacter(px y n)mwPointer pxcharacter() ymwSize n

Argumentspx

Pointer to character or name arrayy

character Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToCharacter copies n character values from the MATLAB array pointedto by px into the Fortran character array y This subroutine is essential for copyingcharacter data from MATLAB pointer arrays into ordinary Fortran character arrays

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxCopyPtrToCharacter (Fortran)

1-361

See AlsomxCopyCharacterToPtr mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

Introduced before R2006a

1 API Reference

1-362

mxCopyPtrToComplex16 (Fortran)COMPLEX16 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex16(pr pi y n)mwPointer pr picomplex16 y(n)mwSize n

Argumentspr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayy

COMPLEX16 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex16 copies n COMPLEX16 values from the MATLAB arrayspointed to by pr and pi into the Fortran COMPLEX16 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex16 (Fortran)

1-363

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyComplex16ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-364

mxCopyPtrToComplex8 (Fortran)COMPLEX8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex8(pr pi y n)mwPointer pr picomplex8 y(n)mwSize n

Argumentspr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayy

COMPLEX8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex8 copies n COMPLEX8 values from the MATLAB arrays pointedto by pr and pi into the Fortran COMPLEX8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex8 (Fortran)

1-365

See AlsomxCopyComplex8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-366

mxCopyPtrToInteger1 (Fortran)INTEGER1 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger1(px y n)mwPointer pxinteger1 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER1 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger1 copies n INTEGER1 values from the MATLAB array pointed toby px either a real or imaginary array into the Fortran INTEGER1 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyPtrToInteger1 (Fortran)

1-367

bull matsqint8F

See AlsomxCopyInteger1ToPtr mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-368

mxCopyPtrToInteger2 (Fortran)INTEGER2 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger2(px y n)mwPointer pxinteger2 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER2 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger2 copies n INTEGER2 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER2 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger2ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger2 (Fortran)

1-369

Introduced before R2006a

1 API Reference

1-370

mxCopyPtrToInteger4 (Fortran)INTEGER4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger4(px y n)mwPointer pxinteger4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger4 copies n INTEGER4 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger4ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger4 (Fortran)

1-371

Introduced before R2006a

1 API Reference

1-372

mxCopyPtrToPtrArray (Fortran)Pointer values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToPtrArray(px y n)mwPointer pxmwPointer y(n)mwSize n

Argumentspx

Pointer to pointer arrayy

Fortran array of mwPointer valuesn

Number of pointers to copy

DescriptionmxCopyPtrToPtrArray copies n pointers from the MATLAB array pointed to by px intothe Fortran array y This subroutine is essential for copying the output of matGetDirinto an array of pointers After calling this function each element of y contains a pointerto a string You can convert these strings to Fortran character arrays by passing eachelement of y as the first argument to mxCopyPtrToCharacter

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToPtrArray (Fortran)

1-373

bull matdemo2F

See AlsomatGetDir mxCopyPtrToCharacter

Introduced before R2006a

1 API Reference

1-374

mxCopyPtrToReal4 (Fortran)REAL4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal4(px y n)mwPointer pxreal4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a single-precision MATLAB arrayy

REAL4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal4 copies n REAL4 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToReal4 (Fortran)

1-375

See AlsomxCopyReal4ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-376

mxCopyPtrToReal8 (Fortran)REAL8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal8(px y n)mwPointer pxreal8 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a double-precision MATLAB arrayy

REAL8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal8 copies n REAL8 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToReal8 (Fortran)

1-377

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyReal8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-378

mxCopyReal4ToPtr (Fortran)REAL4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal4ToPtr(y px n)real4 y(n)mwPointer pxmwSize n

Argumentsy

REAL4 Fortran arraypx

Pointer to the real or imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal4ToPtr copies n REAL4 values from the Fortran REAL4 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyReal4ToPtr (Fortran)

1-379

See AlsomxCopyPtrToReal4 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-380

mxCopyReal8ToPtr (Fortran)REAL8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal8ToPtr(y px n)real8 y(n)mwPointer pxmwSize n

Argumentsy

REAL8 Fortran arraypx

Pointer to the real or imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal8ToPtr copies n REAL8 values from the Fortran REAL8 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyReal8ToPtr (Fortran)

1-381

bull matdemo1F

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyPtrToReal8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-382

mxCreateCellArray (C and Fortran)N-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the created cell For example to create a three-dimensionalcell mxArray set ndim to 3

dimsDimensions array Each element in the dimensions array contains the size of themxArray in that dimension For example in C setting dims[0] to 5 and dims[1] to7 establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellArray (C and Fortran)

1-383

DescriptionUse mxCreateCellArray to create a cell mxArray with size defined by ndim and dimsFor example in C to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims[0] = 4 dims[1] = 8 dims[2] = 7

In Fortran to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims(1) = 4 dims(2) = 8 dims(3) = 7

The created cell mxArray is unpopulated mxCreateCellArray initializes each cell toNULL To put data into a cell call mxSetCell

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateCellMatrix mxGetCell mxSetCell mxIsCell

Introduced before R2006a

1 API Reference

1-384

mxCreateCellMatrix (C and Fortran)2-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellMatrix(mwSize m mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellMatrix(m n)mwSize m n

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellMatrix (C and Fortran)

1-385

DescriptionUse mxCreateCellMatrix to create an m-by-n two-dimensional cell mxArray Thecreated cell mxArray is unpopulated mxCreateCellMatrix initializes each cell to NULLin C (0 in Fortran) To put data into cells call mxSetCell

mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only butmxCreateCellArray can create mxArrays having any number of dimensions greaterthan 1

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray

Introduced before R2006a

1 API Reference

1-386

mxCreateCharArray (C and Fortran)N-D mxChar array

C Syntaxinclude matrixhmxArray mxCreateCharArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the mxArray specified as a positive number If you specify0 1 or 2 mxCreateCharArray creates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray The dims array must have at least ndimelements

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateCharArray (C and Fortran)

1-387

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateCharArray to create an N-dimensional mxChar array The createdmxArray is unpopulated that is mxCreateCharArray initializes each cell to NULL in C(0 in Fortran)

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateCharMatrixFromStrings mxCreateString

1 API Reference

1-388

mxCreateCharMatrixFromStrings (C and Fortran)2-D mxChar array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateCharMatrixFromStrings(mwSize m const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharMatrixFromStrings(m str)mwSize mcharacter() str(m)

Argumentsm

Number of rows in the mxArray The value you specify for m is the number of stringsin str

strIn C an array of strings containing at least m strings In Fortran a characternarray of size m where each element of the array is n bytes

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray Another possible reasonfor failure is that str contains fewer than m strings

mxCreateCharMatrixFromStrings (C and Fortran)

1-389

DescriptionUse mxCreateCharMatrixFromStrings to create a two-dimensional mxArray whereeach row is initialized to a string from str In C the created mxArray has dimensions m-by-max where max is the length of the longest string in str In Fortran the createdmxArray has dimensions m-by-n where n is the number of characters in str(i)

The mxArray represents its data elements as mxChar rather than as C char

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxCreateCharArray mxCreateString mxGetString

Introduced before R2006a

1 API Reference

1-390

mxCreateDoubleMatrix (C and Fortran)2-D double-precision floating-point array

C Syntaxinclude matrixhmxArray mxCreateDoubleMatrix(mwSize m mwSize n mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleMatrix(m n ComplexFlag)mwSize m ninteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsComplexFlag

If the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateDoubleMatrix (C and Fortran)

1-391

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateDoubleMatrix to create an m-by-n mxArray mxCreateDoubleMatrixinitializes each element in the pr array to 0 If you set ComplexFlag to mxCOMPLEX in C(1 in Fortran) mxCreateDoubleMatrix also initializes each element in the pi array to0

If you set ComplexFlag to mxREAL in C (0 in Fortran) mxCreateDoubleMatrixallocates enough memory to hold m-by-n real elements If you set ComplexFlag tomxCOMPLEX in C (1 in Fortran) mxCreateDoubleMatrix allocates enough memory tohold m-by-n real elements and m-by-n imaginary elements

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its associated real and complex elements

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull matrixDividecbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull matsqF

1 API Reference

1-392

bull timestwoFbull xtimesyF

See AlsomxCreateNumericArray

Introduced before R2006a

mxCreateDoubleMatrix (C and Fortran)

1-393

mxCreateDoubleScalar (C and Fortran)Scalar double-precision array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateDoubleScalar(double value)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleScalar(value)real8 value

Argumentsvalue

Value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateDoubleScalar to create a scalar double mxArray When you finish usingthe mxArray call mxDestroyArray to destroy it

1 API Reference

1-394

See AlsomxGetPr mxCreateDoubleMatrix

Alternatives

C Language

In C you can replace the statements

pa = mxCreateDoubleMatrix(1 1 mxREAL)mxGetPr(pa) = value

with a call to mxCreateDoubleScalar

pa = mxCreateDoubleScalar(value)

Fortran Language

In Fortran you can replace the statements

pm = mxCreateDoubleMatrix(1 1 0)mxCopyReal8ToPtr(value mxGetPr(pm) 1)

with a call to mxCreateDoubleScalar

pm = mxCreateDoubleScalar(value)

Introduced before R2006a

mxCreateDoubleScalar (C and Fortran)

1-395

mxCreateLogicalArray (C)N-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalArray(mwSize ndim const mwSize dims)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateLogicalArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray There are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalArray to create an N-dimensional mxArray of mxLogicalelements After creating the mxArray mxCreateLogicalArray initializes all itselements to logical 0 mxCreateLogicalArray differs from mxCreateLogicalMatrixin that the latter can create two-dimensional arrays only

1 API Reference

1-396

mxCreateLogicalArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateLogicalMatrix mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalArray (C)

1-397

mxCreateLogicalMatrix (C)2-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalMatrix(mwSize m mwSize n)

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateLogicalMatrix to create an m-by-n mxArray of mxLogical elementsmxCreateLogicalMatrix initializes each element in the array to logical 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray

1 API Reference

1-398

See AlsomxCreateLogicalArray mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalMatrix (C)

1-399

mxCreateLogicalScalar (C)Scalar logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalScalar(mxLogical value)

Argumentsvalue

Logical value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalScalar to create a scalar logical mxArraymxCreateLogicalScalar is a convenience function that replaces the following code

pa = mxCreateLogicalMatrix(1 1)mxGetLogicals(pa) = value

When you finish using the mxArray call mxDestroyArray to destroy it

1 API Reference

1-400

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxIsLogicalScalarmxIsLogicalScalarTrue mxGetLogicals mxDestroyArray

Introduced before R2006a

mxCreateLogicalScalar (C)

1-401

mxCreateNumericArray (C and Fortran)N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateNumericArray(mwSize ndim const mwSize dims mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericArray(ndim dims classid ComplexFlag)mwSize ndimmwSize dims(ndim)integer4 classid ComplexFlag

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classid

1 API Reference

1-402

value from a MATLAB class name See the Description on page 1-403 section formore information

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericArray to create an N-dimensional mxArray in which all dataelements have the numeric data type specified by classid After creating the mxArraymxCreateNumericArray initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericArray also initializes all itsimaginary data elements to 0 mxCreateNumericArray differs frommxCreateDoubleMatrix as follows

bull All data elements in mxCreateDoubleMatrix are double-precision floating-pointnumbers The data elements in mxCreateNumericArray can be any numerical typeincluding different integer precisions

bull mxCreateDoubleMatrix can create two-dimensional arrays onlymxCreateNumericArray can create arrays of two or more dimensions

mxCreateNumericArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

mxCreateNumericArray (C and Fortran)

1-403

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull doubleelementcbull matrixDividecbull matsqint8F

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-404

Introduced before R2006a

mxCreateNumericArray (C and Fortran)

1-405

mxCreateNumericMatrix (C and Fortran)2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateNumericMatrix(mwSize m mwSize n mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericMatrix(m n classid ComplexFlag)mwSize m ninteger4 classid ComplexFlag

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classidvalue from a MATLAB class name

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

1 API Reference

1-406

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which all data elements havethe numeric data type specified by classid After creating the mxArraymxCreateNumericMatrix initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericMatrix also initializes all itsimaginary data elements to 0 mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray When you finish using the mxArray call mxDestroyArrayto destroy it

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

mxCreateNumericMatrix (C and Fortran)

1-407

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrc

The following Fortran statements create a 4-by-3 matrix of REAL4 elements having noimaginary components

C Create 4x3 mxArray of REAL4 mxCreateNumericMatrix(4 3 + mxClassIDFromClassName(single) 0)

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericMatrix mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-408

mxCreateSparse (C and Fortran)2-D sparse array

C Syntaxinclude matrixhmxArray mxCreateSparse(mwSize m mwSize n mwSize nzmax mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateSparse(m n nzmax ComplexFlag)mwSize m n nzmaxinteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparse should allocate to hold the pr ir and ifComplexFlag is mxCOMPLEX in C (1 in Fortran) pi arrays Set the value of nzmax tobe greater than or equal to the number of nonzero elements you plan to put into themxArray but make sure that nzmax is less than or equal to mn nzmax is greaterthan or equal to 1

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

mxCreateSparse (C and Fortran)

1-409

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray In that case tryreducing nzmax m or n

DescriptionCall mxCreateSparse to create an unpopulated sparse double mxArray The returnedsparse mxArray contains no sparse information and cannot be passed as an argument toany MATLAB sparse functions To make the returned sparse mxArray useful initializethe pr ir jc and (if it exists) pi arrays

mxCreateSparse allocates space for

bull A pr array of length nzmaxbull A pi array of length nzmax but only if ComplexFlag is mxCOMPLEX in C (1 in

Fortran)bull An ir array of length nzmaxbull A jc array of length n+1

When you finish using the sparse mxArray call mxDestroyArray to reclaim all its heapspace

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

1 API Reference

1-410

See AlsomxDestroyArray mxSetNzmax mxSetPr mxSetPi mxSetIr mxSetJcmxComplexity

Introduced before R2006a

mxCreateSparse (C and Fortran)

1-411

mxCreateSparseLogicalMatrix (C)2-D sparse logical array

C Syntaxinclude matrixhmxArray mxCreateSparseLogicalMatrix(mwSize m mwSize n mwSize nzmax)

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparseLogicalMatrix should allocate to holdthe data Set the value of nzmax to be greater than or equal to the number of nonzeroelements you plan to put into the mxArray but make sure that nzmax is less than orequal to mn nzmax is greater than or equal to 1

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

1 API Reference

1-412

DescriptionUse mxCreateSparseLogicalMatrix to create an m-by-n mxArray of mxLogicalelements mxCreateSparseLogicalMatrix initializes each element in the array tological 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its elements

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxCreateSparse mxIsLogical

Introduced before R2006a

mxCreateSparseLogicalMatrix (C)

1-413

mxCreateString (C and Fortran)1-N array initialized to specified string

C Syntaxinclude matrixhmxArray mxCreateString(const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateString(str)character() str

Argumentsstr

String used to initialize mxArray data Only ASCII characters are supported

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateString to create an mxArray initialized to str Many MATLAB functions(for example strcmp and upper) require string array inputs

1 API Reference

1-414

mxCreateString supports both multi-byte and single-byte encoded characters OnWindows and Linux platforms the default encoding is specified by the user localesetting

Free the mxArray when you are finished using it by calling mxDestroyArray

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull revordcbull revordF

See the following examples in matlabrootexternexamplesmx

bull mxcreatestructarraycbull mxisclassc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxCreateCharMatrixFromStrings mxCreateCharArray

Introduced before R2006a

mxCreateString (C and Fortran)

1-415

mxCreateStructArray (C and Fortran)N-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructArray(mwSize ndim const mwSize dims int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructArray(ndim dims nfields fieldnames)mwSize ndimmwSize dims(ndim)integer4 nfieldscharacter() fieldnames(nfields)

Argumentsndim

Number of dimensions If you set ndim to be less than 2 mxCreateStructArraycreates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Typically the dims array should have ndim elements

nfieldsNumber of fields in each element Positive integer

fieldnamesList of field names Field names must be valid MATLAB identifiers which meansthey cannot be NULL or empty

1 API Reference

1-416

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateStructArray to create an unpopulated structure mxArray Each elementof a structure mxArray contains the same number of fields (specified in nfields) Eachfield has a name the list of names is specified in fieldnames A MATLAB structuremxArray is conceptually identical to an array of structs in the C language

Each field holds one mxArray pointer mxCreateStructArray initializes each field toNULL in C (0 in Fortran) Call mxSetField or mxSetFieldByNumber to place a non-NULL mxArray pointer in a field

When you finish using the returned structure mxArray call mxDestroyArray to reclaimits space

Any trailing singleton dimensions specified in the dims argument are automaticallyremoved from the resulting array For example if ndim equals 5 and dims equals [4 17 1 1] the resulting array is given the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

mxCreateStructArray (C and Fortran)

1-417

See AlsomxDestroyArray mxAddField mxRemoveField mxSetFieldmxSetFieldByNumber namelengthmax

Introduced before R2006a

1 API Reference

1-418

mxCreateStructMatrix (C and Fortran)2-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructMatrix(mwSize m mwSize n int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructMatrix(m n nfields fieldnames)mwSize m ninteger4 nfieldscharacter() fieldnames(nfields)

Argumentsm

Number of rows must be a positive integern

Number of columns must be a positive integernfields

Number of fields in each elementfieldnames

List of field names

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

mxCreateStructMatrix (C and Fortran)

1-419

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxCreateStructMatrix and mxCreateStructArray are almost identical The onlydifference is that mxCreateStructMatrix can create only two-dimensional mxArrayswhile mxCreateStructArray can create an mxArray having two or more dimensions

C ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray namelengthmax

Introduced before R2006a

1 API Reference

1-420

mxCreateUninitNumericArray (C)Uninitialized N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateUninitNumericArray(size_t ndim size_t dims mxClassID classid mxComplexity ComplexFlag)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateUninitNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericArray (C)

1-421

DescriptionCall mxCreateUninitNumericArray to create an N-dimensional mxArray in which alldata elements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericArray allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericMatrix mxCreateNumericArray

Introduced in R2015a

1 API Reference

1-422

mxCreateUninitNumericMatrix (C)Uninitialized 2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateUninitNumericMatrix(size_t m size_t n mxClassID classid mxComplexity ComplexFlag)

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericMatrix (C)

1-423

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreateuninitnumericmatrixc

DescriptionCall mxCreateUninitNumericMatrix to create a 2-D mxArray in which all dataelements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericMatrix allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-424

Introduced in R2015a

mxCreateUninitNumericMatrix (C)

1-425

mxDestroyArray (C and Fortran)Free dynamic memory allocated by MXCREATE functions

C Syntaxinclude matrixhvoid mxDestroyArray(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mxDestroyArray(pm)mwPointer pm

Argumentspm

Pointer to the mxArray to free If pm is a NULL pointer the function does nothing

DescriptionmxDestroyArray deallocates the memory occupied by the specified mxArray including

bull Characteristics fields of the mxArray such as size (m and n) and typebull Associated data arrays such as pr and pi for complex arrays and ir and jc for

sparse arraysbull Fields of structure arraysbull Cells of cell arrays

Do not call mxDestroyArray on an mxArray

bull returned in a left-side argument of a MEX file

1 API Reference

1-426

bull returned by the mxGetField or mxGetFieldByNumber functionsbull returned by the mxGetCell function

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexgetarrayc

See the following examples in matlabrootexternexamplesmx

bull mxisclasscbull mxcreatecellmatrixfF

See AlsomxCalloc mxMalloc mxFree mexMakeArrayPersistentmexMakeMemoryPersistent

Introduced before R2006a

mxDestroyArray (C and Fortran)

1-427

mxDuplicateArray (C and Fortran)Make deep copy of array

C Syntaxinclude matrixhmxArray mxDuplicateArray(const mxArray in)

Fortran Syntaxinclude fintrfhmwPointer mxDuplicateArray(in)mwPointer in

Argumentsin

Pointer to the mxArray you want to copy

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxDuplicateArray makes a deep copy of an array and returns a pointer to the copy Adeep copy refers to a copy in which all levels of data are copied For example a deep copyof a cell array copies each cell and the contents of each cell (if any)

1 API Reference

1-428

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxgetinfcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

Introduced before R2006a

mxDuplicateArray (C and Fortran)

1-429

mxFree (C and Fortran)Free dynamic memory allocated by mxCalloc mxMalloc mxRealloc mxArrayToString ormxArrayToUTF8String functions

C Syntaxinclude matrixhvoid mxFree(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mxFree(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of any memory parcel allocated by mxCalloc mxMalloc ormxRealloc If ptr is a NULL pointer the function does nothing

DescriptionmxFree deallocates heap space using the MATLAB memory management facility Thisfunction ensures correct memory management in error and abort (Ctrl+C) conditions

To deallocate heap space MATLAB applications in C should always call mxFree ratherthan the ANSI C free function

In MEX files but excluding MAT or engine standalone applications the MATLABmemory management facility maintains a list of all memory allocated by the followingfunctions

1 API Reference

1-430

bull mxCallocbull mxMallocbull mxReallocbull mxArrayToStringbull mxArrayToUTF8String

The memory management facility automatically deallocates all parcels managed by aMEX file when the MEX file completes and control returns to the MATLAB promptmxFree also removes the memory parcel from the memory management list of parcels

When mxFree appears in a MAT or engine standalone MATLAB application it simplydeallocates the contiguous heap space that begins at address ptr

In MEX files your use of mxFree depends on whether the specified memory parcel ispersistent or nonpersistent By default memory parcels created by mxCallocmxMalloc mxRealloc mxArrayToString and mxArrayToUTF8String arenonpersistent The memory management facility automatically frees all nonpersistentmemory whenever a MEX file completes Thus even if you do not call mxFree MATLABtakes care of freeing the memory for you Nevertheless it is good programming practiceto deallocate memory when you are through using it Doing so generally makes the entiresystem run more efficiently

If an application calls mexMakeMemoryPersistent the specified memory parcelbecomes persistent When a MEX file completes the memory management facility doesnot free persistent memory parcels Therefore the only way to free a persistent memoryparcel is to call mxFree Typically MEX files call mexAtExit to register a cleanuphandler The cleanup handler calls mxFree

Do not use mxFree for an mxArray created by any other functions in the Matrix LibraryAPI Use mxDestroyArray instead

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxcreatecharmatrixfromstrc

mxFree (C and Fortran)

1-431

bull mxisfinitecbull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxMalloc mxRealloc mxArrayToString mxArrayToUTF8String

Introduced before R2006a

1 API Reference

1-432

mxGetCell (C and Fortran)Pointer to element in cell array

C Syntaxinclude matrixhmxArray mxGetCell(const mxArray pm mwIndex index)

Fortran Syntaxinclude fintrfhmwPointer mxGetCell(pm index)mwPointer pmmwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Number of elements in the cell mxArray between the first element and the desiredone See mxCalcSingleSubscript for details on calculating an index in amultidimensional cell array

ReturnsPointer to the ith cell mxArray if successful Otherwise returns NULL in C (0 inFortran) Causes of failure include

bull Specifying the index of a cell array element that has not been populatedbull Specifying a pm that does not point to a cell mxArray

mxGetCell (C and Fortran)

1-433

bull Specifying an index to an element outside the bounds of the mxArraybull Insufficient heap space

Do not call mxDestroyArray on an mxArray returned by the mxGetCell function

DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexed element of the cellmxArray

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCellArray mxIsCell mxSetCell

Introduced before R2006a

1 API Reference

1-434

mxGetChars (C)Pointer to character array data

C Syntaxinclude matrixhmxChar mxGetChars(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first character in the mxArray Returns NULL if the specified array is not acharacter array

DescriptionCall mxGetChars to access the first character in the mxArray that array_ptr points toOnce you have the starting address you can access any other element in the mxArray

See AlsomxGetString

Introduced before R2006a

mxGetChars (C)

1-435

mxGetClassID (C and Fortran)Class of array

C Syntaxinclude matrixhmxClassID mxGetClassID(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetClassID(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumeric identifier of the class (category) of the mxArray that pm points to For a list ofC-language class identifiers see the mxClassID reference page For user-defined typesmxGetClassId returns a unique value identifying the class of the array contents UsemxIsClass to determine whether an array is of a specific user-defined type

DescriptionUse mxGetClassId to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray then mxGetClassId returns mxLOGICAL_CLASS (in C)

1 API Reference

1-436

mxGetClassId is like mxGetClassName except that the former returns the class as aninteger identifier and the latter returns the class as a string

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxClassID mxGetClassName mxIsClass

Introduced before R2006a

mxGetClassID (C and Fortran)

1-437

mxGetClassName (C and Fortran)Class of array as string

Note Use mxGetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhconst char mxGetClassName(const mxArray pm)

Fortran Syntaxinclude fintrfhcharacter() mxGetClassName(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsClass (as a string) of the mxArray pointed to by pm

DescriptionCall mxGetClassName to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray mxGetClassName returns logical

1 API Reference

1-438

mxGetClassID is like mxGetClassName except that the former returns the class as aninteger identifier as listed in the mxClassID reference page and the latter returns theclass as a string as listed in the mxIsClass reference page

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxGetClassID mxIsClass

Introduced before R2006a

mxGetClassName (C and Fortran)

1-439

mxGetData (C and Fortran)Pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxGetData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionIn C mxGetData returns a void pointer (void ) Since void pointers point to a valuethat has no type cast the return value to the pointer type that matches the type specifiedby pm To see how MATLAB types map to their equivalent C types see the table on themxClassID reference page

1 API Reference

1-440

In Fortran to copy values from the returned pointer use one of the mxCopyPtrTofunctions in the following manner

C Get the data in mxArray pm mxCopyPtrToReal8(mxGetData(pm)data + mxGetNumberOfElements(pm))

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxisfinitec

See AlsomxGetImagData mxGetPr mxClassID

Introduced before R2006a

mxGetData (C and Fortran)

1-441

mxGetDimensions (C and Fortran)Pointer to dimensions array

C Syntaxinclude matrixhconst mwSize mxGetDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element in the dimensions array Each integer in the dimensionsarray represents the number of elements in a particular dimension The array is notNULL terminated

DescriptionUse mxGetDimensions to determine how many elements are in each dimension of themxArray that pm points to Call mxGetNumberOfDimensions to get the number ofdimensions in the mxArray

To copy the values to Fortran use mxCopyPtrToInteger4 in the following manner

1 API Reference

1-442

C Get dimensions of mxArray pm mxCopyPtrToInteger4(mxGetDimensions(pm) dims + mxGetNumberOfDimensions(pm))

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetNumberOfDimensions

Introduced before R2006a

mxGetDimensions (C and Fortran)

1-443

mxGetElementSize (C and Fortran)Number of bytes required to store each data element

C Syntaxinclude matrixhsize_t mxGetElementSize(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetElementSize(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of bytes required to store one element of the specified mxArray if successfulReturns 0 on failure The primary reason for failure is that pm points to an mxArrayhaving an unrecognized class If pm points to a cell mxArray or a structure mxArraymxGetElementSize returns the size of a pointer (not the size of all the elements in eachcell or structure field)

DescriptionCall mxGetElementSize to determine the number of bytes in each data element of themxArray For example if the MATLAB class of an mxArray is int16 the mxArray

1 API Reference

1-444

stores each data element as a 16-bit (2-byte) signed integer Thus mxGetElementSizereturns 2

mxGetElementSize is helpful when using a non-MATLAB routine to manipulate dataelements For example the C function memcpy requires (for its third argument) the sizeof the elements you intend to copy

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull doubleelementcbull phonebookc

See AlsomxGetM mxGetN

Introduced before R2006a

mxGetElementSize (C and Fortran)

1-445

mxGetEps (C and Fortran)Value of EPS

C Syntaxinclude matrixhdouble mxGetEps(void)

Fortran Syntaxreal8 mxGetEps

ReturnsValue of the MATLAB eps variable

DescriptionCall mxGetEps to return the value of the MATLAB eps variable This variable holds thedistance from 10 to the next largest floating-point number As such it is a measure offloating-point accuracy The MATLAB pinv and rank functions use eps as a defaulttolerance

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

1 API Reference

1-446

See AlsomxGetInf mxGetNan

Introduced before R2006a

mxGetEps (C and Fortran)

1-447

mxGetField (C and Fortran)Pointer to field value from structure array given index and field name

C Syntaxinclude matrixhmxArray mxGetField(const mxArray pm mwIndex index const char fieldname)

Fortran Syntaxinclude fintrfhmwPointer mxGetField(pm index fieldname)mwPointer pmmwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

fieldnameName of the field whose value you want to extract

1 API Reference

1-448

ReturnsPointer to the mxArray in the specified field at the specified fieldname on successReturns NULL in C (0 in Fortran) if passed an invalid argument or if there is no valueassigned to the specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray Todetermine whether pm points to a structure mxArray call mxIsStruct

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains 10 elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent fieldname Call mxGetFieldNameByNumber ormxGetFieldNumber to get existing field names

bull Insufficient heap space

DescriptionCall mxGetField to get the value held in the specified element of the specified field Inpseudo-C terminology mxGetField returns the value at

pm[index]fieldname

mxGetFieldByNumber is like mxGetField Both functions return the same value Theonly difference is in the way you specify the field mxGetFieldByNumber takes a fieldnumber as its third argument and mxGetField takes a field name as its thirdargument

Do not call mxDestroyArray on an mxArray returned by the mxGetField function

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

mxGetField(pa index field_name)

mxGetField (C and Fortran)

1-449

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where if you have a 1-by-1 structure index is 0

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where if you have a 1-by-1 structure index is 1

ExamplesSee the following example in matlabrootexternexampleseng_mat

bull matreadstructarrayc

See AlsomxGetFieldByNumber mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-450

mxGetFieldByNumber (C and Fortran)Pointer to field value from structure array given index and field number

C Syntaxinclude matrixhmxArray mxGetFieldByNumber(const mxArray pm mwIndex index int fieldnumber)

Fortran Syntaxinclude fintrfhmwPointer mxGetFieldByNumber(pm index fieldnumber)mwPointer pmmwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for more details on calculating an indexfieldnumber

Position of the field whose value you want to extract

mxGetFieldByNumber (C and Fortran)

1-451

In C the first field within each element has a field number of 0 the second field hasa field number of 1 and so on The last field has a field number of N-1 where N is thenumber of fields

In Fortran the first 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 field number of N whereN is the number of fields

ReturnsPointer to the mxArray in the specified field for the desired element on success ReturnsNULL in C (0 in Fortran) if passed an invalid argument or if there is no value assigned tothe specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains ten elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent field number Call mxGetFieldNumber to determine thefield number that corresponds to a given field name

DescriptionCall mxGetFieldByNumber to get the value held in the specified fieldnumber at theindexed element

Do not call mxDestroyArray on an mxArray returned by the mxGetFieldByNumberfunction

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

1 API Reference

1-452

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldByNumber (C and Fortran)

1-453

mxGetFieldNameByNumber (C and Fortran)Pointer to field name from structure array given field number

C Syntaxinclude matrixhconst char mxGetFieldNameByNumber(const mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhcharacter() mxGetFieldNameByNumber(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Position of the desired field For instance in C to get the name of the first field setfieldnumber to 0 to get the name of the second field set fieldnumber to 1 and soon In Fortran to get the name of the first field set fieldnumber to 1 to get thename of the second field set fieldnumber to 2 and so on

ReturnsPointer to the nth field name on success Returns NULL in C (0 in Fortran) on failureCommon causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

1 API Reference

1-454

bull Specifying a value of fieldnumber outside the bounds of the number of fields in thestructure mxArray In C fieldnumber 0 represents the first field andfieldnumber N-1 represents the last field where N is the number of fields in thestructure mxArray In Fortran fieldnumber 1 represents the first field andfieldnumber N represents the last field

DescriptionCall mxGetFieldNameByNumber to get the name of a field in the given structuremxArray A typical use of mxGetFieldNameByNumber is to call it inside a loop to get thenames of all the fields in a given mxArray

Consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test A field number other than 0 1 or 2causes mxGetFieldNameByNumber to return NULL

In Fortran the field number 1 represents the field name field number 2 represents fieldbilling field number 3 represents field test A field number other than 1 2 or 3causes mxGetFieldNameByNumber to return 0

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

mxGetFieldNameByNumber (C and Fortran)

1-455

bull explorec

See AlsomxGetField mxGetFieldByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-456

mxGetFieldNumber (C and Fortran)Field number from structure array given field name

C Syntaxinclude matrixhint mxGetFieldNumber(const mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxGetFieldNumber(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of a field in the structure mxArray

ReturnsField number of the specified fieldname on success In C the first field has a fieldnumber of 0 the second field has a field number of 1 and so on In Fortran the first fieldhas a field number of 1 the second field has a field number of 2 and so on Returns -1 inC (0 in Fortran) on failure Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

mxGetFieldNumber (C and Fortran)

1-457

bull 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 do not know its fieldname call mxGetFieldNameByNumber

For example consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field name has a field number of 0 the field billing has a field number of 1and the field test has a field number of 2 If you call mxGetFieldNumber and specify afield name of anything other than name billing or test mxGetFieldNumber returns-1

Calling

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran the field name has a field number of 1 the field billing has a field numberof 2 and the field test has a field number of 3 If you call mxGetFieldNumber andspecify a field name of anything other than name billing or testmxGetFieldNumber returns 0

Calling

mxGetField(pm index fieldname)

is equivalent to calling

1 API Reference

1-458

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxGetField mxGetFieldByNumber mxGetFieldNameByNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldNumber (C and Fortran)

1-459

mxGetImagData (C and Fortran)Pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxGetImagData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetImagData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the imaginary data Returns NULL in C (0 in Fortran) ifthere is no imaginary data or if there is an error

DescriptionThis function is like mxGetPi except that in C it returns a void For moreinformation see the description for the mxGetData function

1 API Reference

1-460

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxGetData mxGetPi

Introduced before R2006a

mxGetImagData (C and Fortran)

1-461

mxGetInf (C and Fortran)Value of infinity

C Syntaxinclude matrixhdouble mxGetInf(void)

Fortran Syntaxreal8 mxGetInf

ReturnsValue of infinity on your system

DescriptionCall mxGetInf to return the value of the MATLAB internal inf variable inf is apermanent variable representing IEEEreg arithmetic positive infinity Your systemspecifies the value of inf you cannot modify it

Operations that return infinity include

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-462

bull mxgetinfc

See AlsomxGetEps mxGetNaN

Introduced before R2006a

mxGetInf (C and Fortran)

1-463

mxGetIr (C and Fortran)Sparse matrix IR array

C Syntaxinclude matrixhmwIndex mxGetIr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetIr(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the ir array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetIr to obtain the starting address of the ir array The ir array is an array ofintegers The length of ir is nzmax the storage allocated for the sparse array or nnz

1 API Reference

1-464

the number of nonzero matrix elements For example if nzmax equals 100 the ir arraycontains 100 integers

Each value in an ir array indicates a row (offset by 1) at which a nonzero element can befound (The jc array is an index that indirectly specifies a column where nonzeroelements can be found)

For details on the ir and jc arrays see mxSetIr and mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetJc mxGetNzmax mxSetIr mxSetJc mxSetNzmax nzmax nnz

Introduced before R2006a

mxGetIr (C and Fortran)

1-465

mxGetJc (C and Fortran)Sparse matrix JC array

C Syntaxinclude matrixhmwIndex mxGetJc(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetJc(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the jc array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetJc to obtain the starting address of the jc array The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

1 API Reference

1-466

The values in the jc array indirectly indicate columns containing nonzero elements Fora detailed explanation of the jc array see mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetIr mxGetNzmax mxSetIr mxSetJc mxSetNzmax

Introduced before R2006a

mxGetJc (C and Fortran)

1-467

mxGetLogicals (C)Pointer to logical array data

C Syntaxinclude matrixhmxLogical mxGetLogicals(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first logical element in the mxArray The result is unspecified if themxArray is not a logical array

DescriptionCall mxGetLogicals to access the first logical element in the mxArray that array_ptrpoints to Once you have the starting address you can access any other element in themxArray

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxIsLogical mxIsLogicalScalar mxIsLogicalScalarTrue

Introduced before R2006a

1 API Reference

1-468

mxGetM (C and Fortran)Number of rows in array

C Syntaxinclude matrixhsize_t mxGetM(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetM(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of rows in the mxArray to which pm points

DescriptionmxGetM returns the number of rows in the specified array The term rows always meansthe first dimension of the array no matter how many dimensions the array has Forexample if pm points to a four-dimensional array having dimensions 8-by-9-by-5-by-3mxGetM returns 8

mxGetM (C and Fortran)

1-469

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull matrixDividecbull matrixDivideComplexcbull revordcbull timestwocbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull timestwoFbull xtimesyF

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-470

bull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomxGetN mxSetM mxSetN

Introduced before R2006a

mxGetM (C and Fortran)

1-471

mxGetN (C and Fortran)Number of columns in array

C Syntaxinclude matrixhsize_t mxGetN(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetN(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of columns in the mxArray

DescriptionCall mxGetN to determine the number of columns in the specified mxArray

If pm is an N-dimensional mxArray mxGetN is the product of dimensions 2 through NFor example if pm points to a four-dimensional mxArray having dimensions 13-by-5-by-4-by-6 mxGetN returns the value 120 (5 times 4 times 6) If the specified mxArray has morethan two dimensions and you need to know exactly how many elements are in eachdimension call mxGetDimensions

1 API Reference

1-472

If pm points to a sparse mxArray mxGetN still returns the number of columns not thenumber of occupied columns

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull revordcbull timestwocbull xtimesyc

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxGetN (C and Fortran)

1-473

See AlsomxGetM mxGetDimensions mxSetM mxSetN

Introduced before R2006a

1 API Reference

1-474

mxGetNaN (C and Fortran)Value of NaN (Not-a-Number)

C Syntaxinclude matrixhdouble mxGetNaN(void)

Fortran Syntaxreal8 mxGetNaN

ReturnsValue of NaN (Not-a-Number) on your system

DescriptionCall mxGetNaN to return the value of NaN for your system NaN is the IEEE arithmeticrepresentation for Not-a-Number Certain mathematical operations return NaN as aresult for example

bull 0000bull Inf-Inf

Your system specifies the value of Not-a-Number You cannot modify it

C ExamplesSee the following examples in matlabrootexternexamplesmx

mxGetNaN (C and Fortran)

1-475

bull mxgetinfc

See AlsomxGetEps mxGetInf

Introduced before R2006a

1 API Reference

1-476

mxGetNumberOfDimensions (C and Fortran)Number of dimensions in array

C Syntaxinclude matrixhmwSize mxGetNumberOfDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNumberOfDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of dimensions in the specified mxArray The returned value is always 2 orgreater

DescriptionUse mxGetNumberOfDimensions to determine how many dimensions are in thespecified array To determine how many elements are in each dimension callmxGetDimensions

mxGetNumberOfDimensions (C and Fortran)

1-477

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsecbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See AlsomxSetM mxSetN mxGetDimensions

Introduced before R2006a

1 API Reference

1-478

mxGetNumberOfElements (C and Fortran)Number of elements in array

C Syntaxinclude matrixhsize_t mxGetNumberOfElements(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetNumberOfElements(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of elements in the specified mxArray

DescriptionmxGetNumberOfElements tells you how many elements an array has For example ifthe dimensions of an array are 3-by-5-by-10 mxGetNumberOfElements returns thenumber 150

mxGetNumberOfElements (C and Fortran)

1-479

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxgetepsfFbull mxgetinfcbull mxisfinitecbull mxsetdimensionscbull mxsetdimensionsfF

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetDimensions mxGetM mxGetN mxGetClassID mxGetClassName

Introduced before R2006a

1 API Reference

1-480

mxGetNumberOfFields (C and Fortran)Number of fields in structure array

C Syntaxinclude matrixhint mxGetNumberOfFields(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetNumberOfFields(pm)mwPointer pm

Argumentspm

Pointer to a structure mxArray

ReturnsNumber of fields on success Returns 0 on failure The most common cause of failure isthat pm is not a structure mxArray Call mxIsStruct to determine whether pm is astructure

DescriptionCall mxGetNumberOfFields to determine how many fields are in the specified structuremxArray

Once you know the number of fields in a structure you can loop through every field to setor to get field values

mxGetNumberOfFields (C and Fortran)

1-481

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxIsStruct mxSetField

Introduced before R2006a

1 API Reference

1-482

mxGetNzmax (C and Fortran)Number of elements in IR PR and PI arrays

C Syntaxinclude matrixhmwSize mxGetNzmax(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNzmax(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsNumber of elements allocated to hold nonzero entries in the specified sparse mxArray onsuccess Returns an indeterminate value on error The most likely cause of failure is thatpm points to a full (nonsparse) mxArray

DescriptionUse mxGetNzmax to get the value of the nzmax field The nzmax field holds an integervalue that signifies the number of elements in the ir pr and if it exists the pi arraysThe value of nzmax is always greater than or equal to the number of nonzero elements ina sparse mxArray In addition the value of nzmax is always less than or equal to thenumber of rows times the number of columns

mxGetNzmax (C and Fortran)

1-483

As you adjust the number of nonzero elements in a sparse mxArray MATLAB softwareoften adjusts the value of the nzmax field MATLAB adjusts nzmax to reduce the numberof costly reallocations and to optimize its use of heap space

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetnzmaxc

See AlsomxSetNzmax

Introduced before R2006a

1 API Reference

1-484

mxGetPi (C and Fortran)Imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPi(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPi(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the imaginary data elements of the specified mxArray on success ReturnsNULL in C (0 in Fortran) if there is no imaginary data or if there is an error

DescriptionUse mxGetPi on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetImagData

The pi field points to an array containing the imaginary data of the mxArray CallmxGetPi to get the contents of the pi field that is to get the starting address of thisimaginary data

mxGetPi (C and Fortran)

1-485

The best way to determine whether an mxArray is purely real is to call mxIsComplex

If any of the input matrices to a function are complex MATLAB allocates the imaginaryparts of all input matrices

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull fulltosparsec

For Fortran examples see

bull convecF

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetinfcbull mxisfinitecbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexcallmatlabc

See AlsomxGetPr mxSetPi mxSetPr mxGetImagData mxIsDouble

Introduced before R2006a

1 API Reference

1-486

mxGetPr (C and Fortran)Real data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPr(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionUse mxGetPr on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetData

Call mxGetPr to access the real data in the mxArray that pm points to Once you havethe starting address you can access any other element in the mxArray

mxGetPr (C and Fortran)

1-487

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull arrayFillGetPrcbull conveccbull doubleelementcbull findnzcbull fulltosparsecbull matrixDividecbull matrixMultiplycbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull sincallFbull timestwoFbull xtimesyF

See AlsomxGetPi mxSetPi mxSetPr mxGetData mxIsDouble

Introduced before R2006a

1 API Reference

1-488

mxGetProperty (C and Fortran)Value of public property of MATLAB object

C Syntaxinclude matrixhmxArray mxGetProperty(const mxArray pa mwIndex index const char propname)

Fortran Syntaxinclude fintrfhmwPointer mxGetProperty(pa index propname)mwPointer pamwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you want to extract

mxGetProperty (C and Fortran)

1-489

ReturnsPointer to the mxArray of the specified propname on success Returns NULL in C (0 inFortran) if unsuccessful Common causes of failure include

bull Specifying a nonexistent propnamebull Specifying a nonpublic propnamebull Specifying an index to an element outside the bounds of the mxArray To test the

index value use mxGetNumberOfElements or mxGetM and mxGetNbull Insufficient heap space

DescriptionCall mxGetProperty to get the value held in the specified element In pseudo-Cterminology mxGetProperty returns the value at

pa[index]propname

mxGetProperty makes a copy of the value If the property uses a large amount ofmemory creating a copy might be a concern There must be sufficient memory (in theheap) to hold the copy of the value

Examples

Display Name Property of timeseries Object

Create a MEX file disppropertyc in a folder on your MATLAB path================================================================= disppropertyc - Display timeseries Name property This is a MEX file for MATLAB Copyright 2013 The MathWorks Inc All rights reserved ================================================================= include mexh

void mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

1 API Reference

1-490

Check for proper number of arguments if(nrhs=1) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidNumInputs One input required) else if(nlhsgt1) mexErrMsgIdAndTxt( MATLABdisppropertymaxlhs Too many output arguments) Check for timeseries object if (mxIsClass(prhs[0] timeseries)) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidClass Input must be timeseries object) plhs[0] = mxGetProperty(prhs[0]0Name)

Build the MEX file

mex(-vdisppropertyc)

Create a timeseries object

ts = timeseries(rand(5 4)NameLaunchData)

Display name

tsname = dispproperty(ts)

tsname =LaunchData

Change Object Color

Open and build the mexgetpropertyc MEX file in the matlabrootexternexamplesmex folder

Limitationsbull mxGetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

mxGetProperty (C and Fortran)

1-491

See AlsomxSetProperty mxGetNumberOfElements mxGetM mxGetN

Introduced in R2008a

1 API Reference

1-492

mxGetScalar (C and Fortran)Real component of first data element in array

C Syntaxinclude matrixhdouble mxGetScalar(const mxArray pm)

Fortran Syntaxinclude fintrfhreal8 mxGetScalar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray cannot be a cell mxArray a structure mxArray or an emptymxArray

ReturnsThe value of the first real (nonimaginary) element of the mxArray

In C mxGetScalar returns a double If real elements in the mxArray are of a typeother than double then mxGetScalar automatically converts the scalar value into adouble To preserve the original data representation of the scalar cast the return valueto the desired data type

If pm points to a sparse mxArray then mxGetScalar returns the value of the firstnonzero real element in the mxArray If there are no nonzero elements then the functionreturns 0

mxGetScalar (C and Fortran)

1-493

DescriptionCall mxGetScalar to get the value of the first real (nonimaginary) element of themxArray

Usually you call mxGetScalar when pm points to an mxArray containing only oneelement (a scalar) However pm can point to an mxArray containing many elements Ifpm points to an mxArray containing multiple elements then the function returns thevalue of the first real element For example if pm points to a two-dimensional mxArraythen mxGetScalar returns the value of the (11) element If pm points to a three-dimensional mxArray then the function returns the value of the (111) element andso on

Use mxGetScalar on a nonempty mxArray of type numeric logical or char only To testfor these conditions use Matrix Library functions such as mxIsEmpty mxIsLogicalmxIsNumeric or mxIsChar

If the input value to mxGetScalar is type int64 or uint64 then the value might loseprecision if it is greater than flintmax

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull timestwoaltcbull xtimesyc

See the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

1 API Reference

1-494

See AlsomxGetM mxGetN mxIsScalar

mxGetScalar (C and Fortran)

1-495

mxGetString (C and Fortran)mxChar array to C-style string or Fortran character array

C Syntaxinclude matrixhint mxGetString(const mxArray pm char str mwSize strlen)

Fortran Syntaxinclude fintrfhinteger4 mxGetString(pm str strlen)mwPointer pmcharacter() strmwSize strlen

Argumentspm

Pointer to an mxChar arraystr

Starting location mxGetString writes the character data into str and then in Cterminates the string with a NULL character (in the manner of C strings) str canpoint to either dynamic or static memory

strlenSize in bytes of destination buffer pointed to by str Typically in C you set strlento 1 plus the number of elements in the mxArray to which pm points To get thenumber of elements use mxGetM or mxGetN

Do not use with ldquoMultibyte Encoded Charactersrdquo on page 1-497

1 API Reference

1-496

Returns0 on success or if strlen == 0 and 1 on failure Possible reasons for failure include

bull mxArray is not an mxChar arraybull strlen is not large enough to store the entire mxArray If so the function returns 1

and truncates the string

DescriptionCall mxGetString to copy the character data of an mxArray into a C-style string in C ora character array in Fortran The copied data starts at str and contains no more thanstrlen-1 characters in C (no more than strlen characters in Fortran) In C the C-style string is always terminated with a NULL character

If the array contains multiple rows the function copies them into a single array onecolumn at a time

Multibyte Encoded Characters

Use this function only with characters represented in single-byte encoding schemes Forcharacters represented in multibyte encoding schemes use the C functionmxArrayToString Fortran users must allocate sufficient space for the return string toavoid possible truncation

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmallocc

See the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

mxGetString (C and Fortran)

1-497

bull revordF

See AlsomxArrayToString mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetChars

Introduced before R2006a

1 API Reference

1-498

mxIsCell (C and Fortran)Determine whether input is cell array

C Syntaxinclude matrixhbool mxIsCell(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsCell(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCELL_CLASS and logical 0(false) otherwise

DescriptionUse mxIsCell to determine whether the specified array is a cell array

In C calling mxIsCell is equivalent to calling

mxGetClassID(pm) == mxCELL_CLASS

mxIsCell (C and Fortran)

1-499

In Fortran calling mxIsCell is equivalent to calling

mxGetClassName(pm) eq cell

Note mxIsCell does not answer the question ldquoIs this mxArray a cell of a cell arrayrdquo Anindividual cell of a cell array can be of any type

See AlsomxIsClass

Introduced before R2006a

1 API Reference

1-500

mxIsChar (C and Fortran)Determine whether input is mxChar array

C Syntaxinclude matrixhbool mxIsChar(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsChar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCHAR_CLASS and logical 0(false) otherwise

DescriptionUse mxIsChar to determine whether pm points to an mxChar array

In C calling mxIsChar is equivalent to calling

mxGetClassID(pm) == mxCHAR_CLASS

mxIsChar (C and Fortran)

1-501

In Fortran calling mxIsChar is equivalent to calling

mxGetClassName(pm) eq char

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull revordc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxmallocc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxIsClass mxGetClassID

Introduced before R2006a

1 API Reference

1-502

mxIsClass (C and Fortran)Determine whether array is object of specified class

C Syntaxinclude matrixhbool mxIsClass(const mxArray pm const char classname)

Fortran Syntaxinclude fintrfhinteger4 mxIsClass(pm classname)mwPointer pmcharacter() classname

Argumentspm

Pointer to an mxArrayclassname

Array category to test Specify classname as a string (not as an integer identifier)You can specify any one of the following predefined constants

Value of classname Corresponding Classcell mxCELL_CLASSchar mxCHAR_CLASSdouble mxDOUBLE_CLASSfunction_handle mxFUNCTION_CLASSint8 mxINT8_CLASSint16 mxINT16_CLASS

mxIsClass (C and Fortran)

1-503

Value of classname Corresponding Classint32 mxINT32_CLASSint64 mxINT64_CLASSlogical mxLOGICAL_CLASSsingle mxSINGLE_CLASSstruct mxSTRUCT_CLASSuint8 mxUINT8_CLASSuint16 mxUINT16_CLASSuint32 mxUINT32_CLASSuint64 mxUINT64_CLASSltclass_namegt ltclass_idgt

unknown mxUNKNOWN_CLASS

In the table ltclass_namegt represents the name of a specific MATLAB custom objectYou can also specify one of your own class names

ReturnsLogical 1 (true) if pm points to an array having category classname and logical 0(false) otherwise

DescriptionEach mxArray is tagged as being a certain type Call mxIsClass to determine whetherthe specified mxArray has this type MATLAB does not check if the class is derived froma base class

In C

mxIsClass(pm double)

is equivalent to calling either of these forms

1 API Reference

1-504

mxIsDouble(pm)

strcmp(mxGetClassName(pm) double)

In Fortran

mxIsClass(pm double)

is equivalent to calling either one of the following

mxIsDouble(pm)

mxGetClassName(pm) eq double

It is most efficient to use the mxIsDouble form

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxClassID mxGetClassID mxIsEmpty mxGetClassName

Introduced before R2006a

mxIsClass (C and Fortran)

1-505

mxIsComplex (C and Fortran)Determine whether data is complex

C Syntaxinclude matrixhbool mxIsComplex(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsComplex(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm is a numeric array containing complex data and logical 0 (false)otherwise If pm points to a cell array or a structure array mxIsComplex returns false

DescriptionUse mxIsComplex to determine whether an imaginary part is allocated for an mxArrayIf an mxArray is purely real and does not have any imaginary data the imaginarypointer pi is NULL in C (0 in Fortran) If an mxArray is complex pi points to an array ofnumbers

1 API Reference

1-506

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxgetinfc

See the following examples in matlabrootexternexamplesrefbook

bull conveccbull convecFbull fulltosparseFbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorecbull yprimecbull mexlockc

See AlsomxIsNumeric

Introduced before R2006a

mxIsComplex (C and Fortran)

1-507

mxIsDouble (C and Fortran)Determine whether mxArray represents data as double-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsDouble(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsDouble(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as double-precision floating-pointnumbers and logical 0 (false) otherwise

DescriptionCall mxIsDouble to determine whether the specified mxArray represents its real andimaginary data as double-precision floating-point numbers

Older versions of MATLAB software store all mxArray data as double-precision floating-point numbers However starting with MATLAB Version 5 software MATLAB can storereal and imaginary data in various numerical formats

1 API Reference

1-508

In C calling mxIsDouble is equivalent to calling

mxGetClassID(pm) == mxDOUBLE_CLASS

In Fortran calling mxIsDouble is equivalent to calling

mxGetClassName(pm) eq double

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsDouble (C and Fortran)

1-509

mxIsEmpty (C and Fortran)Determine whether array is empty

C Syntaxinclude matrixhbool mxIsEmpty(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsEmpty(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is empty and logical 0 (false) otherwise

DescriptionUse mxIsEmpty to determine whether an mxArray contains no data An mxArray isempty if the size of any of its dimensions is 0

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-510

bull mxisfinitec

See AlsomxIsClass

Introduced before R2006a

mxIsEmpty (C and Fortran)

1-511

mxIsFinite (C and Fortran)Determine whether input is finite

C Syntaxinclude matrixhbool mxIsFinite(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsFinite(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is finite and logical 0 (false) otherwise

DescriptionCall mxIsFinite to determine whether value is finite A number is finite if it is greaterthan -Inf and less than Inf

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-512

bull mxisfinitec

See AlsomxIsInf mxIsNan

Introduced before R2006a

mxIsFinite (C and Fortran)

1-513

mxIsFromGlobalWS (C and Fortran)Determine whether array was copied from MATLAB global workspace

C Syntaxinclude matrixhbool mxIsFromGlobalWS(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsFromGlobalWS(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array was copied out of the global workspace and logical 0(false) otherwise

DescriptionmxIsFromGlobalWS is useful for standalone MAT-file programs

1 API Reference

1-514

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnsc

Introduced before R2006a

mxIsFromGlobalWS (C and Fortran)

1-515

mxIsInf (C and Fortran)Determine whether input is infinite

C Syntaxinclude matrixhbool mxIsInf(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsInf(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is infinite and logical 0 (false) otherwise

DescriptionCall mxIsInf to determine whether value is equal to infinity or minus infinityMATLAB software stores the value of infinity in a permanent variable named Inf whichrepresents IEEE arithmetic positive infinity The value of the variable Inf is built intothe system you cannot modify it

Operations that return infinity include

1 API Reference

1-516

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

If value equals NaN (Not-a-Number) mxIsInf returns false In other words NaN is notequal to infinity

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxIsFinite mxIsNaN

Introduced before R2006a

mxIsInf (C and Fortran)

1-517

mxIsInt16 (C and Fortran)Determine whether array represents data as signed 16-bit integers

C Syntaxinclude matrixhbool mxIsInt16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt16 to determine whether the specified array represents its real andimaginary data as 16-bit signed integers

In C calling mxIsInt16 is equivalent to calling

mxGetClassID(pm) == mxINT16_CLASS

1 API Reference

1-518

In Fortran calling mxIsInt16 is equivalent to calling

mxGetClassName(pm) == int16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt16 (C and Fortran)

1-519

mxIsInt32 (C and Fortran)Determine whether array represents data as signed 32-bit integers

C Syntaxinclude matrixhbool mxIsInt32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt32 to determine whether the specified array represents its real andimaginary data as 32-bit signed integers

In C calling mxIsInt32 is equivalent to calling

mxGetClassID(pm) == mxINT32_CLASS

1 API Reference

1-520

In Fortran calling mxIsInt32 is equivalent to calling

mxGetClassName(pm) == int32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt32 (C and Fortran)

1-521

mxIsInt64 (C and Fortran)Determine whether array represents data as signed 64-bit integers

C Syntaxinclude matrixhbool mxIsInt64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt64 to determine whether the specified array represents its real andimaginary data as 64-bit signed integers

In C calling mxIsInt64 is equivalent to calling

mxGetClassID(pm) == mxINT64_CLASS

1 API Reference

1-522

In Fortran calling mxIsInt64 is equivalent to calling

mxGetClassName(pm) == int64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt64 (C and Fortran)

1-523

mxIsInt8 (C and Fortran)Determine whether array represents data as signed 8-bit integers

C Syntaxinclude matrixhbool mxIsInt8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 8-bit integers and logical 0 (false)otherwise

DescriptionUse mxIsInt8 to determine whether the specified array represents its real andimaginary data as 8-bit signed integers

In C calling mxIsInt8 is equivalent to calling

mxGetClassID(pm) == mxINT8_CLASS

1 API Reference

1-524

In Fortran calling mxIsInt8 is equivalent to calling

mxGetClassName(pm) eq int8

See AlsomxIsClass mxGetClassID mxIsInt16 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt8 (C and Fortran)

1-525

mxIsLogical (C and Fortran)Determine whether array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogical(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsLogical(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a logical mxArray Otherwise it returns logical 0(false)

DescriptionUse mxIsLogical to determine whether MATLAB software treats the data in themxArray as Boolean (logical) If an mxArray is logical MATLAB treats all zeros asmeaning false and all nonzero values as meaning true

1 API Reference

1-526

See AlsomxIsClass

TopicsldquoLogical Operationsrdquo

Introduced before R2006a

mxIsLogical (C and Fortran)

1-527

mxIsLogicalScalar (C)Determine whether scalar array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogicalScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is of class mxLogical and has 1-by-1 dimensionsOtherwise it returns logical 0 (false)

DescriptionUse mxIsLogicalScalar to determine whether MATLAB treats the scalar data in themxArray as logical or numerical

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalarTrue

TopicsldquoLogical Operationsrdquo

1 API Reference

1-528

Introduced before R2006a

mxIsLogicalScalar (C)

1-529

mxIsLogicalScalarTrue (C)Determine whether scalar array of type mxLogical is true

C Syntaxinclude matrixhbool mxIsLogicalScalarTrue(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the value of the mxArray logical scalar element is true Otherwise itreturns logical 0 (false)

DescriptionUse mxIsLogicalScalarTrue to determine whether the value of a scalar mxArray istrue or false

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalar

TopicsldquoLogical Operationsrdquo

1 API Reference

1-530

Introduced before R2006a

mxIsLogicalScalarTrue (C)

1-531

mxIsNaN (C and Fortran)Determine whether input is NaN (Not-a-Number)

C Syntaxinclude matrixhbool mxIsNaN(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsNaN(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is NaN (Not-a-Number) and logical 0 (false) otherwise

DescriptionCall mxIsNaN to determine whether value is NaN NaN is the IEEE arithmeticrepresentation for Not-a-Number A NaN is obtained as a result of mathematicallyundefined operations such as

bull 0000bull Inf-Inf

1 API Reference

1-532

The system understands a family of bit patterns as representing NaN NaN is not a singlevalue it is a family of numbers that MATLAB software (and other IEEE-compliantapplications) uses to represent an error condition or missing data

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsec

See AlsomxIsFinite mxIsInf

Introduced before R2006a

mxIsNaN (C and Fortran)

1-533

mxIsNumeric (C and Fortran)Determine whether array is numeric

C Syntaxinclude matrixhbool mxIsNumeric(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsNumeric(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array can contain numeric data The following class IDs representstorage types for arrays that can contain numeric data

bull mxDOUBLE_CLASSbull mxSINGLE_CLASSbull mxINT8_CLASSbull mxUINT8_CLASSbull mxINT16_CLASSbull mxUINT16_CLASS

1 API Reference

1-534

bull mxINT32_CLASSbull mxUINT32_CLASSbull mxINT64_CLASSbull mxUINT64_CLASS

Logical 0 (false) if the array cannot contain numeric data

DescriptionCall mxIsNumeric to determine whether the specified array contains numeric data Ifthe specified array has a storage type that represents numeric data mxIsNumericreturns logical 1 (true) Otherwise mxIsNumeric returns logical 0 (false)

Call mxGetClassID to determine the exact storage type

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxGetClassID

Introduced before R2006a

mxIsNumeric (C and Fortran)

1-535

mxIsScalar (C)Determine whether array is scalar array

C Syntaxinclude matrixhbool mxIsScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray has 1-by-1 dimensions Otherwise it returns logical 0(false)

Note Only use mxIsScalar for mxArray classes with IDs documented by mxClassID

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxisscalarc

See AlsomxClassID | mxGetScalar

1 API Reference

1-536

Introduced in R2015a

mxIsScalar (C)

1-537

mxIsSingle (C and Fortran)Determine whether array represents data as single-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsSingle(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSingle(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as single-precision floating-point numbersand logical 0 (false) otherwise

DescriptionUse mxIsSingle to determine whether the specified array represents its real andimaginary data as single-precision floating-point numbers

In C calling mxIsSingle is equivalent to calling

mxGetClassID(pm) == mxSINGLE_CLASS

1 API Reference

1-538

In Fortran calling mxIsSingle is equivalent to calling

mxGetClassName(pm) eq single

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsSingle (C and Fortran)

1-539

mxIsSparse (C and Fortran)Determine whether input is sparse array

C Syntaxinclude matrixhbool mxIsSparse(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSparse(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a sparse mxArray and logical 0 (false) otherwise Afalse return value means that pm points to a full mxArray or that pm does not point to avalid mxArray

DescriptionUse mxIsSparse to determine whether pm points to a sparse mxArray Many routines(for example mxGetIr and mxGetJc) require a sparse mxArray as input

1 API Reference

1-540

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

See Alsosparse mxGetIr mxGetJc mxCreateSparse

Introduced before R2006a

mxIsSparse (C and Fortran)

1-541

mxIsStruct (C and Fortran)Determine whether input is structure array

C Syntaxinclude matrixhbool mxIsStruct(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsStruct(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a structure mxArray and logical 0 (false) otherwise

DescriptionUse mxIsStruct to determine whether pm points to a structure mxArray Many routines(for example mxGetFieldNameByNumber and mxSetField) require a structuremxArray as an argument

1 API Reference

1-542

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldNameByNumbermxGetField mxSetField

Introduced before R2006a

mxIsStruct (C and Fortran)

1-543

mxIsUint16 (C and Fortran)Determine whether array represents data as unsigned 16-bit integers

C Syntaxinclude matrixhbool mxIsUint16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint16 to determine whether the specified mxArray represents its real andimaginary data as 16-bit unsigned integers

In C calling mxIsUint16 is equivalent to calling

mxGetClassID(pm) == mxUINT16_CLASS

1 API Reference

1-544

In Fortran calling mxIsUint16 is equivalent to calling

mxGetClassName(pm) eq uint16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint16 (C and Fortran)

1-545

mxIsUint32 (C and Fortran)Determine whether array represents data as unsigned 32-bit integers

C Syntaxinclude matrixhbool mxIsUint32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint32 to determine whether the specified mxArray represents its real andimaginary data as 32-bit unsigned integers

In C calling mxIsUint32 is equivalent to calling

mxGetClassID(pm) == mxUINT32_CLASS

1 API Reference

1-546

In Fortran calling mxIsUint32 is equivalent to calling

mxGetClassName(pm) eq uint32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint64

Introduced before R2006a

mxIsUint32 (C and Fortran)

1-547

mxIsUint64 (C and Fortran)Determine whether array represents data as unsigned 64-bit integers

C Syntaxinclude matrixhbool mxIsUint64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint64 to determine whether the specified mxArray represents its real andimaginary data as 64-bit unsigned integers

In C calling mxIsUint64 is equivalent to calling

mxGetClassID(pm) == mxUINT64_CLASS

1 API Reference

1-548

In Fortran calling mxIsUint64 is equivalent to calling

mxGetClassName(pm) eq uint64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint32

Introduced before R2006a

mxIsUint64 (C and Fortran)

1-549

mxIsUint8 (C and Fortran)Determine whether array represents data as unsigned 8-bit integers

C Syntaxinclude matrixhbool mxIsUint8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 8-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint8 to determine whether the specified mxArray represents its real andimaginary data as 8-bit unsigned integers

In C calling mxIsUint8 is equivalent to calling

mxGetClassID(pm) == mxUINT8_CLASS

1 API Reference

1-550

In Fortran calling mxIsUint8 is equivalent to calling

mxGetClassName(pm) eq uint8

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint8 (C and Fortran)

1-551

mxLogical (C)Type for logical array

DescriptionAll logical mxArrays store their data elements as mxLogical rather than as bool

The header file containing this type is

include matrixh

See AlsomxCreateLogicalArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

Introduced before R2006a

1 API Reference

1-552

mxMalloc (C and Fortran)Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxMalloc(mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxMalloc(n)mwSize n

Argumentsn

Number of bytes to allocate for n greater than 0

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxMalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxMalloc is unsuccessful when there is insufficient free heap space

If you call mxMalloc in C with value n = 0 MATLAB returns either NULL or a validpointer

mxMalloc (C and Fortran)

1-553

DescriptionmxMalloc allocates contiguous heap space sufficient to hold n bytes To allocate memoryin MATLAB applications use mxMalloc instead of the ANSI C malloc function

In MEX files but not MAT or engine applications mxMalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

1 API Reference

1-554

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxRealloc

Introduced before R2006a

mxMalloc (C and Fortran)

1-555

mxRealloc (C and Fortran)Reallocate dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxRealloc(void ptr mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxRealloc(ptr size)mwPointer ptrmwSize size

Argumentsptr

Pointer to a block of memory allocated by mxCalloc mxMalloc or mxReallocsize

New size of allocated memory in bytes

ReturnsPointer to the start of the reallocated block of memory if successful If unsuccessful in aMAT or engine standalone application mxRealloc returns NULL in C (0 in Fortran) andleaves the original memory block unchanged (Use mxFree to free the original memoryblock) If unsuccessful in a MEX file the MEX file terminates and control returns to theMATLAB prompt

mxRealloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-556

DescriptionmxRealloc changes the size of a memory block that has been allocated with mxCallocmxMalloc or mxRealloc To allocate memory in MATLAB applications use mxReallocinstead of the ANSI C realloc function

mxRealloc changes the size of the memory block pointed to by ptr to size bytes Thecontents of the reallocated memory are unchanged up to the smaller of the new and oldsizes The reallocated memory might be in a different location from the original memoryso the returned pointer can be different from ptr If the memory location changesmxRealloc frees the original memory block pointed to by ptr

If size is greater than 0 and ptr is NULL in C (0 in Fortran) mxRealloc behaves likemxMalloc mxRealloc allocates a new block of memory of size bytes and returns apointer to the new block

If size is 0 and ptr is not NULL in C (0 in Fortran) mxRealloc frees the memorypointed to by ptr and returns NULL in C (0 in Fortran)

In MEX files but not MAT or engine applications mxRealloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

mxRealloc (C and Fortran)

1-557

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxMalloc

Introduced before R2006a

1 API Reference

1-558

mxRemoveField (C and Fortran)Remove field from structure array

C Syntaxinclude matrixhvoid mxRemoveField(mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhsubroutine mxRemoveField(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Number of the field you want to remove In C to remove the first field setfieldnumber to 0 to remove the second field set fieldnumber to 1 and so on InFortran to remove the first field set fieldnumber to 1 to remove the second fieldset fieldnumber to 2 and so on

DescriptionCall mxRemoveField to remove a field from a structure array If the field does not existnothing happens This function does not destroy the field values To destroy the actualfield values call mxRemoveField and then call mxDestroyArray

Consider a MATLAB structure initialized to

mxRemoveField (C and Fortran)

1-559

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test In Fortran the field number 1represents the field name field number 2 represents field billing field number 3represents field test

See AlsomxAddField mxDestroyArray mxGetFieldByNumber

Introduced before R2006a

1 API Reference

1-560

mxSetCell (C and Fortran)Set contents of cell array

C Syntaxinclude matrixhvoid mxSetCell(mxArray pm mwIndex index mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetCell(pm index value)mwPointer pm valuemwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Index from the beginning of the mxArray Specify the number of elements betweenthe first cell of the mxArray and the cell you want to set The easiest way to calculateindex in a multidimensional cell array is to call mxCalcSingleSubscript

valuePointer to new value for the cell You can put an mxArray of any type into a cell Youcan even put another cell mxArray into a cell

DescriptionCall mxSetCell to put the designated value into a particular cell of a cell mxArray

mxSetCell (C and Fortran)

1-561

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxDestroyArray on the pointer returned by mxGetCellbefore you call mxSetCell

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray mxCreateCellMatrix mxGetCell mxIsCellmxDestroyArray

Introduced before R2006a

1 API Reference

1-562

mxSetClassName (C)Structure array to MATLAB object array

Note Use mxSetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhint mxSetClassName(mxArray array_ptr const char classname)

Argumentsarray_ptr

Pointer to an mxArray of class mxSTRUCT_CLASSclassname

Object class to which to convert array_ptr

Returns0 if successful and nonzero otherwise One cause of failure is that array_ptr is not astructure mxArray Call mxIsStruct to determine whether array_ptr is a structure

DescriptionmxSetClassName converts a structure array to an object array to be saved later to aMAT-file MATLAB does not register or validate the object until it is loaded by the LOADcommand If the specified classname is an undefined class within MATLAB LOADconverts the object back to a simple structure array

mxSetClassName (C)

1-563

See AlsomxIsClass mxGetClassID mxIsStruct

Introduced before R2006a

1 API Reference

1-564

mxSetData (C and Fortran)Set pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxSetData(mxArray pm void pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetData(pm pr)mwPointer pm pr

Argumentspm

Pointer to an mxArraypr

Pointer to an array Each element in the array contains the real component of avalue The array must be in dynamic memory call mxCalloc to allocate thismemory Do not use the ANSI C calloc function which can cause memoryalignment issues leading to program termination

DescriptionmxSetData is like mxSetPr except that in C its second argument is a void Use thisfunction on numeric arrays with contents other than double

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetData before you callmxSetData

mxSetData (C and Fortran)

1-565

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatac

See AlsomxCalloc mxFree mxGetData mxSetPr

Introduced before R2006a

1 API Reference

1-566

mxSetDimensions (C and Fortran)Modify number of dimensions and size of each dimension

C Syntaxinclude matrixhint mxSetDimensions(mxArray pm const mwSize dims mwSize ndim)

Fortran Syntaxinclude fintrfhinteger4 mxSetDimensions(pm dims ndim)mwPointer pmmwSize ndimmwSize dims(ndim)

Argumentspm

Pointer to an mxArraydims

Dimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray In most cases there are ndim elements in the dimsarray

ndimNumber of dimensions

mxSetDimensions (C and Fortran)

1-567

Returns0 on success and 1 on failure mxSetDimensions allocates heap space to hold the inputsize array So it is possible (though unlikely) that increasing the number of dimensionscan cause the system to run out of heap space

DescriptionCall mxSetDimensions to reshape an existing mxArray mxSetDimensions is likemxSetM and mxSetN however mxSetDimensions provides greater control for reshapingan mxArray that has more than two dimensions

mxSetDimensions does not allocate or deallocate any space for the pr or pi arrays Soif your call to mxSetDimensions increases the number of elements in the mxArrayenlarge the pr (and pi if it exists) arrays accordingly

If your call to mxSetDimensions reduces the number of elements in the mxArray youcan optionally reduce the size of the pr and pi arrays using mxRealloc

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetdimensionsfF

See AlsomxGetNumberOfDimensions mxSetM mxSetN mxRealloc

Introduced before R2006a

1 API Reference

1-568

mxSetField (C and Fortran)Set field value in structure array given index and field name

C Syntaxinclude matrixhvoid mxSetField(mxArray pm mwIndex index const char fieldname mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetField(pm index fieldname pvalue)mwPointer pm pvaluemwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of an element in the array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an index

mxSetField (C and Fortran)

1-569

fieldnameName of a field in the structure The field must exist in the structure CallmxGetFieldNameByNumber or mxGetFieldNumber to determine existing fieldnames

pvaluePointer to an mxArray containing the data you want to assign to fieldname

DescriptionUse mxSetField to assign the contents of pvalue to the field fieldname of elementindex

If you want to replace the contents of fieldname first free the memory of the existingdata Use the mxGetField function to get a pointer to the field call mxDestroyArray onthe pointer then call mxSetField to assign the new value

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then call mxSetFieldon each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

1 API Reference

1-570

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldmxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetFieldByNumber mxDestroyArray mxCalcSingleSubscript

Alternatives

C Language

In C you can replace the statements

field_num = mxGetFieldNumber(pa fieldname)mxSetFieldByNumber(pa index field_num new_value_pa)

with a call to mxSetField

mxSetField(pa index fieldname new_value_pa)

Fortran Language

In Fortran you can replace the statements

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

with a call to mxSetField

mxSetField(pm index fieldname newvalue)

Introduced before R2006a

mxSetField (C and Fortran)

1-571

mxSetFieldByNumber (C and Fortran)Set field value in structure array given index and field number

C Syntaxinclude matrixhvoid mxSetFieldByNumber(mxArray pm mwIndex index int fieldnumber mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetFieldByNumber(pm index fieldnumber pvalue)mwPointer pm pvaluemwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an indexfieldnumber

Position of the field in the structure The field must exist in the structure

1 API Reference

1-572

In C the first field within each element has a fieldnumber of 0 The fieldnumberof the last is N-1 where N is the number of fields

In Fortran the first field within each element has a fieldnumber of 1 Thefieldnumber of the last is N where N is the number of fields

pvaluePointer to the mxArray containing the data you want to assign

DescriptionUse mxSetFieldByNumber to assign the contents of pvalue to the field specified byfieldnumber of element index mxSetFieldByNumber is like mxSetField howeverthe function identifies the field by position number not by name

If you want to replace the contents at fieldnumber first free the memory of the existingdata Use the mxGetFieldByNumber function to get a pointer to the field callmxDestroyArray on the pointer then call mxSetFieldByNumber to assign the newvalue

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then callmxSetFieldByNumber on each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

mxSetFieldByNumber (C and Fortran)

1-573

Alternatives

C Language

In C calling

mxSetField(pa index field_name new_value_pa)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxSetFieldByNumber(pa index field_num new_value_pa)

Fortran Language

In Fortran calling

mxSetField(pm index fieldname newvalue)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldByNumbermxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxDestroyArray mxCalcSingleSubscript

Introduced before R2006a

1 API Reference

1-574

mxSetImagData (C and Fortran)Set pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxSetImagData(mxArray pm void pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetImagData(pm pi)mwPointer pm pi

Argumentspm

Pointer to an mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory errors will result when the array is destroyed

DescriptionmxSetImagData is like mxSetPi except that in C its pi argument is a void Usethis function on numeric arrays with contents other than double

mxSetImagData (C and Fortran)

1-575

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetImagData beforeyou call mxSetImagData

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxCalloc mxFree mxGetImagData mxSetPi

Introduced before R2006a

1 API Reference

1-576

mxSetIr (C and Fortran)IR array of sparse array

C Syntaxinclude matrixhvoid mxSetIr(mxArray pm mwIndex ir)

Fortran Syntaxinclude fintrfhsubroutine mxSetIr(pm ir)mwPointer pm ir

Argumentspm

Pointer to a sparse mxArrayir

Pointer to the ir array The ir array must be sorted in column-major order

DescriptionUse mxSetIr to specify the ir array of a sparse mxArray The ir array is an array ofintegers the length of the ir array equals the value of nzmax the storage allocated forthe sparse array or nnz the number of nonzero matrix elements

Each element in the ir array indicates a row (offset by 1) at which a nonzero elementcan be found (The jc array is an index that indirectly specifies a column where nonzeroelements can be found See mxSetJc for more details on jc)

mxSetIr (C and Fortran)

1-577

For example suppose that you create a 7-by-3 sparse mxArray named Sparrowcontaining six nonzero elements by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The pr array holds the real data for the sparse matrix which in Sparrow is the five 1sand the one 2 If there is any nonzero imaginary data it is in a pi arraySubscript ir pr jc Comments(21) 1 1 0 Column 1 ir is 1 because row is 2(51) 4 1 2 Column 1 ir is 4 because row is 5(32) 2 1 3 Column 2 ir is 2 because row is 3(23) 1 2 6 Column 3 ir is 1 because row is 2(53) 4 1 Column 3 ir is 4 because row is 5(63) 5 1 Column 3 ir is 5 because row is 6

Notice how each element of the ir array is always 1 less than the row of thecorresponding nonzero element For instance the first nonzero element is in row 2therefore the first element in ir is 1 (that is 2 ndash 1) The second nonzero element is inrow 5 therefore the second element in ir is 4 (5 ndash 1)

The ir array must be in column-major order The ir array must define the row positionsin column 1 (if any) first then the row positions in column 2 (if any) second and so onthrough column N Within each column row position 1 must appear before row position2 and so on

mxSetIr does not sort the ir array for you you must specify an ir array that is alreadysorted

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetIr before you callmxSetIr

1 API Reference

1-578

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateSparse mxGetIr mxGetJc mxSetJc mxFree nzmax nnz

Introduced before R2006a

mxSetIr (C and Fortran)

1-579

mxSetJc (C and Fortran)JC array of sparse array

C Syntaxinclude matrixhvoid mxSetJc(mxArray pm mwIndex jc)

Fortran Syntaxinclude fintrfhsubroutine mxSetJc(pm jc)mwPointer pm jc

Argumentspm

Pointer to a sparse mxArrayjc

Pointer to the jc array

DescriptionUse mxSetJc to specify a new jc array for a sparse mxArray The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

If the jth column of the sparse mxArray has any nonzero elements

bull jc[j] is the index in ir pr and pi (if it exists) of the first nonzero element in thejth column

bull jc[j+1]-1 is the index of the last nonzero element in the jth column

1 API Reference

1-580

bull For the jth column of the sparse matrix jc[j] is the total number of nonzeroelements in all preceding columns

The number of nonzero elements in the jth column of the sparse mxArray is

jc[j+1] - jc[j]

For the jth column of the sparse mxArray jc[j] is the total number of nonzeroelements in all preceding columns The last element of the jc array jc[number ofcolumns] is equal to nnz which is the number of nonzero elements in the entire sparsemxArray

For example consider a 7-by-3 sparse mxArray named Sparrow containing six nonzeroelements created by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The following table lists the contents of the ir jc and pr arraysSubscript ir pr jc Comment(21) 1 1 0 Column 1 contains two nonzero

elements with rows designated byir[0] and ir[1]

(51) 4 1 2 Column 2 contains one nonzeroelement with row designated by ir[2]

(32) 2 1 3 Column 3 contains three nonzeroelements with rows designated byir[3]ir[4] and ir[5]

(23) 1 2 6 There are six nonzero elements in all(53) 4 1 (63) 5 1

mxSetJc (C and Fortran)

1-581

As an example of a much sparser mxArray consider a 1000-by-8 sparse mxArray namedSpacious containing only three nonzero elements The ir pr and jc arrays containthe values listed in this tableSubscript ir pr jc Comment(732) 72 1 0 Column 1 contains no nonzero

elements(503) 49 1 0 Column 2 contains one nonzero

element with row designated by ir[0](645) 63 1 1 Column 3 contains one nonzero

element with row designated by ir[1] 2 Column 4 contains no nonzero

elements 2 Column 5 contains one nonzero

element with row designated by ir[2] 3 Column 6 contains no nonzero

elements 3 Column 7 contains no nonzero

elements 3 Column 8 contains no nonzero

elements 3 There are three nonzero elements in all

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetJc before you callmxSetJc

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-582

See AlsomxCreateSparse mxGetIr mxGetJc mxSetIr mxFree

Introduced before R2006a

mxSetJc (C and Fortran)

1-583

mxSetM (C and Fortran)Set number of rows in array

C Syntaxinclude matrixhvoid mxSetM(mxArray pm mwSize m)

Fortran Syntaxinclude fintrfhsubroutine mxSetM(pm m)mwPointer pmmwSize m

Argumentspm

Pointer to an mxArraym

Number of rows

DescriptionCall mxSetM to set the number of rows in the specified mxArray The term rows meansthe first dimension of an mxArray regardless of the number of dimensions Call mxSetNto set the number of columns

You typically use mxSetM to change the shape of an existing mxArray The mxSetMfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So ifyour calls to mxSetM and mxSetN increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays Call mxRealloc to enlarge them

1 API Reference

1-584

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetN mxRealloc

Introduced before R2006a

mxSetM (C and Fortran)

1-585

mxSetN (C and Fortran)Set number of columns in array

C Syntaxinclude matrixhvoid mxSetN(mxArray pm mwSize n)

Fortran Syntaxinclude fintrfhsubroutine mxSetN(pm n)mwPointer pmmwSize n

Argumentspm

Pointer to an mxArrayn

Number of columns

DescriptionCall mxSetN to set the number of columns in the specified mxArray The term columnsalways means the second dimension of a matrix Calling mxSetN forces an mxArray tohave two dimensions For example if pm points to an mxArray having three dimensionscalling mxSetN reduces the mxArray to two dimensions

You typically use mxSetN to change the shape of an existing mxArray The mxSetNfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So if

1 API Reference

1-586

your calls to mxSetN and mxSetM increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetM

Introduced before R2006a

mxSetN (C and Fortran)

1-587

mxSetNzmax (C and Fortran)Set storage space for nonzero elements

C Syntaxinclude matrixhvoid mxSetNzmax(mxArray pm mwSize nzmax)

Fortran Syntaxinclude fintrfhsubroutine mxSetNzmax(pm nzmax)mwPointer pmmwSize nzmax

Argumentspm

Pointer to a sparse mxArraynzmax

Number of elements mxCreateSparse should allocate to hold the arrays pointed toby ir pr and pi (if it exists) Set nzmax greater than or equal to the number ofnonzero elements in the mxArray but set it to be less than or equal to the number ofrows times the number of columns If you specify an nzmax value of 0 mxSetNzmaxsets the value of nzmax to 1

DescriptionUse mxSetNzmax to assign a new value to the nzmax field of the specified sparsemxArray The nzmax field holds the maximum number of nonzero elements in the sparsemxArray

1 API Reference

1-588

The number of elements in the ir pr and pi (if it exists) arrays must be equal tonzmax Therefore after calling mxSetNzmax you must change the size of the ir pr andpi arrays To change the size of one of these arrays

1 Call mxRealloc with a pointer to the array setting the size to the new value ofnzmax

2 Call the appropriate mxSet routine (mxSetIr mxSetPr or mxSetPi) to establishthe new memory area as the current one

Ways to determine how large to make nzmax are

bull Set nzmax equal to or slightly greater than the number of nonzero elements in asparse mxArray This approach conserves precious heap space

bull Make nzmax equal to the total number of elements in an mxArray This approacheliminates (or at least reduces) expensive reallocations

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetNzmax mxRealloc

Introduced before R2006a

mxSetNzmax (C and Fortran)

1-589

mxSetPi (C and Fortran)Set new imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPi(mxArray pm double pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetPi(pm pi)mwPointer pm pi

Argumentspm

Pointer to a full (nonsparse) mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory leaks and other memory errors might result

DescriptionUse mxSetPi to set the imaginary data of the specified mxArray

Most mxCreate functions optionally allocate heap space to hold imaginary data If youtell an mxCreate function to allocate heap spacemdashfor example by setting theComplexFlag to mxCOMPLEX in C (1 in Fortran) or by setting pi to a non-NULL value in

1 API Reference

1-590

C (a nonzero value in Fortran)mdashyou do not ordinarily use mxSetPi to initialize thecreated mxArrays imaginary elements Rather you call mxSetPi to replace the initialimaginary values with new ones

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPi before you callmxSetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetImagData mxSetPr mxFree

Introduced before R2006a

mxSetPi (C and Fortran)

1-591

mxSetPr (C and Fortran)Set new real data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPr(mxArray pm double pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetPr(pm pr)mwPointer pm pr

Argumentspm

Pointer to a full (nonsparse) mxArraypr

Pointer to the first element of an array Each element in the array contains the realcomponent of a value The array must be in dynamic memory call mxCalloc toallocate this memory Do not use the ANSI C calloc function which can causememory alignment issues leading to program termination If pr points to staticmemory memory leaks and other memory errors can result

DescriptionUse mxSetPr to set the real data of the specified mxArray

All mxCreate calls allocate heap space to hold real data Therefore you do notordinarily use mxSetPr to initialize the real elements of a freshly created mxArrayRather you call mxSetPr to replace the initial real values with new ones

1 API Reference

1-592

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPr before you callmxSetPr

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

See the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetData mxSetPi mxFree

Introduced before R2006a

mxSetPr (C and Fortran)

1-593

mxSetProperty (C and Fortran)Set value of public property of MATLAB object

C Syntaxinclude matrixhvoid mxSetProperty(mxArray pa mwIndex index const char propname const mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetProperty(pa index propname value)mwPointer pa valuemwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you are assigning

valuePointer to the mxArray you are assigning

1 API Reference

1-594

DescriptionUse mxSetProperty to assign a value to the specified property In pseudo-Cterminology mxSetProperty performs the assignment

pa[index]propname = value

Property propname must be an existing public property and index must be within thebounds of the mxArray To test the index value use mxGetNumberOfElements ormxGetM and mxGetN functions

mxSetProperty makes a copy of the value before assigning it as the new property valueMaking a copy might be a concern if the property uses a large amount of memory Theremust be sufficient memory (in the heap) to hold the copy of the value

Limitationsbull mxSetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

See AlsomxGetProperty

Introduced in R2008a

mxSetProperty (C and Fortran)

1-595

Page 3: C and Fortran API Reference

Revision HistoryDecember 1996 First Printing New for MATLAB 5 (Release 8)May 1997 Online only Revised for MATLAB 51 (Release 9)January 1998 Online Only Revised for MATLAB 52 (Release 10)January 1999 Online Only Revised for MATLAB 53 (Release 11)September 2000 Online Only Revised for MATLAB 60 (Release 12)June 2001 Online only Revised for MATLAB 61 (Release 121)July 2002 Online only Revised for MATLAB 65 (Release 13)January 2003 Online only Revised for MATLAB 651 (Release 13SP1)June 2004 Online only Revised for MATLAB 70 (Release 14)October 2004 Online only Revised for MATLAB 701 (Release 14SP1)March 2005 Online only Revised for MATLAB 704 (Release 14SP2)September 2005 Online only Revised for MATLAB 71 (Release 14SP3)March 2006 Online only Revised for MATLAB 72 (Release 2006a)September 2006 Online only Revised for MATLAB 73 (Release 2006b)March 2007 Online only Revised and renamed for MATLAB 74

(Release 2007a)September 2007 Online only Revised and renamed for MATLAB 75

(Release 2007b)March 2008 Online only Revised and renamed for MATLAB 76

(Release 2008a)October 2008 Online only Revised and renamed for MATLAB 77

(Release 2008b)March 2009 Online only Revised for MATLAB 78 (Release 2009a)September 2009 Online only Revised for MATLAB 79 (Release 2009b)March 2010 Online only Revised and renamed for MATLAB 710

(Release 2010a)September 2010 Online only Revised for MATLAB 711 (Release 2010b)April 2011 Online only Revised for MATLAB 712 (Release 2011a)September 2011 Online only Revised for MATLAB 713 (Release 2011b)March 2012 Online only Revised for MATLAB 714 (Release 2012a)September 2012 Online only Revised for MATLAB 80 (Release 2012b)March 2013 Online only Revised for MATLAB 81 (Release 2013a)September 2013 Online only Revised for MATLAB 82 (Release 2013b)March 2014 Online only Revised for MATLAB 83 (Release 2014a)October 2014 Online only Revised for MATLAB 84 (Release 2014b)March 2015 Online only Revised for MATLAB 85 (Release 2015a)September 2015 Online only Revised for MATLAB 86 (Release 2015b)March 2016 Online only Revised for MATLAB 90 (Release 2016a)September 2016 Online only Revised for MATLAB 91 (Release 2016b)March 2017 Online only Revised for MATLAB 92 (Release 2017a)September 2017 Online only Revised for MATLAB 93 (Release 2017b)

API Reference1

v

Contents

API Reference

1

matlabdataArrayDimensionsType specifying array dimensions

DescriptionUse the ArrayDimensions type to specify the size of an array ArrayDimensions isspecified as

using ArrayDimensions = stdvectorltsize_tgt

Free Function

getNumElementsinline size_t getNumElements(const ArrayDimensionsamp dims)

Determine the number of elements based on the ArrayDimensions

const ArrayDimensionsampdims

Array dimensions

inline size_t Number of elements

None

See Also

TopicsldquoMATLAB Data API Typesrdquo

1 API Reference

1-2

Introduced in R2017b

matlabdataArrayDimensions

1-3

matlabdataArrayElementRefC++ class representing element of Array or ReferenceltArraygt object

DescriptionAn ArrayElementRef object is created when using operator[] into an Array or aReferenceltArraygt It is untyped since Array and ReferenceltArraygt do not havetype information It collects up the indexes specified by the user and can be cast to anelement if the array holds primitive data or can be used to create a ReferenceltTgtinstance

Indexing is zero-based

Class DetailsNamespace matlabdataInclude ArrayElementRefhpp

Template Parametersbool is_const_ref Indicates if this reference is const The non-const

version of this class supports assignment

Other Operatorsbull ldquooperator[]rdquo on page 1-4bull ldquooperator Trdquo on page 1-5bull ldquooperator=rdquo on page 1-6

operator[]ArrayElementRefltis_const_refgt operator[](size_t idx)

ArrayElementRefltis_const_refgt operator[](stdstring idx)

1 API Reference

1-4

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indices in anindexing operation

stdstring idx Index to add Array must support string indexing

TooManyIndicesProvidedException

Too many indices provided The number of size_tindices is more than the number of dimensions in thearray

StringIndexMustBeLastException

String index is not the last index A size_t index isprovided after a string index

StringIndexNotValidException

An stdstring index is not valid for this array

CanOnlyUseOneStringIndexException

More than one stdstring index provided

double val = arr[2][7][f1]

operator Ttemplate lttypename Tgtoperator T() const

Cast a value Throws an error if not arithmetic complex or stdstring

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain the type specifiedby T

Array dblArray_const = factorycreateArrayltdoublegt(22)double val = dblArray_const[1][2]

matlabdataArrayElementRef

1-5

operator=template lttypename TgtArrayElementRefltis_const_refgtamp operator= (T rhs)

Assign a primitive or complex type to an element of an Array The Array must be non-const

If the Array contains other Arrays then operator= can assign an Array into theelement

T rhs The value to assign to an element in the Array specifiedas a primitive or complex type or as an Array

ArrayElementRefltis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain a primitive orcomplex type or does not contain other Arrays

Assign numeric types to Array arr

Array arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55arr[1][2] = stdcomplexltdoublegt(54 31)

Assign an Array to cell_arr then create a ReferenceltArraygt ref to the element

Array cell_arr = factorycreateArrayltArraygt(13)cell_arr[2] = factorycreateScalar(true)ReferenceltArraygt ref = cell_arr[2]

See AlsoArray | ArrayElementTypedRef | Reference | TypedArrayRef

1 API Reference

1-6

Introduced in R2017b

matlabdataArrayElementRef

1-7

matlabdataArrayElementTypedRefC++ class representing element of TypedArray or TypedArrayRef object

DescriptionAn ArrayElementTypedRef object is created when using operator[] into aTypedArrayltTgt or a TypedArrayRefltTgt It collects up the indexes specified by theuser and can be cast to ltTgt without the added cost of type checking that exists whenusing ArrayElementRef Primitive types can be cast to Tamp which is not supported withArrayElementRef The non-const version of this class supports assignment

Class DetailsNamespace matlabdataInclude ArrayElementTypedRefhpp

Template ParametersT Element typesbool is_const_ref TBD

Other Operatorsbull ldquooperator[]rdquo on page 1-8bull ldquooperator referencerdquo on page 1-9bull ldquooperator=rdquo on page 1-10

operator[]ArrayElementTypedRefltT is_const_refgt operator[](size_t idx)

ArrayElementTypedRefltArray is_const_refgt operator[](stdstringidx)

1 API Reference

1-8

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indicesin an indexing operation

stdstring idx Index to add Array must support string indexing

ArrayElementTypedRefltArray is_const_refgt

New instance with the additional index

TooManyIndicesProvidedException

Too many indices provided

StringIndexMustBeLastException

String index is not the last index

double val = arr[2][7][3]

operator referenceoperator reference() const

operator stdstring() const

Cast to reference to its primitive value

T

stdstring

The value

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

double val = dblArray[1][2]

stdstring val = strArray[1][2]

matlabdataArrayElementTypedRef

1-9

operator=ArrayElementTypedRefltT is_const_refgtamp operator= (T rhs)

ArrayElementTypedRefltT is_const_refgtamp operator= (stdstring rhs)

Assign a value into an Array The Array must be non-const

T rhs

stdstring rhs

Value to assign to an element in the Array

ArrayElementTypedRefltTis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

arr[1][2] = stdcomplexltdoublegt(54 31)

arr[1][2] = MyString

ExamplesTBD

TypedArrayltdoublegt arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55doubleamp val = arr[0][0]CellArray cell_arr = factorycreateArrayltArraygt(12)cell_arr[0] = factorycreateScalar(105)cell_arr[1] = factorycreateScalar(false)ArrayRef ref_to_element = cell_arr[0]TypedArrayRefltdoublegt typed_ref_to_element = cell_arr[0]

1 API Reference

1-10

Array const shared_copy_of_element = cell_arr[1]TypedArrayltboolgt const typed_shared_copy_of_element = cell_arr[1]

See AlsoArray | ArrayElementRef | ArrayElementTypedRef | Reference |TypedArrayRef | TypedIterator

Introduced in R2017b

matlabdataArrayElementTypedRef

1-11

matlabdataArrayFactoryC++ class to create arrays

DescriptionUse ArrayFactory to create matlabdataArray objects

Class DetailsNamespace matlabdataInclude ArrayFactoryhpp

Constructors

Default Constructor

ArrayFactory()

FailedToLoadLibMatlabDataArrayException

Concrete implementation has not been loaded

Destructor~ArrayFactory()

Member Functionsbull ldquocreateArrayrdquo on page 1-13bull ldquocreateScalarrdquo on page 1-14bull ldquocreateCellArrayrdquo on page 1-15

1 API Reference

1-12

bull ldquocreateCharArrayrdquo on page 1-16bull ldquocreateStructArrayrdquo on page 1-17bull ldquocreateEnumArrayrdquo on page 1-18bull ldquocreateSparseArrayrdquo on page 1-19bull ldquocreateEmptyArrayrdquo on page 1-20bull ldquocreateBufferrdquo on page 1-21bull ldquocreateArrayFromBufferrdquo on page 1-21

createArraytemplate lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims)

template lttypename ItType typename TgtTypedArrayltTgt createArray(ArrayDimensions dims ItType begin ItType end)

template lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims const T const begin const T const end)

template lttypename Tgt TypedArrayltTgt createArray(ArrayDimensions dims stdinitializer_listltTgt data)

Creates a TypedArrayltTgt with the given dimensions Fills the array with data ifspecified Data is copied and must be in column major order

bull ItType - Iterator types specified as stditeratorbull T - Element types specified as one of the following C++ data types

bool int8_t int16_t int32_t int64_t uint8_tuint16_t uint32_t uint64_t float double char16_t

matlabdataArrayFactory

1-13

matlabdataString

stdcomplexltdoublegt

stdcomplexltfloatgt

stdcomplexltint8_tgt

stdcomplexltuint8_tgt

stdcomplexltint16_tgt

stdcomplexltuint16_tgt

stdcomplexltint32_tgt

stdcomplexltuint32_tgt

stdcomplexltint64_tgt

stdcomplexltuint64_tgt

matlabdataMATLABString

ArrayDimensionsdims

Dimensions for the array

ItType begin

ItType end

Start and end of the user supplied data The data type isdetermined by the value_type of the iterator

const T constbegin

const T const end

Start and end of the user supplied data specified as C-stylepointer Supports all primitive types complex types andstring types

stdinitializer_listltTgt

Initializer list containing the data

matlabOutOfMemoryException

The array could not be allocated

createScalartemplate lttypename TgtTypedArrayltTgt createScalar(const T val)

TypedArrayltStringgt createScalar(const String val)

TypedArrayltStringgt createScalar(const stdstring val)

Creates a scalar TypedArrayltTgt with the given value This method supports arithmetictypes complex types and string types

const T val Value to be inserted into the scalar If valis 7-bit ASCII data then the methodconverts it to UTF16

const String valconst stdstring val

1 API Reference

1-14

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory

Create a vector containing 2 scalar values stdvectorltmatlabdataArraygt args( factorycreateScalarltint16_tgt(100) factorycreateScalarltint16_tgt(60)) return 0

ldquoCall Function with Single Returned Argumentrdquo

createCellArrayCellArrayltArraygt createCellArray(ArrayDimensions dims)

template lttypename TargsgtCellArrayltArraygt createCellArray(ArrayDimensions dims Targs data)

Creates a CellArray with the specified data Data is specified in column major order

Targs Variadic template of

bull arithmetic typebull complex typebull matlabdataStringbull stdstringbull matlabdataArray

matlabdataArrayFactory

1-15

ArrayDimensionsdims

Dimensions of the cell array

Targs data Elements to be inserted into the cell array specified as aprimitive complex type string or Array

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f CellArray myArray = fcreateCellArray( 12 fcreateCharArray(MATLAB Cell Array) fcreateArrayltdoublegt( 22 12 22 32 42 ))

return 0

createCharArrayCharArray createCharArray(String str)

CharArray createCharArray(stdstring str)

Creates a 1xn CharArray from the specified input where n is the string length

matlabdataString str

Data to be filled into the array

stdstring str

matlabOutOfMemoryException

The array could not be allocated

1 API Reference

1-16

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) return 0

createStructArrayStructArray createStructArray(ArrayDimensions dims stdvectorltstdstringgt fieldNames)

Creates a StructArray with the given dimensions and field names

ArrayDimensions dims Dimensions for the arraystdvectorltstdstringgtfieldNames

Vector of the field names for the structure

matlabOutOfMemoryException

The array could not be allocated

DuplicateFieldNameInStructArrayException

Duplicate field names specified

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f

Create StructArray equivalent to MATLAB structure s s = struct(loc east west data [1 2 3] [4 5 6 7 8]) StructArray S = fcreateStructArray( 12 loc data ) S[0][loc] = fcreateCharArray(east) S[0][data] = fcreateArrayltuint8_tgt( 1 3 1 2 3 )

matlabdataArrayFactory

1-17

S[1][loc] = fcreateCharArray(west) S[1][data] = fcreateArrayltdoublegt( 1 5 4 5 6 7 8 )

Access the value defined by the MATLAB statement s(1)data ReferenceltArraygt val = S[0][data] return 0

createEnumArrayEnumArray createEnumArray(ArrayDimensions dims stdstring className stdvectorltstdstringgt enums)

EnumArray createEnumArray(ArrayDimensions dims stdstring className)

Creates an EnumArray of type className If specified the array is initialized with thelist of enumeration names

ArrayDimensionsdims

Dimensions for the array

stdstringclassName

Class name of the enumeration array

stdvectorltstdstringgt enums

List of the enumeration names

matlabOutOfMemoryException

The array could not be allocated

MustSpecifyClassNameException

Class name not specified

WrongNumberOfEnumsSuppliedException

The wrong number of enumerations provided

include MatlabDataArrayhppinclude ltvectorgt

1 API Reference

1-18

int main() using namespace matlabdata ArrayFactory f auto blue = fcreateEnumArray( 11 TextColor Blue )

Create an argument vector stdvectorltArraygt args( fcreateCharArray(My text) stdmove(blue) )

return 0

createSparseArraytemplate lttypename TgtSparseArrayltTgt createSparseArray(ArrayDimensions dims size_t nnz buffer_ptr_tltTgt data buffer_ptr_tltsize_tgt rows buffer_ptr_tltsize_tgt cols)

Creates a SparseArrayltTgt with rows-by-cols dimensions Only two dimensions areallowed for sparse arrays The buffer is not copied and the array takes ownership

T Element types specified as double bool orstdcomplexltdoublegt

ArrayDimensionsdims

Dimensions for the array

size_t nnz Number of nonzero elementsbuffer_ptr_tltTgtdata

Buffer containing the nonzero elements

buffer_ptr_tltsize_tgt rows

Buffer containing the row value for each element

buffer_ptr_tltsize_tgt cols

Buffer containing the column value for each element

matlabdataArrayFactory

1-19

matlabOutOfMemoryException

The array could not be allocated

InvalidDimensionsInSparseArrayException

More than two dimensions are specified

include MatlabDataArrayhpp

int main() stdvectorltdoublegt data = 35 1298 2176 stdvectorltsize_tgt rows = 001 stdvectorltsize_tgt cols = 048 size_t nnz = 3

matlabdataArrayFactory factory auto data_p = factorycreateBufferltdoublegt(nnz) auto rows_p = factorycreateBufferltsize_tgt(nnz) auto cols_p = factorycreateBufferltsize_tgt(nnz)

double dataPtr = data_pget() size_t rowsPtr = rows_pget() size_t colsPtr = cols_pget() stdfor_each(databegin() dataend() [amp](const doubleamp e) (dataPtr++) = e ) stdfor_each(rowsbegin() rowsend() [amp](const size_tamp e) (rowsPtr++) = e ) stdfor_each(colsbegin() colsend() [amp](const size_tamp e) (colsPtr++) = e )

matlabdataSparseArrayltdoublegt arr = factorycreateSparseArrayltdoublegt( 29 nnz stdmove(data_p) stdmove(rows_p) stdmove(cols_p)) return 0

createEmptyArrayArray createEmptyArray()

Creates an empty Array containing no elements

Array Empty array

1 API Reference

1-20

matlabOutOfMemoryException

The array could not be allocated

createBuffertemplate lttypename Tgtbuffer_ptr_tltTgt createBuffer(size_t numberOfElements)

Creates a buffer which can be passed into createArrayFromBuffer No data copies aremade when creating an array from a buffer Data must be in column major order

T Primitive types

size_t numberOfElements Number of elements not the actualbuffer size

buffer_ptr_tltTgt Unique_ptr containing the buffer

matlabOutOfMemoryException

The array could not be allocated

createArrayFromBuffertemplate lttypename TgtTypedArrayltTgt createArrayFromBuffer(ArrayDimensions dims buffer_ptr_tltTgt buffer)

Creates a TypedArrayltTgt using the given buffer

T Primitive types

ArrayDimensions dims Dimensions for the arraybuffer_ptr_tltTgt buffer Buffer containing the data The buffer is not

copied The TypedArrayltTgt object takesownership of the buffer Data must be in columnmajor order

matlabdataArrayFactory

1-21

matlabOutOfMemoryException

The array could not be allocated

See Also

Introduced in R2017b

1 API Reference

1-22

matlabdataReferenceltArraygtC++ class to get reference to Array

DescriptionUse the ReferenceltArraygt class to get a reference to an Array element of a containerobject such as a MATLAB structure or cell array The class is a base class for allreference types that refer to arrays and provides basic array information ArrayRef isdefined as

using ArrayRef = ReferenceltArraygt

Class DetailsNamespace matlabdataInclude ArrayReferenceExthpp

Member Functionsbull ldquogetTyperdquo on page 1-23bull ldquogetDimensionsrdquo on page 1-24bull ldquogetNumberOfElementsrdquo on page 1-24bull ldquoisEmptyrdquo on page 1-24

getTypeArrayType getType() const

ArrayType Type of the array

NotEnoughIndicesProvidedException

Not enough indices provided

matlabdataReferenceltArraygt

1-23

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

InvalidArrayTypeException

Array type not recognized

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Array dimensions vector

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

getNumberOfElementssize_t getNumberOfElements() const

size_t Number of elements in array

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

isEmptybool isEmpty() const

bool Returns true if array is empty otherwise returns false

NotEnoughIndicesProvidedException

Not enough indices provided

1 API Reference

1-24

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-25bull ldquogetWritableElementsrdquo on page 1-25

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are const

const ReferenceltArraygtampref

ReferenceltArraygt

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are non-const

ReferenceltArraygtamp ref ReferenceltArraygt

matlabdataReferenceltArraygt

1-25

RangeltTypedIterator Tgt Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayType

Introduced in R2017b

1 API Reference

1-26

matlabdataArrayTypeC++ array type enumeration class

DescriptionUse ArrayType objects to identify the data type and other attributes of a MATLABarray

Class DetailsNamespace matlabdataInclude ArrayTypehpp

Enumerationenum class ArrayType UNKNOWN LOGICAL CHAR DOUBLE SINGLE INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 COMPLEX_DOUBLE COMPLEX_SINGLE COMPLEX_INT8 COMPLEX_UINT8 COMPLEX_INT16 COMPLEX_UINT16 COMPLEX_INT32 COMPLEX_UINT32

matlabdataArrayType

1-27

COMPLEX_INT64 COMPLEX_UINT64 CELL STRUCT OBJECT VALUE_OBJECT HANDLE_OBJECT_REF ENUM SPARSE_LOGICAL SPARSE_DOUBLE SPARSE_COMPLEX_DOUBLE MATLAB_STRING

C++ Data Type ConversionMATLAB ArrayType Value C++ Type DescriptionDOUBLE double double-precision (64-bit)

floating-point numberSINGLE float single-precision (32-bit)

floating-point numberINT8 int8_t signed 8-bit integerUINT8 uint8_t unsigned 8-bit integerINT16 int16_t signed 16-bit integerUINT16 uint16_t unsigned 16-bit integerINT32 int32_t signed 32-bit integerUINT32 uint32_t unsigned 32-bit integerINT64 int64_t signed 64-bit integerUINT64 uint64_t unsigned 64-bit integerCHAR char16_t 16-bit characterLOGICAL bool logicalCOMPLEX_DOUBLE stdcomplexltdoublegt complex double-precision

(64-bit) floating-pointnumber

1 API Reference

1-28

MATLAB ArrayType Value C++ Type DescriptionCOMPLEX_SINGLE stdcomplexltfloatgt complex single precision

(32-bit) floating-pointnumber

COMPLEX_INT8 stdcomplexltint8_tgt complex signed 8-bitinteger

COMPLEX_UINT8 stdcomplexltuint8_tgt complex unsigned 8-bitinteger

COMPLEX_INT16 stdcomplexltint16_tgt complex signed 16-bitinteger

COMPLEX_UINT16 stdcomplexltuint16_tgt complex unsigned 16-bitinteger

COMPLEX_INT32 stdcomplexltint32_tgt complex signed 32-bitinteger

COMPLEX_UINT32 stdcomplexltuint32_tgt complex unsigned 32-bitinteger

COMPLEX_INT64 stdcomplexltint64_tgt complex signed 64-bitinteger

COMPLEX_UINT64 stdcomplexltuint64_tgt complex unsigned 64-bitinteger

CELL matlabdataArray Array containing otherArrays

STRUCT matlabdataStruct Array with named fieldsthat can contain data ofvarying types and sizes

OBJECT matlabdataObject MATLAB objectVALUE_OBJECT matlabdataObject MATLAB value objectHANDLE_OBJECT_REF matlabdataObject Reference to an existing

handle object in MATLABENUM matlabdataEnumerat

ionArray of enumerationvalues

SPARSE_LOGICAL bool Sparse array of logicalSPARSE_DOUBLE double Sparse array of double

matlabdataArrayType

1-29

MATLAB ArrayType Value C++ Type DescriptionSPARSE_COMPLEX_DOUBLE stdcomplexltdoublegt Sparse array of complex

doubleMATLAB_STRING matlabdataMATLABSt

ringMATLAB string

See AlsoArrayVisitors

Introduced in R2017b

1 API Reference

1-30

matlabdataArrayVisitorsFunctions for defining visitor pattern

DetailsNamespace matlabdataInclude ArrayVisitorshpp

Functionsbull ldquoapply_visitorrdquo on page 1-31bull ldquoapply_visitor_refrdquo on page 1-31

apply_visitorauto apply_visitor(Array a V visitor)

TBD

TBD

InvalidArrayTypeException

apply_visitor_refauto apply_visitor_ref(const ArrayRefamp a V visitor)

Apply functor V to Array a

Result of V

matlabdataArrayVisitors

1-31

InvalidArrayTypeException

See Also

Introduced in R2017b

1 API Reference

1-32

matlabdataCellArrayC++ class to access MATLAB cell arrays

DescriptionA CellArray is a TypedArray with Array as the element type Use CellArray objectsto access MATLAB cell arrays To create a CellArray call createCellArrayCellArray is defined as

using CellArray = TypedArrayltArraygt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

ExamplesCreate Cell Array

Create a cell array with two elements

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CellArray cellArray1 = factorycreateCellArray( 12 factorycreateCharArray(MATLAB Cell Array) factorycreateArrayltdoublegt( 22 12 22 32 42 ))

matlabdataCellArray

1-33

return 0

See AlsocreateCellArray

Introduced in R2017b

1 API Reference

1-34

matlabdataCharArrayC++ class to access MATLAB character arrays

DescriptionUse CharArray objects to work with MATLAB character arrays To create a CharArraycall createCharArray

Class DetailsNamespace matlabdataBase class TypedArrayltchar16_tgtInclude CharArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-35bull ldquoCopy Assignment Operatorsrdquo on page 1-36bull ldquoMove Constructorsrdquo on page 1-37bull ldquoMove Assignment Operatorsrdquo on page 1-37

Copy Constructors

CharArray(const CharArrayamp rhs)

CharArray(const Arrayamp rhs)

Creates a shared data copy of a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

matlabdataCharArray

1-35

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray B(A) return 0

createCharArray on page 1-16

Copy Assignment OperatorsCharArrayamp operator=(const CharArrayamp rhs)

CharArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray C = factorycreateCharArray()

1 API Reference

1-36

Arrays A and C refer to the same data C = A

return 0

Move Constructors

CharArray(CharArrayampamp rhs)

CharArray(Arrayampamp rhs)

Moves contents of a CharArray object to a new instance

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move constructor - Creates B copies data from A A not valid CharArray B(stdmove(A))

return 0

Move Assignment Operators

CharArrayamp operator=(CharArrayampamp rhs)

CharArrayamp operator=(Arrayampamp rhs)

matlabdataCharArray

1-37

Assigns the input to this CharArray object

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move assignment - Data from A moved to C A no longer valid CharArray C = factorycreateCharArray() C = stdmove(A)

return 0

Member Functionsbull ldquotoUTF16rdquo on page 1-38bull ldquotoAsciirdquo on page 1-39

toUTF16String toUTF16() const

matlabdataString Contents of CharArray as matlabdataString

None

1 API Reference

1-38

toAsciistdstring toAscii() const

stdstring Contents of CharArray as ASCII string

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f auto arr = fcreateCharArray(helloworld) stdstring s = arrtoAscii()

return 0

ldquoEvaluate Mathematical Function in MATLABrdquo

See AlsoldquocreateCharArrayrdquo on page 1-16 | TypedArray | matlabdataString

Introduced in R2017b

matlabdataCharArray

1-39

matlabdataReferenceltCharArraygtC++ class to get reference to CharArray

DescriptionThe CharArrayExt class extends the APIs available to a reference to a CharArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquotoUTF16rdquo on page 1-40bull ldquotoAsciirdquo on page 1-40

toUTF16String toUTF16() const

matlabdataString Contents of reference to CharArray as a utf16 string

None

toAsciistdstring toAscii() const

stdstring Contents of reference to CharArray asmatlabdataString

1 API Reference

1-40

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

See AlsoCharArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltCharArraygt

1-41

matlabdataEnumArrayC++ class to access MATLAB enumeration arrays

DescriptionUse EnumArray objects to access enumeration arrays To create an EnumArray callcreateEnumArray

Class DetailsNamespace matlabdataBase class TypedArrayltEnumerationgtInclude EnumArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-42bull ldquoCopy Assignment Operatorsrdquo on page 1-43bull ldquoMove Constructorsrdquo on page 1-43bull ldquoMove Assignment Operatorsrdquo on page 1-43

Copy Constructors

EnumArray(const EnumArrayamp rhs)

EnumArray(const Arrayamp rhs)

Creates a shared data copy of an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as EnumArray object

1 API Reference

1-42

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Copy Assignment OperatorsEnumArrayamp operator=(const EnumArrayamp rhs)

EnumArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move ConstructorsEnumArray(EnumArrayampamp rhs)

EnumArray(Arrayampamp rhs)

Moves contents of an EnumArray object to a new instance

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move Assignment OperatorsEnumArrayamp operator=(EnumArrayampamp rhs)

matlabdataEnumArray

1-43

EnumArrayamp operator=(Arrayampamp rhs)

Assigns the input to this EnumArray object

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Member Functions

getClassNamestdstring getClassName() const

Return class name for this EnumArray

stdstring The class name

None

See AlsoldquocreateEnumArrayrdquo on page 1-18 | TypedArray

Introduced in R2017b

1 API Reference

1-44

matlabdataReferenceltEnumArraygtC++ class to get reference to EnumArray

DescriptionThe EnumArrayExt class extends the APIs available to a reference to an EnumArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functions

getClassNamestdstring getClassName() const

Return class name for this reference to an EnumArray object

stdstring Class name

None

See AlsoEnumArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltEnumArraygt

1-45

matlabdataEnumerationElement type for MATLAB enumeration arrays

DescriptionEnumeration is the element type for an EnumArray object

Class DetailsNamespace matlabdataInclude Enumerationhpp

See AlsoEnumArray

TopicsldquoMATLAB Data API Typesrdquo

Introduced in R2017b

1 API Reference

1-46

matlabExceptionC++ base class for exceptions

DescriptionAll MATLAB C++ exceptions can be caught as matlabException

Class DetailsNamespace matlabInclude Exceptionhpp

See Also

TopicsldquoMATLAB Data API Exceptionsrdquo

Introduced in R2017b

matlabException

1-47

matlabdataForwardIteratorltTgtTemplated C++ class to provide forward iterator support for StructArray field names

DescriptionUse ForwardIterator objects to access a range of field name elements in aStructArray

Class DetailsNamespace matlabdataInclude ForwardIteratorhpp

Template ParametersT matlabdataMATLABFieldIdentifier

Constructorsbull ldquoCopy Constructorsrdquo on page 1-48bull ldquoCopy Assignment Operatorsrdquo on page 1-49

Copy Constructors

ForwardIterator(const ForwardIteratorltTgtamp rhs)

Creates a shared data copy of a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to copy

ForwardIterator New instance

1 API Reference

1-48

None

Copy Assignment Operators

ForwardIteratorltTgtamp operator=(const ForwardIteratorltTgtamp rhs)

Assigns a shared data copy to a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to assign

ForwardIteratorltTgt Updated instance

None

Other Operatorsbull ldquooperator++rdquo on page 1-49bull ldquooperator--rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperatorrdquo on page 1-51bull ldquooperator-gtrdquo on page 1-51bull ldquooperator[]rdquo on page 1-51

operator++ForwardIteratorltTgtamp operator++()

Pre-increment operator

ForwardIteratorltTgtamp Reference to updated value

matlabdataForwardIteratorltTgt

1-49

None

operator--ForwardIteratorltTgt operator--(int)

Post-increment operator

ForwardIteratorltTgt New object

None

operator=bool operator==(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if the iterators point to the same elementOtherwise returns false

None

operator=bool operator=(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if this iterator points to a differentelement Otherwise returns false

None

1 API Reference

1-50

operatorreference operator() const

reference Shared copy of element that iterator points to specifiedas

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataForwardIteratorltTgt

1-51

See AlsoMATLABFieldIdentifier | StructArray

Introduced in R2017b

1 API Reference

1-52

matlabdataGetArrayTypeC++ struct TBD

DescriptionUse GetArrayType objects to TBD

Class DetailsNamespace matlabdataInclude GetArrayTypehpp

See Also

Introduced in R2017b

matlabdataGetArrayType

1-53

matlabdataGetReturnTypeC++ struct TBD

DescriptionUse GetReturnType to convert a template argument to the appropriate templateargument when creating a TypedArray

Class DetailsNamespace matlabdataInclude GetReturnTypehpp

See Also

Introduced in R2017b

1 API Reference

1-54

matlabdataMATLABFieldIdentifierC++ class used to identify field names in MATLAB struct array

Description

Class DetailsNamespace matlabdataInclude MATLABFieldIdentifierhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-55bull ldquoConstructorrdquo on page 1-55bull ldquoDestructorrdquo on page 1-56bull ldquoCopy Constructorsrdquo on page 1-56bull ldquoCopy Assignment Operatorsrdquo on page 1-56bull ldquoMove Constructorsrdquo on page 1-57bull ldquoMove Assignment Operatorsrdquo on page 1-57

Default ConstructorMATLABFieldIdentifier()

Construct an empty MATLABFieldIdentifier

None

ConstructorMATLABFieldIdentifier(stdstring str)

matlabdataMATLABFieldIdentifier

1-55

Construct a MATLABFieldIdentifier from stdstring

stdstring str String that contains the field name

Destructor

~MATLABFieldIdentifier()

Destroy a MATLABFieldIdentifier

None

Copy Constructors

MATLABFieldIdentifier(const MATLABFieldIdentifieramp rhs)

Creates a shared data copy of a MATLABFieldIdentifier object

constMATLABFieldIdentifieramprhs

Value to copy

None

Copy Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifier constamp rhs)

Assigns a shared data copy to a MATLABFieldIdentifier object

MATLABFieldIdentifierconstamp rhs

Value to move

1 API Reference

1-56

MATLABFieldIdentifieramp Updated instance

None

Move Constructors

MATLABFieldIdentifier(MATLABFieldIdentifierampamp rhs)

Moves contents a MATLABFieldIdentifier object to a new instance

MATLABFieldIdentifierampamprhs

Value to move

None

Move Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifierampamp rhs)

MATLABFieldIdentifierampamprhs

Value to move

MATLABFieldIdentifieramp Updated instance

None

Destructor~MATLABFieldIdentifier()

Description

Destroy a MATLABFieldIdentifier

matlabdataMATLABFieldIdentifier

1-57

Other Operators

operator stdstringoperator stdstring() const

stdstring Representation of the MATLABFieldIdentifier object

None

Free Functions

operator==bool operator==(const MATLABFieldIdentifieramp rhs) const

Check if two MATLABFieldIdentifier objects are identical

constMATLABFieldIdentifieramprhs

Value to be compared

bool Returns true if the objects are identical Otherwisereturns false

None

See AlsoForwardIterator | StructArray

Introduced in R2017b

1 API Reference

1-58

matlabdataMATLABStringElement type for MATLAB string arrays

DescriptionMATLABString is defined as

using MATLABString = OptionalltStringgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataString

Introduced in R2017b

matlabdataMATLABString

1-59

matlabdataReferenceltMATLABStringgtC++ class to get reference to element of StringArray

DescriptionA ReferenceltMATLABStringgt object is created when using operator[] into anStringArray or dereferenceing a String arrary iterator

Class DetailsNamespace matlabdataInclude MATLABStringReferenceExthpp

Cast

String()operator String() const

matlabdataString Element of a MATLABString array converted toString

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

stdruntime_error Array element does not have a value

1 API Reference

1-60

Member Functionsbull ldquoboolrdquo on page 1-61bull ldquohas_valuerdquo on page 1-61

booloperator bool() const

Check whether string contains a value

operator True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

has_valuebool has_value() const

Check whether string contains a value

bool True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

matlabdataReferenceltMATLABStringgt

1-61

See Also

Introduced in R2017b

1 API Reference

1-62

matlabdataArrayC++ base class for all array types

DescriptionUse Array objects to represent single and multi-dimensional arrays The Array classprovides methods for users to be able to query generic information about all arrays suchas dimensions and type and has methods to create deep copies and shared data copiesUse ArrayFactory methods to construct Arrays Once an Array has been constructedit can be moved or cloned (deep-copied) or a shared-data copy can be created Arrayssupport copy-on-write semantics

Class DetailsNamespace matlabdataInclude MDArrayhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-63bull ldquoCopy Constructorsrdquo on page 1-64bull ldquoCopy Assignment Operatorsrdquo on page 1-64bull ldquoMove Constructorsrdquo on page 1-64bull ldquoMove Assignment Operatorsrdquo on page 1-65

Default Constructor

Array()

None

matlabdataArray

1-63

Copy Constructors

Array(const Arrayamp rhs)

Creates a shared data copy of an Array object

const Arrayamp rhs Value to copy

None

Copy Assignment Operators

Arrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an Array object

const Arrayamp rhsrhs Value to copy

Arrayamp Updated instance

None

Move Constructors

Array(Arrayampamp rhs)

Moves contents of an Array object to a new instance

Arrayampamp rhs Value to move

None

1 API Reference

1-64

Move Assignment Operators

Arrayamp operator=(Arrayampamp rhs)

Assigns the input to this Array object

Arrayampamp rhs Value to move

Arrayamp Updated instance

None

Destructorvirtual ~Array()

Indexing Operators

operator[]ArrayElementRefltfalsegt operator[](size_t idx)

ArrayElementReflttruegt operator[](size_t idx) const

Enables [] indexing on const and non-const arrays Indexing is 0-based

size_t idx First array index

ArrayElementRefltfalsegt Temporary object containing the index specified Thereturn value allows the element of the array to bemodified or retrieved

matlabdataArray

1-65

ArrayElementReflttruegt Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Member Functionsbull ldquogetTyperdquo on page 1-66bull ldquogetDimensionsrdquo on page 1-66bull ldquogetNumberOfElementsrdquo on page 1-66bull ldquoisEmptyrdquo on page 1-67

getTypeArrayType getType() const

ArrayType Array type

None

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Vector of each dimension in the array

None

getNumberOfElementssize_t getNumberOfElements() const

size_t The number of elements in the array

1 API Reference

1-66

None

isEmptybool isEmpty() const

bool True if array is empty False if array is not empty

None

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-67bull ldquogetWritableElementsrdquo on page 1-67

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const Arrayamp arr)

Get a range containing the elements of the Array Iterators contained in the range areconst

const Arrayamp arr Array

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(Arrayamp arr)

matlabdataArray

1-67

Get a range containing the elements of the Array Iterators contained in the range arenon-const

Arrayamp arr Array

RangeltTypedIterator Tgt Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayFactory

Introduced in R2017b

1 API Reference

1-68

matlabdataObjectElement type for MATLAB object arrays

DescriptionObject is the element type for an ObjectArray

Class DetailsNamespace matlabdataInclude Objecthpp

See AlsoObjectArray

Introduced in R2017b

matlabdataObject

1-69

matlabdataObjectArrayC++ class to access MATLAB object arrays

DescriptionUse ObjectArray objects to access MATLAB object arrays You do not create anObjectArray only MATLAB functions create ObjectArrays You can pass anObjectArray to a MATLAB function

ObjectArray is defined as

using ObjectArray = TypedArrayltObjectgt

Class DetailsNamespace matlabdataInclude ObjectArrayhpp

See AlsoObject

Introduced in R2017b

1 API Reference

1-70

matlabdataOptionalltTgtTemplated C++ class representing optional values

DescriptionUse Optional objects to represent values that might or might not exist

Class DetailsNamespace matlabdataInclude Optionalhpp

Template ParametersT Array type specified as matlabdataString

Constructorsbull ldquoDefault Constructorsrdquo on page 1-71bull ldquoCopy Constructorsrdquo on page 1-71bull ldquoCopy Assignment Operatorsrdquo on page 1-72bull ldquoMove Constructorsrdquo on page 1-72bull ldquoMove Assignment Operatorsrdquo on page 1-72

Default Constructors

optional()

Copy Constructors

optional(const optionalamp other)

matlabdataOptionalltTgt

1-71

Creates a shared data copy

const optionalamp other Value to copy

None

Copy Assignment OperatorsoptionalltTgtamp operator=(const optionalltTgtamp other)

Assigns a shared data copy

const optionalltTgtamp other Value to copy

optionalltTgtamp Updated instance

None

Move Constructorsoptional(optionalampamp other)

optional(Tampamp value)

Moves contents of an Optional object to a new instance

optionalampamp other Value to moveTampamp value Value of type T to move

None

Move Assignment OperatorsoptionalltTgtamp operator=(optionalltTgtampamp other)

1 API Reference

1-72

optionalltTgtamp operator=(Tampamp value)

Assigns the input to this instance

optionalltTgtampamp other

Tampamp value

Value to move

optionalltTgtamp Updated instance

None

Other Operatorsbull ldquooperator=rdquo on page 1-73bull ldquooperator-gtrdquo on page 1-74bull ldquooperatorrdquo on page 1-74bull ldquooperator Trdquo on page 1-74

operator=optionalltTgtamp operator=(nullopt_t)

optionalltTgtamp operator=(const optionalltTgtamp other)

optionalltTgtamp operator=(optionalltTgtampamp other)

optionalltTgtamp operator=(Tampamp value)

optionalltTgtamp operator=(const Tamp value)

Assignment operators

optionalltTgtamp Updated instance

None

matlabdataOptionalltTgt

1-73

operator-gtconst T operator-gt() const

T operator-gt()

const T

T

Pointer to the element

stdruntime_error Optional object does not contain a value

operatorconst Tamp operator() const

Tamp operator()

const Tamp

Tamp

Reference to the element

stdruntime_error Optional object does not contain a value

operator Toperator T() const

Cast optionalltTgt value to T

operator Value contained in optionalltTgt if it exists

stdruntime_error There is no value

1 API Reference

1-74

Member Functionsbull ldquoboolrdquo on page 1-75bull ldquohas_valuerdquo on page 1-75bull ldquoswaprdquo on page 1-75bull ldquoresetrdquo on page 1-76

boolexplicit operator bool() const

Check whether object contains a value

operator True if object contains a value

None

has_valuebool has_value() const

Check whether object contains a value

bool True if object contains a value

None

swapvoid swap(optional ampother)

Swap value of this optional instance with value contained in the parameter

optional ampother Value to swap

matlabdataOptionalltTgt

1-75

None

resetvoid reset()

Reset optional value to missing

None

See Also

Introduced in R2017b

1 API Reference

1-76

matlabdataRangeltItTypeElemTypegtTemplated C++ class to provide range-based operation support

DescriptionRange objects wrap begin and end functions to enable range-based operations

Class DetailsNamespace matlabdataInclude Rangehpp

Template ParametersIteratorType Iterator typeElementType Element type

Constructorsbull ldquoConstructorrdquo on page 1-77bull ldquoMove Constructorsrdquo on page 1-78bull ldquoMove Assignment Operatorsrdquo on page 1-78

Constructor

Range(IteratorTypeltElementTypegt begin IteratorTypeltElementTypegtend)

Creates a Range object

matlabdataRangeltItTypeElemTypegt

1-77

IteratorTypeltElementTypegt begin

IteratorTypeltElementTypegt end

First and last elements of range

Range New instance

None

Move Constructors

Range(Rangeampamp rhs)

Moves contents of a Range object to a new instance

Rangeampamp rhs Range to move

Range New instance

None

Move Assignment Operators

Rangeamp operator=(Rangeampamp rhs)

Assigns the input to this Range object

Rangeampamp rhs Range to move

Rangeamp Updated instance

None

1 API Reference

1-78

beginIteratorTypeltElementTypegtamp begin()

ReturnsIteratorTypeltElementTypegtamp

First element in range

None

endIteratorTypeltElementTypegtamp end()

ReturnsIteratorTypeltElementTypegtamp

End of range

None

See Also

Introduced in R2017b

matlabdataRangeltItTypeElemTypegt

1-79

matlabdataReferenceltTgtTemplated C++ class to get references to Array elements

DescriptionA Reference object is a reference to an element of an Array without making a copy AReference is

bull Not a shared copybull Valid as long as the array that contains the reference is validbull Not thread-safe

Class DetailsNamespace matlabdataInclude Referencehpp

Template ParametersT Type of element referred to specified as

bull Arraybull Structbull Enumerationbull MATLABStringbull All stdcomplex types

Constructorsbull ldquoCopy Constructorrdquo on page 1-81bull ldquoCopy Assignment Operatorsrdquo on page 1-81bull ldquoMove Assignment Operatorsrdquo on page 1-81

1 API Reference

1-80

bull ldquoMove Constructorsrdquo on page 1-81

Copy ConstructorReference(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

Copy Assignment OperatorsReferenceltTgtamp operator=(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

ReferenceltTgtamp Updated instance

Move Assignment OperatorsReferenceltTgtamp operator=(ReferenceltTgtampamp rhs)

ReferenceltTgtampamp rhs Value to move

ReferenceltTgtamp Updated instance

None

Move ConstructorsReference(ReferenceltTgtampamp rhs)

Moves contents of a Reference object to a new instance

ReferenceltTgtampamp rhs Value to move

None

matlabdataReferenceltTgt

1-81

Other Operatorsbull ldquooperator=rdquo on page 1-82bull ldquooperatorltltrdquo on page 1-82bull ldquooperator T()rdquo on page 1-83bull ldquooperator stdstring()rdquo on page 1-83

operator=ReferenceltTgtamp operator=(T rhs)

ReferenceltTgtamp operator=(stdstring rhs)

ReferenceltTgtamp operator=(String rhs)

T rhs Value to assign The array being indexed must be non-const

stdstring rhs String to assign The array must be non-const andallow strings to be assigned

String rhs String to assign to StringArray The array beingindexed must be non-const

ReferenceltTgtamp Updated instance

None

operatorltlt

stdostreamamp operator ltlt(stdostreamamp os ReferenceltTgt constamp rhs)

stdostreamamp os ReferenceltTgt constamp rhs

stdostreamamp

1 API Reference

1-82

operator T()operator T() const

Cast to element from the array

T Shared copy of element from the array

None

operator stdstring()operator stdstring() const

Cast to stdstring from the array Makes a copy of the stdstring Only valid fortypes that can be cast to a stdstring

stdstring The string

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

stdruntime_error MATLABString is missing

Free Functions

operator==inline bool operator ==(ReferenceltMATLABStringgt constamp lhsstdstring constamp rhs)

inline bool operator ==(stdstring constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhs Stringconstamp rhs)

matlabdataReferenceltTgt

1-83

inline bool operator ==(String constamp lhs ReferenceltMATLABStringgtconstamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsMATLABString constamp rhs)

inline bool operator ==(MATLABString constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsReferenceltMATLABStringgt constamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhs Tconstamp rhs)

templatelttypename Tgt bool operator ==(T constamp lhs ReferenceltTgtconstamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhsReferenceltTgt constamp rhs)

ReferenceltMATLABStringgtconstamp lhs

stdstring constamp rhs Values tocompare

stdstring constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

String constamp rhs

String constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

MATLABString constamp rhs

MATLABString constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

ReferenceltMATLABStringgtconstamp rhs

ReferenceltTgt constamp lhs T constamp rhsT constamp lhs ReferenceltTgt constamp rhsReferenceltTgt constamp lhs ReferenceltTgt constamp rhs

1 API Reference

1-84

bool Returns true if values are equal

stdruntime_error Cannot compare argument to MATLABString

See Also

TopicsldquoAccess C++ Data Array Container Elementsrdquo

Introduced in R2017b

matlabdataReferenceltTgt

1-85

matlabdataSparseArrayltTgtTemplated C++ class to access data in MATLAB sparse arrays

DescriptionUse SparseArray objects to work with sparse MATLAB arrays To create aSparseArray call createSparseArray

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude SparseArrayhpp

Template ParametersT Type of element referred to specified as

bull boolbull doublebull stdcomplexltdoublegt

Constructorsbull ldquoCopy Constructorsrdquo on page 1-86bull ldquoCopy Assignment Operatorsrdquo on page 1-87bull ldquoMove Constructorsrdquo on page 1-87bull ldquoMove Assignment Operatorsrdquo on page 1-88

Copy Constructors

SparseArray(const SparseArrayltTgtamp rhs)

1 API Reference

1-86

SparseArray(const Arrayamp rhs)

Creates a shared data copy of a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array ofArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Copy Assignment OperatorsSparseArrayamp operator=(const SparseArrayltTgtamp rhs)

SparseArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

Move ConstructorsSparseArray(SparseArrayampamp rhs)

matlabdataSparseArrayltTgt

1-87

SparseArray(Arrayampamp rhs)

Moves contents a SparseArray object to a new instance

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Move Assignment Operators

SparseArrayamp operator=(SparseArrayltTgtampamp rhs)

SparseArrayamp operator=(Arrayampamp rhs)

Assigns the input to this SparseArray object

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

1 API Reference

1-88

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-89bull ldquoEnd Iteratorsrdquo on page 1-89

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functionsbull ldquogetNumberOfNonZeroElementsrdquo on page 1-90

matlabdataSparseArrayltTgt

1-89

bull ldquogetIndexrdquo on page 1-90

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array

size_t Number of nonzero elements in the array

None

getIndexSparseIndex getIndex(const TypedIteratorltTgtamp it)

SparseIndex getIndex(const TypedIteratorltT constgtamp it)

Returns the row-column coordinates of the nonzero entry that the iterator is pointing to

const TypedIteratorltTgtampit

Iterator pointing to the current entry in the sparsematrix

const TypedIteratorltTconstgtamp it

SparseIndex Row-column coordinates of the nonzero entry that theiterator is pointing to SparseIndex is defined asstdpairltsize_t size_tgt

None

See AlsoArray | createSparseArray

1 API Reference

1-90

Introduced in R2017b

matlabdataSparseArrayltTgt

1-91

matlabdataReferenceltSparseArrayltTgtgtTemplated C++ class to get reference to SparseArray

DescriptionUse the ReferenceltSparseArraygt class to get a reference to a SparseArray elementof a container object such as a MATLAB structure or cell array

Class DetailsNamespace matlabdataInclude SparseArrayRefhpp

Template ParametersT Type of elements in SparseArray specified as bool

double or stdcomplexltdoublegt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-92bull ldquoEnd Interatorsrdquo on page 1-93

Begin Interatorsiterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array Iterates over non-zeroelements of the SparseArray

1 API Reference

1-92

None

End Interators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functions

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array Since sparse arrays only storenonzero elements this method returns the actual array size It is different from arraydimensions that specify the full array size

size_t Number of nonzero elements in the array

None

See Also

Introduced in R2017b

matlabdataReferenceltSparseArrayltTgtgt

1-93

matlabdataStringType representing strings as stdbasic_stringltchar16_tgt

DescriptionThe String class defines the element type of a StringArray String is defined as

using String = stdbasic_stringltchar16_tgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

1 API Reference

1-94

matlabdataStringArrayC++ class to access MATLAB string arrays

DescriptionUse StringArray objects to access MATLAB string arrays StringArray is defined as

using StringArray = TypedArrayltMATLABStringgt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

matlabdataStringArray

1-95

matlabdataStructArrayC++ class to access MATLAB struct arrays

DescriptionUse StructArray objects to work with MATLAB struct arrays To access a field for asingle element in the array use the field name To create a StructArray object callcreateStructArray

Class DetailsNamespace matlabdataBase class TypedArrayltStructgtInclude StructArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-96bull ldquoCopy Assignment Operatorsrdquo on page 1-97bull ldquoMove Constructorsrdquo on page 1-97bull ldquoMove Assignment Operatorsrdquo on page 1-98

Copy Constructors

StructArray(const StructArrayamp rhs)

StructArray(const Arrayamp rhs)

Creates a shared data copy of a StructArray object

const StructArrayamp rhs Value to copy

1 API Reference

1-96

const Arrayamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Copy Assignment Operators

StructArrayamp operator=(const StructArrayamp rhs)

StructArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a StructArray object

const StructArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeSTRUCT object

StructArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Move Constructors

StructArray(StructArrayampamp rhs)

StructArray(Arrayampamp rhs)

Moves contents of a StructArray object to a new instance

StructArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

matlabdataStructArray

1-97

Move Assignment OperatorsStructArrayamp operator=(StructArrayampamp rhs)

Assigns the input to this StructArray object

StructArrayampamp rhs Value to move

StructArrayamp Updated instance

None

Destructor~StructArray()

Description

Free memory for StructArray object

Member Functionsbull ldquogetFieldNamesrdquo on page 1-98bull ldquogetNumberOfFieldsrdquo on page 1-99

getFieldNamesRangeltForwardIterator MatlabFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enable access to allfields in StructArray object

None

1 API Reference

1-98

getNumberOfFieldssize_t getNumberOfFields() const

size_t Number of fields

None

ExamplesCreate StructArray

Suppose that you have the following MATLAB structure

s = struct(loc east west data [1 2 3] [4 5 6 7 8])

Create a variable containing the data for loc east

val = s(1)data

The following C++ code creates these variables

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory

StructArray S = factorycreateStructArray( 12 loc data ) S[0][loc] = factorycreateCharArray(east) S[0][data] = factorycreateArrayltuint8_tgt( 1 3 1 2 3 ) S[1][loc] = factorycreateCharArray(west) S[1][data] = factorycreateArrayltdoublegt( 1 5 4 5 6 7 8 )

ReferenceltArraygt val = S[0][data] return 0

bull ldquoCreate Structure Array and Send to MATLABrdquo

matlabdataStructArray

1-99

See AlsoMATLABFieldIdentifier | Range | createStructArray

TopicsldquoCreate Structure Array and Send to MATLABrdquo

Introduced in R2017b

1 API Reference

1-100

matlabdataReferenceltStructArraygtC++ class to get reference to StructArray

DescriptionThe StructArrayExt class extends the APIs available to a reference to a StructArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquogetFieldNamesrdquo on page 1-101bull ldquogetNumberOfFieldsrdquo on page 1-101

getFieldNamesRangeltForwardIterator MATLABFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enables access to allfields in StructArray object

None

getNumberOfFieldssize_t getNumberOfFields() const

matlabdataReferenceltStructArraygt

1-101

size_t Number of fields

None

See AlsoReferenceltTypedArrayltTgtgt | StructArray

Introduced in R2017b

1 API Reference

1-102

matlabdataStructElement type for MATLAB struct arrays

DescriptionStruct is the element type for a StructArray object

Class DetailsNamespace matlabdataInclude Structhpp

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-103bull ldquoEnd Iteratorsrdquo on page 1-103

Begin Iteratorsconst_iterator begin() const

const_iterator cbegin() const

const_iterator Iterator to beginning of list of fields specified asTypedIteratorltArray constgt

None

End Iteratorsconst_iterator end() const

const_iterator cend() const

matlabdataStruct

1-103

const_iterator Iterator to end of list of fields specified asTypedIteratorltArray constgt

None

Indexing Operators

operator[]Array operator[](stdstring idx) const

Enables [] indexing on a StructArray object Indexing is 0-based

stdstring idx Field name

Array Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in this StructArray

See AlsoldquocreateStructArrayrdquo on page 1-17 | StructArray

Introduced in R2017b

1 API Reference

1-104

matlabdataReferenceltStructgtC++ class to get reference to element of StructArray

DescriptionUse the ReferenceltStructgt class to access an element of a StructArray

Class DetailsNamespace matlabdataInclude StructRefhpp

Indexing Operators

operator[]ReferenceltArraygt operator[](stdstring idx)

Array operator[](stdstring idx) const

Index into the Struct with a field name

stdstring idx Field name

ReferenceltArraygt Reference to Array found at specified fieldArray Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in the struct

matlabdataReferenceltStructgt

1-105

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-106bull ldquoEnd Iteratorsrdquo on page 1-106

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

1 API Reference

1-106

Cast

Struct()operator Struct() const

Create a shared copy of the Struct

Struct Shared copy

None

See Also

Introduced in R2017b

matlabdataReferenceltStructgt

1-107

matlabdataTypedArrayltTgtTemplated C++ class to access array data

DescriptionThe templated TypedArray class provides typesafe APIs to handle all array types(except sparse arrays) inside an array This class defines the following iterator types

using iterator = TypedIteratorltTgt

using const_iterator = TypedIteratorltT constgt

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude TypedArrayhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_t

1 API Reference

1-108

uint64_tchar16_tboolstdcomplexltdoublegtstdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorrdquo on page 1-109bull ldquoCopy Assignment Operatorrdquo on page 1-110bull ldquoMove Constructorrdquo on page 1-110bull ldquoMove Assignment Operatorrdquo on page 1-111

Copy ConstructorTypedArray(const TypedArrayltTgtamp rhs)

TypedArray(const Arrayamp rhs)

Creates a shared data copy of the input

matlabdataTypedArrayltTgt

1-109

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Copy Assignment Operator

TypedArrayltTgtamp operator=(const TypedArrayltTgtamp rhs)

TypedArrayltTgtamp operator=(const Arrayamp rhs)

Assigns a shared data copy of the input to this TypedArrayltTgt

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Move Constructor

TypedArray(TypedArrayltTgtampamp rhs)

TypedArray(Arrayampamp rhs)

Moves contents of the input to a new instance

TypedArrayltTgtampamp rhs Value to be movedArrayampamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input does not match

1 API Reference

1-110

Move Assignment Operator

TypedArrayltTgtamp operator=(TypedArrayltTgtampamp rhs)

TypedArrayltTgtamp operator=(Arrayampamp rhs)

Moves the input to this TypedArrayltTgt object

TypedArrayltTgtampamp rhs Value to move

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Destructorvirtual ~TypedArray()

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-111bull ldquoEnd Iteratorsrdquo on page 1-112

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

matlabdataTypedArrayltTgt

1-111

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

Indexing Operators

operator[]ArrayElementTypedRefltT stdis_constltTgtvaluegt operator[](size_tidx)

ArrayElementTypedRefltT truegt operator[](size_t idx) const

Enables [] indexing on a TypedArray Indexing is 0-based

size_t idx First array index

1 API Reference

1-112

ArrayElementTypedRefltTstdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltTtruegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Suppose that you have a cell array c Assign a value to a ReferenceltArraygt object andcall the member function getType

ReferenceltArraygt r = c[0][0]auto t = c[0][0]getType

Member Functions

releasebuffer_ptr_tltTgt release()

Release the underlying buffer from the Array If the Array is shared a copy of the bufferis made otherwise no copy is made After the buffer is released the array contains noelements

buffer_ptr_tltTgt A unique_ptr with the data pointer

InvalidArrayTypeException

This TypedArray does not support releasing the buffer

matlabdataTypedArrayltTgt

1-113

ExamplesAssign Values to Array Elements

Create an array equivalent to the MATLAB array [1 2 3 4] then replace eachelement of the array with a single value

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory Create an array equivalent to the MATLAB array [1 2 3 4] matlabdataTypedArrayltdoublegt D = factorycreateArrayltdoublegt( 22 1324 ) Change the values for (autoamp elem D) elem = 55 return 0

bull ldquoBring Result of MATLAB Calculation Into C++rdquo

See AlsoArray | ArrayType

TopicsldquoBring Result of MATLAB Calculation Into C++rdquo

Introduced in R2017b

1 API Reference

1-114

matlabdataReferenceltTypedArrayltTgtgtC++ class to get reference to TypedArray

DescriptionThe ReferenceltTypedArrayltTgtgt class extends the APIs available to a reference to anArray It derives from the ReferenceltArraygt class and provides iterators and type-safe indexing ReferenceltTypedArrayltTgtgt is not thread-safe - do not pass referencesto TypedArray objects between threads

TypedArrayRef is defined in TypedArrayRefhpp as

template lttypename Tgtusing TypedArrayRef = ReferenceltTypedArrayltTgtgt

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

ConstructorReference(const ReferenceltArraygtamp rhs)

Description

Create a ReferenceltTypedArrayltTgtgt object from a ReferenceltArraygt object

Parametersconst ReferenceltArraygtamprhs

Value to copy

matlabdataReferenceltTypedArrayltTgtgt

1-115

ThrowsTypeMismatchException Element of Array does not match ltTgt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-116bull ldquoEnd Iteratorsrdquo on page 1-116

Begin Interators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

1 API Reference

1-116

None

Indexing Operators

operator[]ArrayElementTypedRefltarr_elem_type stdis_constltTgtvaluegtoperator[](size_t idx)

ArrayElementTypedRefltarr_elem_type truegt operator[](size_t idx)const

Enables [] indexing on a reference to an Array Indexing is 0-based

size_t idx First array index

ArrayElementTypedRefltarr_elem_typestdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltarr_elem_type truegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

InvalidFieldNameException

Field name is invalid for a struct

Other Operators

operator=ReferenceltTypedArrayltTgtgtamp operator= (TypedArrayltTgt rhs)

matlabdataReferenceltTypedArrayltTgtgt

1-117

Assign a TypedArray to an element of the referenced Array The Array being indexedmust be non-const

TypedArrayltTgt rhs Value to assign

ReferenceltTypedArrayltTgtgtamp

Updated instance

None

See Also

Introduced in R2017b

1 API Reference

1-118

matlabdataTypedIteratorltTgtTemplated C++ class to provide random access iterator

DescriptionTypedIterator is the return type of all begin and end functions that support randomaccess

Class DetailsNamespace matlabdataInclude TypedIteratorhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tchar16_tboolstdcomplexltdoublegt

matlabdataTypedIteratorltTgt

1-119

stdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorsrdquo on page 1-120bull ldquoCopy Assignment Operatorsrdquo on page 1-121bull ldquoMove Constructorsrdquo on page 1-121bull ldquoMove Assignment Operatorsrdquo on page 1-121

Copy Constructors

TypedIterator(const TypedIteratorltTgtamp rhs)

Creates a shared data copy of a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

None

1 API Reference

1-120

Copy Assignment OperatorsTypedIteratorltTgtamp operator=(const TypedIteratorltTgtamp rhs)

Assigns a shared data copy to a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

TypedIteratorltTgtamp Updated instance

None

Move ConstructorsTypedIterator(TypedIteratorltTgt ampamprhs)

Moves contents of a TypedIterator object to a new instance

TypedIteratorltTgtampamp rhs Value to move

None

Move Assignment OperatorsTypedIteratorltTgtamp operator=(TypedIteratorltTgtampamp rhs)

Assigns the input to this TypedIterator object

TypedIteratorltTgtampamp rhs Value to move

TypedIteratorltTgtamp Updated instance

None

matlabdataTypedIteratorltTgt

1-121

Other Operatorsbull ldquooperator++rdquo on page 1-122bull ldquooperator--rdquo on page 1-122bull ldquooperator++rdquo on page 1-123bull ldquooperator--rdquo on page 1-123bull ldquooperator+=rdquo on page 1-123bull ldquooperator-=rdquo on page 1-124bull ldquooperator=rdquo on page 1-124bull ldquooperatorltrdquo on page 1-124bull ldquooperatorgtrdquo on page 1-125bull ldquooperatorlt=rdquo on page 1-125bull ldquooperatorgt=rdquo on page 1-125bull ldquooperator+rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperatorrdquo on page 1-127bull ldquooperator-gtrdquo on page 1-127bull ldquooperator[]rdquo on page 1-127

operator++TypedIteratorltTgtamp operator++()

Pre-increment operator

TypedIteratorltTgtamp Original iterator

None

operator--TypedIteratorltTgtamp operator--()

1 API Reference

1-122

Pre-decrement operator

TypedIteratorltTgtamp Original iterator

None

operator++TypedIteratorltTgt operator++(int)

Post-increment operator

TypedIteratorltTgt Copy of original iterator

None

operator--TypedIteratorltTgt operator--(int)

Post-decrement operator

TypedIteratorltTgt Copy of original iterator

None

operator+=TypedIteratorltTgtamp operator+=(difference_type d)

Addition assignment operator

difference_type d Amount to add specified as stdptrdiff_t

matlabdataTypedIteratorltTgt

1-123

TypedIteratorltTgtamp Updated instance

None

operator-=TypedIteratorltTgtamp operator-=(difference_type d)

Subtraction assignment operator

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgtamp Updated instance

None

operator=bool operator=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if iterators do not point to same element

None

operatorltbool operatorlt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

1 API Reference

1-124

bool Returns true if left-side iterator is less than right-sideiterator

operatorgtbool operatorgt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than right-side iterator

operatorlt=bool operatorlt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is less than or equal toright-side iterator

None

operatorgt=bool operatorgt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than orequal to right-side iterator

None

matlabdataTypedIteratorltTgt

1-125

operator+TypedIteratorltTgt operator+(difference_type d) const

Creates an iterator that is added to this one by the amount passed in

difference_type d Amount to add specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-TypedIteratorltTgt operator-(difference_type d) const

Creates an iterator that is decremented from this one by the amount passed in

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-difference_type operator-(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

difference_type Difference between iterators specified asstdptrdiff_t

None

1 API Reference

1-126

operatorreference operator() const

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataTypedIteratorltTgt

1-127

Free Function

operator==bool operator==(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if both iterators point to same element

None

See Also

Introduced in R2017b

1 API Reference

1-128

matlabdataapply_visitorCall Visitor class on arrays

Descriptionauto apply_visitor(Array a V visitor) dispatch to visitor class operationsbased on array type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersmatlabdataArray a

The matlabdataArray to operate on with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

matlabdataapply_visitor

1-129

matlabdataapply_visitor_refCall Visitor class on array references

Descriptionauto apply_visitor_ref(const ArrayRefamp a V visitor) dispatch to visitorclass operations based on array reference type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersconstmatlabdataArrayRefamp a

A matlabdataArrayRef reference to the array to operateon with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

1 API Reference

1-130

matlabengineMATLABEngineEvaluate MATLAB functions from C++ program

DescriptionThe matlabengineMATLABEngine class uses a MATLAB process as acomputational engine for C++ This class provides an interface between the C++language and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom C++ programs

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Factory MethodsThe matlabengineMATLABEngine class provides methods to start MATLAB and toconnect to a shared MATLAB session synchronously or asynchronously

bull matlabenginestartMATLAB mdash Start MATLAB synchronouslybull matlabenginestartMATLABAsync mdash Start MATLAB asynchronouslybull matlabengineconnectMATLAB mdash Connect to shared MATLAB session

synchronouslybull matlabengineconnectMATLABAsync mdash Connect to shared MATLAB session

asynchronously

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -h

matlabengineMATLABEngine

1-131

bull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup OptionsrdquoFor an example of how to use MATLAB startup options when starting engineapplications see ldquoStart MATLAB with Startup Optionsrdquo

Method Summary

Member Functionsldquofevalrdquo on page 1-133

Evaluate MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-136

Evaluate MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-138 Evaluate MATLAB statement as a string synchronouslyldquoevalAsyncrdquo on page1-139

Evaluate MATLAB statement as a string asynchronously

ldquogetVariablerdquo onpage 1-140

Get variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-141

Get variable from the MATLAB base workspace asynchronously

ldquosetVariablerdquo onpage 1-142

Put variable into the MATLAB base workspace synchronously

ldquosetVariableAsyncrdquoon page 1-142

Put variable into the MATLAB base workspace asynchronously

ldquogetPropertyrdquo onpage 1-143

Get object property value

ldquogetPropertyAsyncrdquoon page 1-144

Get object property value asynchronously

1 API Reference

1-132

ldquosetPropertyrdquo onpage 1-145

Set object property value

ldquosetPropertyAsyncrdquoon page 1-146

Set object property value asynchronously

Member Function Details

fevalstdvectorltmatlabdataArraygt feval(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

ResultType feval(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs )

ResultType feval(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB functions with input arguments synchronously Use feval when youwant to pass arguments from C++ to MATLAB and when you want to return a resultfrom MATLAB to C++

Inputs and outputs can be types defined by the MATLAB Data Array API or can benative C++ types

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

matlabengineMATLABEngine

1-133

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

stdvectorltmatlabdataArraygt

Outputs returned from MATLAB function

matlabdataArray Single output returned from MATLAB functionResultType Output returned from MATLAB function as a user-specified

type Can be a stdtuple if returning multiple arguments

matlabengineMATLABNotAvailableException

The MATLAB session is not available

1 API Reference

1-134

matlabengineMATLABExecutionException

There is a MATLAB runtime error in the function

matlabengineTypeConversionException

The result of a MATLAB function cannot be converted tothe specified type

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

This example passes an array of numeric values to a MATLAB function The codeperforms these steps

bull Creates a matlabdataArray with the dimensions 2-by-3 from a vector ofnumeric values of type double

bull Starts a shared MATLAB sessionbull Passes the data array to the MATLAB sqrt function and returns the result to C++

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabengine

stdvectorltdoublegt cppData 4 8 12 16 20 24

Create a 2-by-3 matlab data array matlabdataArrayFactory factory auto inputArray = factorycreateArray( 2 3 cppDatacbegin() cppDatacend())

Start MATLAB engine stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Pass data array to MATLAB sqrt function And return results auto result = matlabPtr-gtfeval(usqrt inputArray)

When calling feval using native C++ types the input arguments are restricted to scalarvalues For example this code returns the square root of a scalar value

include MatlabEnginehppusing namespace matlabengine

Start MATLAB engine synchronously stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Call sqrt function double result = matlabPtr-gt fevalltdoublegt(usqrt double(27))

matlabengineMATLABEngine

1-135

For functions that return multiple output arguments you can use the MATLAB data APIor if using C++ types a stdtuple For an example see ldquoCall Function with Native C++ Typesrdquo

ldquoCall MATLAB Functions from C++rdquo

ldquoMATLAB Data APIrdquo

fevalAsyncFutureResultltstdvectorltmatlabdataArraygtgt fevalAsync(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt amp output = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amp error = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs)

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB function with input arguments and returned values asynchronously

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

1 API Reference

1-136

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

FutureResult A FutureResult object used to get the result of calling theMATLAB function

None

This example passes the scalar double 127 to the MATLAB sqrt functionasynchronously The FutureResult is then used to get the result

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() matlabdataArrayFactory factory matlabdataArray argument = factorycreateScalarltdoublegt(127) FutureResultltmatlabdataArraygt future = matlabPtr-gt fevalAsync(convertUTF8StringToUTF16String(sqrt) stdmove(argument))

matlabengineMATLABEngine

1-137

matlabdataTypedArrayltdoublegt result = futureget()

ldquoCall Function Asynchronouslyrdquo

evalvoid eval(const matlabengineString ampstatement const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string synchronously

constmatlabengineString ampstatement

MATLAB statement to evaluate

conststdshared_ptrltmatlabengineStreamBuffergtampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergtamperror

Stream buffer used to store the error message from theMATLAB command

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

There is a runtime error in the MATLAB statement

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB statement

This example evaluates the following MATLAB statement

a = sqrt(127)

1 API Reference

1-138

The statement creates the variable a in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

evalAsyncFutureResultltvoidgt evalAsync(const matlabengineString ampstr const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string asynchronously

const Stringamp str MATLAB statement to evaluateconststdshared_ptrltmatlabengineStreamBuffergt ampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergt amperror

Stream buffer used to store the error message from theMATLAB command

FutureResult A FutureResult object used to wait for the completion of theMATLAB statement

None

This example evaluates the following MATLAB statement asynchronouslya = sqrt(127)

The statement creates the variable a in the MATLAB base workspace

matlabengineMATLABEngine

1-139

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltvoidgt future = matlabPtr-gt evalAsync(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

getVariablematlabdataArray getVariable(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace

constmatlabengineStringamp varName

Name of a variable in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variablefrom For more information see global

matlabdataArray

Variable obtained from the MATLAB base or global workspace

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The requested variable does not exist in the specifiedMATLAB base or global workspace

This example gets a variable named varName from the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray varName = matlabPtr-gtgetVariable(convertUTF8StringToUTF16String(varName))

1 API Reference

1-140

ldquoPass Variables from MATLAB to C++rdquo

getVariableAsyncFutureResultltmatlabdataArraygt getVariableAsync(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace asynchronously

constmatlabengineStringamp varName

Name of the variable in MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variable fromFor more information see global

FutureResult A FutureResult object that you can use to get the variableobtained from the MATLAB workspace as amatlabdataArray

None

This example gets a variable named varName from the MATLAB base workspaceasynchronously

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltmatlabdataArraygt future = matlabPtr-gt getVariableAsync(convertUTF8StringToUTF16String(varName))matlabdataArray varName = futureget()

ldquoPass Variables from MATLAB to C++rdquo

matlabengineMATLABEngine

1-141

setVariablevoid setVariable(const matlabengineString ampvarName const matlabdataArray ampvar WorkspaceType workspaceType = WorkspaceTypeBASE)

Put a variable into the MATLAB base or global workspace If a variable with the samename exists in the MATLAB workspace setVariable overwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

matlabengineMATLABNotAvailableException

The MATLAB session is not available

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from C++ to MATLABrdquo

setVariableAsyncFutureResultltvoidgt setVariableAsync(const matlabengineString ampvarName const matlabdataArray var WorkspaceType workspaceType = WorkspaceTypeBASE)

1 API Reference

1-142

Put a variable into the MATLAB base or global workspace asynchronously If a variablewith the same name exists in the MATLAB base workspace setVariableAsyncoverwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

None

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )FutureResultltvoidgt future = matlabPtr-gt setVariableAsync(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from MATLAB to C++rdquo

getPropertymatlabdataArray getProperty(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property

matlabengineMATLABEngine

1-143

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

matlabdataArray

Value of the named property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetProperty returns the exception messageproperty value as a matlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(try surf(4) catch me end))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))matlabdataCharArray message = matlabPtr-gt getProperty(mException convertUTF8StringToUTF16String(message))stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

getPropertyAsyncFutureResultltmatlabdataArraygt getPropertyAsync(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property asynchronously

1 API Reference

1-144

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

FutureResult FutureResult object that is used to synchronize the operation

None

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetPropertyAsync returns a FutureResultthat you use to get the exception message property value as amatlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(trysurf(4)catch meend))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))FutureResultltmatlabdataArraygt future = matlabPtr-gt getPropertyAsync(mException convertUTF8StringToUTF16String(message))matlabdataCharArray message = futureget()stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

setPropertyvoid setProperty(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property

matlabdataArray ampobject

MATLAB object

matlabengineMATLABEngine

1-145

const StringamppropertyName

Name of the property to set

constmatlabdataArray amppropertyValue

Value assigned to the property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example shows how to set a MATLAB object property It creates a MATLAB graphand returns the line handle object Setting the value of the line LineStyle property tothe character changes the property value of the line object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray()matlabPtr-gtsetProperty(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

setPropertyAsyncFutureResultltvoidgt setPropertyAsync(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property asynchronously

matlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property to set

1 API Reference

1-146

constmatlabdataArray amppropertyValue

Value assigned to the property

None

This example shows how to set a MATLAB object property asynchronously It creates aMATLAB graph and returns the line handle object Setting the line LineStyle propertyto the character changes the property value of the object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray() FutureResultltvoidgt future = matlabPtr-gt setPropertyAsync(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

See Also

Introduced in R2017b

matlabengineMATLABEngine

1-147

matlabengineconnectMATLABConnect to shared MATLAB session synchronously

Descriptionstdunique_ptrltMATLABEnginegt connectMATLAB()

stdunique_ptrltMATLABEnginegt connectMATLAB(constmatlabengineStringamp name)

Connect synchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-148

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to a MATLABEngine object

ExceptionsmatlabengineEngineException

Throws exception if function fails to connect to the specified MATLABsession

Examples

Connect to Shared MATLAB Session

Connect to a shared MATLAB session named my_matlab

stdunique_ptrltMATLABEnginegt matlabPrt = connectMATLAB(convertUTF8StringToUTF16String(my_matlab))

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineconnectMatlabAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

matlabengineconnectMATLAB

1-149

matlabengineconnectMATLABAsyncConnect to shared MATLAB session asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync()

FutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync(constmatlabengineStringamp name)

Connect asynchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-150

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object that you can use to get the pointer to theMATLABEngine

Examples

Connect to Shared MATLAB Session Asynchronously

Connect to a shared MATLAB session named my_matlab asynchronously Use theFutureResult get method to retrieve the pointer to the MATLABEngine objectFutureResultsltstdunique_ptrltMATLABEnginegtgt future = connectMATLABAsync(convertUTF8StringToUTF16String(my_matlab))stdunique_ptrltMATLABEnginegt matlabPtr = futureget()

bull ldquoConnect C++ to Running MATLAB Sessionrdquo

See AlsomatlabengineconnectMatlab

TopicsldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

matlabengineconnectMATLABAsync

1-151

matlabengineconvertUTF8StringToUTF16StringConvert UTF-8 string to UTF-16 string

Descriptionstdbasic_stringltchar16_tgt convertUTF8StringToUTF16String(conststdstringamp utf8string)

Convert a UTF-8 string to a UTF-16 string Use this function to convert ASCII strings tomatlabengineString strings which are required by MATLAB C++ Enginefunctions

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdstringamputf8string

A UTF-8 string

Return Valuestdbasic_stringltchar16_tgt

A UTF-16 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-152

matlabengineTypeConversionException

The input type cannot be converted tostdbasic_stringltchar16_tgt

Examples

Convert String

Convert a UTF-8 string to a matlabengineString (UTF-16 string)

matlabengineString matlabStatement = convertUTF8StringToUTF16String(sqrt(127))

See AlsomatlabengineString |matlabengineconvertUTF16StringToUTF8String

Introduced in R2017b

matlabengineconvertUTF8StringToUTF16String

1-153

matlabengineconvertUTF16StringToUTF8StringConvert UTF-16 string to UTF-8 string

Descriptionstdstring convertUTF16StringToUTF8String(conststdbasic_stringltchar16_tgtamp utf16string)

Convert a UTF-16 string to a UTF-8 string

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdbasic_stringltchar16_tgtamputf16string

A UTF-16 string

Return Valuestdstring A UTF-8 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-154

matlabengineTypeConversionException

The input type cannot be converted to stdstring

Examples

Convert String

Convert a matlabengineString (UTF-16 string) to a stdstring (UTF-8string)

matlabengineString matlabStatement = (usqrt(127))stdstring cmdString = convertUTF16StringToUTF8String(matlabStatement)

See AlsomatlabengineString |matlabengineconvertUTF8StringToUTF16String

Introduced in R2017b

matlabengineconvertUTF16StringToUTF8String

1-155

matlabenginefindMATLABFind shared MATLAB sessions synchronously

DescriptionstdvectorltStringgt findMATLAB()

Find all shared MATLAB sessions on the local machine

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValuestdvectorltStringgt

A vector of the names of all shared MATLAB sessions on the localmachine or an empty vector if no shared MATLAB sessions areavailable

ExceptionsmatlabengineEngineException

Throws exception if the call fails while searching for shared MATLABsessions

Examples

1 API Reference

1-156

Find Shared MATLAB Session Synchronously

stdvectorltStringgt names = findMATLAB()

See AlsomatlabenginefindMATLABAsync

Introduced in R2017b

matlabenginefindMATLAB

1-157

matlabenginefindMATLABAsyncFind shared MATLAB sessions asynchronously

DescriptionFutureResultltstdvectorltStringgtgt findMATLABAsync()

Find all shared MATLAB sessions on the local machine asynchronously

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValueFutureResultltstdvectorltStringgtgt

A FutureResult object that you can use to get the names of sharedMATLAB sessions on the local machine

Examples

Find Shared MATLAB Session Asynchronously

Find the names of all shared MATLAB sessions on the local machine asynchronouslyUse the FutureResult get method to retrieve the names

1 API Reference

1-158

FutureResultltstdvectorltStringgtgt futureNames = findMATLABAsync()stdvectorltStringgt matlabSessions = futureNamesget()

See AlsomatlabenginefindMATLAB

Introduced in R2017b

matlabenginefindMATLABAsync

1-159

matlabengineFutureResultRetrieve result from asynchronous operation

DescriptionA future result is an object that you can use to retrieve the result of MATLAB functionsor statements The FutureResult class provides all member functions of the C++stdfuture class

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Functions Delegated to stdfutureoperator= share get wait wait_for wait_until

1 API Reference

1-160

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement You cannot cancelasynchronous operations that use matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution had already begun

bool Was command canceled if execution had already begun

bool flag = futurecancel()

No exceptions thrown

matlabengineFutureResult

1-161

See Also

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

1 API Reference

1-162

matlabenginestartMATLABStart MATLAB synchronously

Descriptionstdunique_ptrltMATLABEnginegt startMATLAB(const stdvectorltStringgtampoptions = stdvectorltStringgt())

Start MATLAB synchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtampoptions

Options used to start MATLAB See ldquoSpecify Startup Optionsrdquo

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to the MATLABEngine object

matlabenginestartMATLAB

1-163

ExceptionsmatlabengineEngineException

MATLAB failed to start

Examples

Start MATLAB Synchronously

Start MATLAB synchronously and return a unique pointer to the MATLABEngine object

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Start MATLAB with Startup Options

Start MATLAB with the -nojvm option and return a unique pointer to theMATLABEngine object

stdvectorltStringgt optionVecoptionVecpush_back(convertUTF8StringToUTF16String(-nojvm))stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB(optionVec)

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineMATLABEngine | matlabenginestartMATLABAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

1 API Reference

1-164

matlabenginestartMATLABAsyncStart MATLAB asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt startMATLABAsync(conststdvectorltStringgtamp options = stdvectorltStringgt())

Start MATLAB asynchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtamp options

Startup options used to launch MATLAB

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object used to get the pointer to theMATLABEngine

Examples

matlabenginestartMATLABAsync

1-165

Start MATLAB Asynchronously

Start MATLAB asynchronously and return a FutureResult object Use theFutureResult to get a pointer to the MATLABEngine objectFutureResultltstdunique_ptrltMATLABEnginegtgt matlabFuture = startMATLAB()stdunique_ptrltMATLABEnginegt matlabPtr = matlabFutureget()

bull ldquoSpecify Startup Optionsrdquo

See AlsomatlabenginestartMATLAB

TopicsldquoSpecify Startup Optionsrdquo

Introduced in R2017b

1 API Reference

1-166

matlabengineterminateEngineClientFree engine resources during runtime

Descriptionvoid matlabengineterminateEngineClient releases all MATLAB engineresources during runtime when you no longer need the MATLAB engine in yourapplication program

Note Programs cannot start a new MATLAB engine or connect to a shared MATLABsession after calling terminateEngineClient

IncludeNamespace matlabengineInclude MatlabEnginehpp

ExamplesTerminate the engine session to free resources Start MATLAB sessionstdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Terminate MATLAB sessionmatlabengineterminateEngineClient()

See AlsomatlabenginestartMATLAB

Introduced in R2017b

matlabengineterminateEngineClient

1-167

matlabengineWorkspaceTypeType of MATLAB workspace

DescriptionThe matlabengineWorkspaceType enum class specifies the MATLAB workspaceto pass variables to or get variables fromBASE Variables scoped to the MATLAB base workspace

(command line and nonfunction scripts)GLOBAL Variables scoped to the MATLAB global workspace

(command line functions and scripts)

MATLAB scopes variables by workspace Variables that are scoped to the baseworkspace must be passed to functions as arguments Variables scoped to the globalworkspace can be accessed by any function that defines the specific variable name asglobal

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

ExamplesThis example

bull Connects to a shared MATLAB sessionbull Creates a matlabdataArray containing numeric values of type doublebull Puts the array in the MATLAB global workspaceinclude MatlabDataArrayhppinclude MatlabEnginehppinclude ltiostreamgt

static void putGlobalVar()

1 API Reference

1-168

using namespace matlabengine

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

Create matlab data array factory matlabdataArrayFactory factory

Create data variable matlabdataArray data = factorycreateArrayltdoublegt ( 1 5 40 110 47 362 723 )

Put data variable in MATLAB global workspace matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data WorkspaceTypeGLOBAL)

See AlsomatlabdataArrayFactory | matlabengineMATLABEngine |matlabengineconvertUTF8StringToUTF16String

TopicsldquoPass Variables from C++ to MATLABrdquoldquoPass Variables from MATLAB to C++rdquo

Introduced in R2017b

matlabengineWorkspaceType

1-169

matlabengineStringDefine UTF16 string

DescriptionType definition for stdbasic_stringltchar16_tgt

ExamplesThis example defines a variable containing the name of a shared MATLAB session Passthis string to the matlabengineconnectMATLAB function to connect to the namedsessionmatlabengineString session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

See AlsomatlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoMATLAB Engine API for C++rdquoldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

1 API Reference

1-170

matlabengineStreamBufferDefine stream buffer

DescriptionType definition for stdbasic_streafbufltchar16_tgt

ExamplesThis example defines string buffers to return output from the evaluation of a MATLABfunction by the MATLABEngineeval member function This function uses a bufferderived from matlabengineStreamBuffer to return output from MATLAB to C++include MatlabEnginehppinclude MatlabDataArrayhppinclude ltiostreamgt

using namespace matlabengineusing SBuf = stdbasic_stringbufltchar16_tgt

void printFromBuf(const stdshared_ptrltSBufgt buf) Get text from buf auto text_ = buf-gtstr() stdcout ltlt ltlt convertUTF16StringToUTF8String(text_) ltlt ltlt stdendl

int main()

Create Array factory matlabdataArrayFactory factory

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

auto outBuf = stdmake_sharedltSBufgt() auto errBuf = stdmake_sharedltSBufgt()

matlabPtr-gteval(convertUTF8StringToUTF16String(matlabengineengineName) outBuf errBuf) printFromBuf(outBuf) printFromBuf(errBuf) return 0

matlabengineStreamBuffer

1-171

See AlsomatlabengineconnectMATLAB |matlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoRedirect MATLAB Command Window Output to C++rdquo

Introduced in R2017b

1 API Reference

1-172

matlabengineSharedFutureResultRetrieve result from asynchronous operation as shared future

DescriptionA shared future result is an object that you use to retrieve the result of MATLABfunctions or statements any number of times

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using one of these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Function Delegated to stdshared_futureoperator= get valid wait wait_for wait_until

matlabengineSharedFutureResult

1-173

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement

Note that you cannot cancel asynchronous start connection or find operations which areinitiated using these functions matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution has already begun

bool True if the MATLAB command can be canceled

bool flag = futurecancel()

None

1 API Reference

1-174

See AlsomatlabengineFutureResult

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

matlabengineSharedFutureResult

1-175

commathworksengineMatlabEngine classPackage commathworksengine

Java class using MATLAB as a computational engine

DescriptionThe commathworksengineMatlabEngine class uses a MATLAB process as acomputational engine for Javareg This class provides an interface between the Javalanguage and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom Java

Constructor SummaryThe MatlabEngine class provides static methods to start MATLAB and to connect to ashared MATLAB session synchronously or asynchronously Only these static methodscan instantiate this class

bull Start MATLAB synchronously mdash ldquostartMatlabrdquo on page 1-178bull Connect to shared MATLAB session synchronously mdash ldquoconnectMatlabrdquo on page 1-180bull Start MATLAB asynchronously mdash ldquostartMatlabAsyncrdquo on page 1-179bull Connect to shared MATLAB session asynchronously mdash ldquoconnectMatlabAsyncrdquo on

page 1-181

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -n

1 API Reference

1-176

bull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup Optionsrdquo

Method Summary

Static MethodsldquostartMatlabrdquo onpage 1-178

Start MATLAB synchronously

ldquostartMatlabAsyncrdquoon page 1-179

Start MATLAB asynchronously

ldquofindMatlabrdquo onpage 1-179

Find all available shared MATLAB sessions from a local machinesynchronously

ldquofindMatlabAsyncrdquoon page 1-180

Find all available shared MATLAB sessions from a local machineasynchronously

ldquoconnectMatlabrdquo onpage 1-180

Connect to a shared MATLAB session on a local machinesynchronously

ldquoconnectMatlabAsyncrdquo on page 1-181

Connect to a shared MATLAB session on a local machineasynchronously

Member VariableNULL_WRITER Use a writer that ignores the contents from the MATLAB

command window

Member Functionsldquofevalrdquo on page 1-182

Evaluate a MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-183

Evaluate a MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-184 Evaluate a MATLAB expression as a string synchronously

commathworksengineMatlabEngine class

1-177

ldquoevalAsyncrdquo on page1-185

Evaluate a MATLAB expression as a string asynchronously

ldquogetVariablerdquo onpage 1-186

Get a variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-187

Get a variable from the MATLAB base workspace asynchronously

ldquoputVariablerdquo onpage 1-187

Put a variable into the MATLAB base workspace synchronously

ldquoputVariableAsyncrdquoon page 1-188

Put a variable into the MATLAB base workspace asynchronously

ldquodisconnectrdquo on page1-188

Disconnect from the current MATLAB session synchronously

ldquodisconnectAsyncrdquoon page 1-189

Disconnect from the current MATLAB session asynchronously

ldquoquitrdquo on page 1-189 Force the shutdown of the current MATLAB sessionsynchronously

ldquoquitAsyncrdquo on page1-189

Force the shutdown of the current MATLAB sessionasynchronously

ldquocloserdquo on page 1-190

Disconnect or terminate the current MATLAB session

Method Details

startMatlabstatic MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Start MATLAB synchronously

String[] options Startup options used to start MATLAB engine For options seeldquoStartup and Shutdownrdquo

1 API Reference

1-178

Instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start

MatlabEngine engine = MatlabEnginestartMatlab()

ldquoStart and Close MATLAB Session from Javardquo

startMatlabAsyncstatic FutureltMatlabEnginegt startMatlabAsync(String[] options)

static FutureltMatlabEnginegt startMatlabAsync()

Start MATLAB asynchronously

String[] options Startup options used to start MATLAB For options seeldquoStartup and Shutdownrdquo

Instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEnginestartMatlabAsync()

ldquoStart and Close MATLAB Session from Javardquo

findMatlabstatic String[] findMatlab()

Find all shared MATLAB sessions on the local machine synchronously

commathworksengineMatlabEngine class

1-179

An array of the names of all shared MATLAB sessions on the local machine or an emptyvector if there are no shared MATLAB sessions available on the local machine

commathworksengineEngineException

If there is a failure during the search for MATLAB sessions

String[] engines = MatlabEnginefindMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

findMatlabAsyncstatic FutureltSting[]gt findMatlabAsync()

Find all shared MATLAB sessions on local machine asynchronously

An instance of FutureltString[]gt

FutureltString[]gt future = MatlabEnginefindMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabstatic MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Connect to a shared MATLAB session on local machine synchronously

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session with default options

1 API Reference

1-180

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

String name Name of the shared MATLAB session Use ldquofindMatlabrdquo on page1-179 to get the names of shared MATLAB sessions

An instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start or connect

MatlabEngine engine = MatlabEngineconnectMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabAsyncstatic FutureltMatlabEnginegt connectMatlabAsync(String name)

static FutureltMatlabEnginegt connectMatlabAsync

Connect to a shared MATLAB session on local machine asynchronously The behavior isthe same as that of connectMatlab except the mechanism is asynchronous

String name Name of the shared MATLAB session

An instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEngineconnectMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

commathworksengineMatlabEngine class

1-181

fevalltTgt T feval(int nlhs String func Writer output Writer errorObjecthellip args)

ltTgt T feval(int nlhs String func Objecthellip args)

ltTgt T feval(String func Writer output Writer error Objecthellip args)

ltTgt T feval(String func Objecthellip args)

Evaluate MATLAB functions with input arguments synchronously

String func Name of the MATLAB function or script to evaluateint nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

Result of executing the MATLAB function

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

1 API Reference

1-182

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is a MATLAB runtime error in the function

commathworksengineUnsupportedTypeExeption

There is an unsupported data type

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB function

double result = enginefeval(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

fevalAsyncltTgt FutureltTgt fevalAsync(int nlhs String func Writer outputWriter error Objecthellip args)

ltTgt FutureltTgt fevalAsync(int nlhs String func Objecthellip args)

ltTgt FutureltTgt fevalAsync(String func Writer output Writer errorObjecthellip args)

ltTgt FutureltTgt fevalAsync(String func Objecthellip args)

Evaluate MATLAB functions with input arguments asynchronously

String func Name of the MATLAB function or script to evaluate

commathworksengineMatlabEngine class

1-183

int nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginefevalAsync(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

evalvoid eval(String command Writer output Writer error)

void eval(String command)

Evaluate a MATLAB statement as a string synchronously

1 API Reference

1-184

String command MATLAB statement to evaluateWriter output Stream used to store the standard output from the MATLAB

statement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABstatement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is an error in the MATLAB statement duringruntime

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB statement

engineeval(result = sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

evalAsyncFutureltVoidgt evalAsync(String command Writer output Writer error)

FutureltVoidgt evalAsync(String command)

Evaluate a MATLAB statement as a string asynchronously

String command MATLAB statement to evaluate

commathworksengineMatlabEngine class

1-185

Writer output Stream used to store the standard output from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the output from the MATLABcommand window

Writer error Stream used to store the standard error from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the error message from theMATLAB command window

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineevalAsync(sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

getVariableltTgt T getVariable(String varName)

Get a variable from the MATLAB base workspace

String varName Name of a variable in the MATLAB base workspace

Variable passed from the MATLAB base workspace

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

1 API Reference

1-186

javalangIllegalStateException

The MATLAB session is not available

double myVar = enginegetVariable(myVar)

ldquoPass Variables from MATLAB to Javardquo

getVariableAsyncltTgt FutureltTgt getVariableAsync(String varName)

Get a variable from the MATLAB base workspace asynchronously

String varName Name of a variable in MATLAB base workspace

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginegetVariableAsync(myVar)

ldquoPass Variables from MATLAB to Javardquo

putVariablevoid putVariable(String varName T varData)

Put a variable into the MATLAB base workspace

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

commathworksengineMatlabEngine class

1-187

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

javalangIllegalStateException

The MATLAB session is not available

engineputVariable(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

putVariableAsyncFutureltVoidgt putVariableAsync(String varName T varData)

Put a variable into the MATLAB base workspace asynchronously

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineputVariableAsync(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

disconnectvoid disconnect()

Disconnect from the current MATLAB session

1 API Reference

1-188

commathworksengineEngineException

The current MATLAB session cannot be disconnected

enginedisconnect()

ldquoClose MATLAB Engine Sessionrdquo

disconnectAsyncFutureltVoidgt disconnectAsync()

Disconnect from the current MATLAB session

FutureltVoidgt future = enginedisconnectAsync()

ldquoClose MATLAB Engine Sessionrdquo

quitviod quit()

Force the shutdown of the current MATLAB session

commathworksengineEngineException

The current MATLAB session cannot be shut down

enginequit()

ldquoClose MATLAB Engine Sessionrdquo

quitAsyncFutureltVoidgt quitAsync()

commathworksengineMatlabEngine class

1-189

Force the shutdown of the current MATLAB session asynchronously without waiting fortermination

An instance of FutureltVoidgt

FutureltVoidgt future = enginequitAsync()

ldquoClose MATLAB Engine Sessionrdquo

closevoid close()

MatlabEngine provides the close() method to implement thejavalangAutoCloseable interface for MatlabEngine objects This close()method enables you to use a try-with-resources statement to automatically disconnect orterminate the MATLAB session at the end of the statement

The MatlabEngine close() method disconnects or terminates the current MATLABsession depending on the context

bull If a Java process starts the MATLAB session as a default non-shared sessionclose() terminates MATLAB

bull If the MATLAB session is a shared session close() disconnects MATLAB from thisJava process MATLAB terminates when there are no other connections

To force the shutdown or disconnection of the current MATLAB session explicitly callMatlabEnginequit() MatlabEnginedisconnect() or their asynchronouscounterparts

engineclose()

ldquoClose MATLAB Engine Sessionrdquo

1 API Reference

1-190

Examples

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously The workflowis

bull Open a MATLAB sessionbull Invoke the MATLAB sqrt function with arguments asynchronouslybull Get the result of the MATLAB functionbull Close the MATLAB engine

import commathworksengineMatlabEngine

FutureltMatlabEnginegt engFuture = MatlabEnginestartMatlabAsync()MatlabEngine engine = engFutureget()double myVar = 4FutureltDoublegt future = enginefevalAsync(sqrt myVar)double result = futureget()Systemoutprintln(result)

See AlsomatlabengineengineName | matlabengineisEngineShared |matlabengineshareEngine

TopicsldquoBuild Java Engine ProgramsrdquoldquoStart and Close MATLAB Session from Javardquo

Introduced in R2016b

commathworksengineMatlabEngine class

1-191

commathworksmatlabtypesComplex classPackage commathworksmatlabtypes

Java class to pass complex data to and from MATLAB

DescriptionThe Complex class provides Java support for MATLAB complex arrays Use this class topass complex data to MATLAB The MATLAB engine passes complex data to Java as aninstance of Complex

All MATLAB numeric types are converted to double in Java

Constructor SummaryComplex(double real double imag) constructs an instance of Complex with thespecified real and imaginary values

Field Summarydouble real The real part of the complex datadouble imag The imaginary part of the complex data

Examples

Pass Complex Variable to MATLAB Function

import commathworksengineMatlabEngine

MatlabEngine engine = MatlabEnginestartMatlab()

1 API Reference

1-192

Complex c = new Complex(23)Complex cj = enginefeval(conjc)

bull ldquoUsing Complex Variables in Javardquo

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoUsing Complex Variables in Javardquo

Introduced in R2016b

commathworksmatlabtypesComplex class

1-193

commathworksmatlabtypesHandleObject classPackage commathworksmatlabtypes

Java class to represent MATLAB handle objects

DescriptionJava represents handle objects that are passed from MATLAB as instances of theHandleObject class When passing a handle object back to MATLAB Java passes areference to the HandleObject instance This reference can be either an array or ascalar depending on the original handle object passed to Java from MATLAB

You can pass a handle object only to the MATLAB session in which it was originallycreated You cannot construct a HandleObject in Java

Examples

Get Handle Object from MATLAB

This example starts a shared MATLAB session and creates a containersMap object inthe MATLAB workspace The statement evaluated in the MATLAB workspace returns ahandle variable that refers to the Map object

The engine getVariable function returns the MATLAB handle variable as aHandleObject instance This instance is used to call the MATLABcontainersMapkeys function to obtain the Map keys

import commathworksengineMatlabEngineimport commathworksmatlabtypes

MatlabEngine engine = MatlabEnginestartMatlab()engineeval(cm = containersMap(idname11mw))

1 API Reference

1-194

HandleObject handle = enginegetVariable(cm)String[] cells = enginefeval(keys handle)

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex | commathworksmatlabtypesStruct

TopicsldquoUsing MATLAB Handle Objects in Javardquo

Introduced in R2016b

commathworksmatlabtypesHandleObject class

1-195

commathworksmatlabtypesStruct classPackage commathworksmatlabtypes

Java class to pass MATLAB struct to and from MATLAB

DescriptionThe Struct class provides support for passing data between MATLAB and Java as aMATLAB struct The Struct class implements the javautilMap interface

The Struct class is designed as an immutable type Attempting to change the mappingskeys or values of the returned Struct causes an UnsupportedOperationExceptionCalling these methods can cause the exception put() putAll() remove()entrySet() keySet() and values()

For an example see ldquoUsing MATLAB Structures in Javardquo

Constructor SummaryStruct s = new Struct(field1value1field2value2 ) creates aninstance of Struct with the specified field names and values

Method SummarycontainsKey(Object key) Returns true if this map contains a

mapping for the specified keycontainsValue(Object value) Returns true if this map maps one or more

keys to the specified valueentrySet() Returns a Set view of the mappings

contained in this mapequals(Object o) Compares the specified object with this

map for equality

1 API Reference

1-196

get(Object key) Returns the value to which the specifiedkey is mapped or null if this map containsno mapping for the key

hashCode() Returns the hash code value for this mapisEmpty() Returns true if this map contains no key-

value mappingskeySet() Returns a Set view of the keys contained

in this mapsize() Returns the number of key-value mappings

in this mapvalues() Returns a Collection view of the values

contained in this map

Examples

Create Struct for MATLAB Function Argument

Create a Struct and assign a key and value

import commathworksengineimport commathworksmatlabtypes

class StructProperties public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() int[] y = 12345 double[] color = 100507 Struct s = new Struct(ColorcolorLineWidth2) engfeval(plotys)

bull ldquoUsing MATLAB Structures in Javardquo

commathworksmatlabtypesStruct class

1-197

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject

TopicsldquoUsing MATLAB Structures in Javardquo

Introduced in R2016b

1 API Reference

1-198

commathworksmatlabtypesCellStr classPackage commathworksmatlabtypes

Java class to represent MATLAB cell array of char vectors

DescriptionThe CellStr class provides support for passing data from Java to MATLAB as aMATLAB cell array of char vectors (called a cellstr in MATLAB see cellstr) Thereare MATLAB functions that require cell arrays of char vectors as inputs To passarguments from Java to a MATLAB function requiring cellst inputs use the JavaCellStr class to create a compatible type

A MATLAB cellstr is mapped to a Java String array

Constructor SummaryCellStr(Object stringArray) creates a CellStr using a String or String arrayThe String array can have multiple dimensions

Method SummaryObject getStringArray() Get the String or String array used to

create the CellStrboolean equals(CellStr1CellStr2) Compare one CellStr instance with

another Two CellStr instances are equalif the String or String array they containare the same

commathworksmatlabtypesCellStr class

1-199

Examples

Construct CellStrThis example constructs a CellStr named keySet and puts the variable in theMATLAB base workspaceimport commathworksengineimport commathworksmatlabtypes

class javaCellstr public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() CellStr keySet = new CellStr(new String[]JanFebMarApr) engputVariable(mapKeyskeySet) engclose()

Construct CellStr Array

This example creates a CellStr array and passes it to the MATLAB plot function tochange the appearance of the graph produced by MATLAB The call to the MATLABprint function exports the figure as a jpeg file named myPlotjpg

import commathworksengineimport commathworksmatlabtypes

class CellStrArray public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() String[][] strArray = new String[2][2] strArray[0][0] = MarkerFaceColor strArray[0][1] = MarkerEdgeColor strArray[1][0] = green strArray[1][1] = red CellStr markerCellStr = new CellStr(strArray) engputVariable(MmarkerCellStr) engeval(plot(110--bsM)) engeval(print(myPlot-djpeg)) engclose()

1 API Reference

1-200

See AlsocommathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoPass Java CellStr to MATLABrdquo

Introduced in R2016b

commathworksmatlabtypesCellStr class

1-201

engClose (C and Fortran)Quit MATLAB engine session

C Syntaxinclude enginehint engClose(Engine ep)

Fortran Syntaxinclude enginehinteger4 engClose(ep)mwPointer ep

Argumentsep

Engine pointer

Returns0 on success and 1 otherwise Possible failure includes attempting to terminate analready-terminated MATLAB engine session

DescriptionThis routine sends a quit command to the MATLAB engine session and closes theconnection

1 API Reference

1-202

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIXreg operating systemsbull engwindemoc for a C example on Microsoftreg Windowsreg operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen

Introduced before R2006a

engClose (C and Fortran)

1-203

engEvalString (C and Fortran)Evaluate expression in string

C Syntaxinclude enginehint engEvalString(Engine ep const char string)

Fortran Syntaxinclude enginehinteger4 engEvalString(ep string)mwPointer epcharacter() string

Argumentsep

Engine pointerstring

String to execute

Returns1 if the engine session is no longer running or the engine pointer is invalid or NULLOtherwise returns 0 even if the MATLAB engine session cannot evaluate the command

DescriptionengEvalString evaluates the expression contained in string for the MATLAB enginesession ep previously started by engOpen

1 API Reference

1-204

UNIX Operating Systems

On UNIX systems engEvalString sends commands to the MATLAB workspace bywriting down a pipe connected to the MATLAB stdin process MATLAB reads back fromstdout any output resulting from the command that ordinarily appears on the screeninto the buffer defined by engOutputBuffer

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Microsoft Windows Operating Systems

On a Windows system engEvalString communicates with MATLAB software using aComponent Object Model (COM) interface

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engOutputBuffer

Introduced before R2006a

engEvalString (C and Fortran)

1-205

engGetVariable (C and Fortran)Copy variable from MATLAB engine workspace

C Syntaxinclude enginehmxArray engGetVariable(Engine ep const char name)

Fortran Syntaxinclude enginehmwPointer engGetVariable(ep name)mwPointer epcharacter() name

Argumentsep

Engine pointername

Name of mxArray to get from MATLAB workspace

ReturnsPointer to a newly allocated mxArray structure or NULL if the attempt failsengGetVariable fails if the named variable does not exist

DescriptionengGetVariable reads the named mxArray from the MATLAB engine sessionassociated with ep

1 API Reference

1-206

The limit for the size of data transferred is 2 GB

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengPutVariable mxDestroyArray

Introduced before R2006a

engGetVariable (C and Fortran)

1-207

engGetVisible (C)Determine visibility of MATLAB engine session

C Syntaxinclude enginehint engGetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Pointer to value returned from engGetVisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengGetVisible returns the current visibility setting for MATLAB engine session ep Avisible engine session runs in a window on the Windows desktop thus making the engineavailable for user interaction MATLAB removes an invisible session from the desktop

ExamplesThe following code opens engine session ep and disables its visibility

1 API Reference

1-208

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengSetVisible

engGetVisible (C)

1-209

Engine (C)Type for MATLAB engine

DescriptionA handle to a MATLAB engine object

Engine is a C language opaque type

You can call MATLAB software as a computational engine by writing C and Fortranprograms that use the MATLAB engine library Engine is the link between yourprogram and the separate MATLAB engine process

The header file containing this type is

include engineh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc shows how to call the MATLAB engine functions from a C programbull engwindemoc show how to call the MATLAB engine functions from a C program for

Windows systemsbull fengdemoF shows how to call the MATLAB engine functions from a Fortran

program

See AlsoengOpen

1 API Reference

1-210

engOpen (C and Fortran)Start MATLAB engine session

C Syntaxinclude enginehEngine engOpen(const char startcmd)

Fortran Syntaxinclude enginehmwPointer engOpen(startcmd)character() startcmd

Argumentsstartcmd

String to start the MATLAB process On Windows systems the startcmd stringmust be NULL

ReturnsPointer to an engine handle or NULL if the open fails

DescriptionThis routine allows you to start a MATLAB process for using MATLAB as acomputational engine

engOpen starts a MATLAB process using the command specified in the stringstartcmd establishes a connection and returns an engine pointer

engOpen (C and Fortran)

1-211

On UNIX systems if startcmd is NULL or the empty string engOpen starts a MATLABprocess on the current host using the command matlab If startcmd is a hostnameengOpen starts a MATLAB process on the designated host by embedding the specifiedhostname string into the larger string

rsh hostname bincsh -c setenv DISPLAY hostname0 matlab

If startcmd is any other string (has white space in it or nonalphanumeric characters)MATLAB executes the string literally

On UNIX systems engOpen performs the following steps

1 Creates two pipes2 Forks a new process Sets up the pipes to pass stdin and stdout from MATLAB

(parent) software to two file descriptors in the engine program (child)3 Executes a command to run MATLAB software (rsh for remote execution)

On Windows systems engOpen opens a COM channel to MATLAB The MATLABsoftware you registered during installation starts If you did not register duringinstallation enter the following command at the MATLAB prompt

matlab -regserver

See ldquoMATLAB COM Integrationrdquo for additional details

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

Introduced before R2006a

1 API Reference

1-212

engOpenSingleUse (C)Start MATLAB engine session for single nonshared use

C Syntaxinclude enginehEngine engOpenSingleUse(const char startcmd void dcom int retstatus)

Argumentsstartcmd

String to start MATLAB process On Microsoft Windows systems the startcmdstring must be NULL

dcomReserved for future use must be NULL

retstatusReturn status possible cause of failure

Returns

Microsoft Windows Operating Systems Only

Pointer to an engine handle or NULL if the open fails

UNIX Operating Systems

Not supported on UNIX systems

engOpenSingleUse (C)

1-213

DescriptionThis routine allows you to start multiple MATLAB processes using MATLAB as acomputational engine

engOpenSingleUse starts a MATLAB process establishes a connection and returns aunique engine identifier or NULL if the open fails Each call to engOpenSingleUsestarts a new MATLAB process

engOpenSingleUse opens a COM channel to MATLAB This starts the MATLABsoftware you registered during installation If you did not register during installationenter the following command at the MATLAB prompt

matlab -regserver

engOpenSingleUse allows single-use instances of an engine serverengOpenSingleUse differs from engOpen which allows multiple applications to use thesame engine server

See ldquoMATLAB COM Integrationrdquo for additional details

1 API Reference

1-214

engOutputBuffer (C and Fortran)Specify buffer for MATLAB output

C Syntaxinclude enginehint engOutputBuffer(Engine ep char p int n)

Fortran Syntaxinclude enginehinteger4 engOutputBuffer(ep p)mwPointer epcharactern p

Argumentsep

Engine pointerp

Pointer to character buffern

Length of buffer p

Returns1 if you pass it a NULL engine pointer Otherwise returns 0

engOutputBuffer (C and Fortran)

1-215

DescriptionengOutputBuffer defines a character buffer for engEvalString to return any outputthat ordinarily appears on the screen

The default behavior of engEvalString is to discard any standard output caused by thecommand it is executing A call to engOutputBuffer with a buffer of nonzero lengthtells any subsequent calls to engEvalString to save output in the character bufferpointed to by p

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Note The buffer returned by engEvalString is not NULL terminated

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engEvalString

Introduced before R2006a

1 API Reference

1-216

engPutVariable (C and Fortran)Put variable into MATLAB engine workspace

C Syntaxinclude enginehint engPutVariable(Engine ep const char name const mxArray pm)

Fortran Syntaxinclude enginehinteger4 engPutVariable(ep name pm)mwPointer ep pmcharacter() name

Argumentsep

Engine pointername

Name of mxArray in the engine workspacepm

mxArray pointer

Returns0 if successful and 1 if an error occurs

DescriptionengPutVariable writes mxArray pm to the engine ep giving it the variable name name

engPutVariable (C and Fortran)

1-217

If the mxArray does not exist in the workspace the function creates it If an mxArraywith the same name exists in the workspace the function replaces the existing mxArraywith the new mxArray

The limit for the size of data transferred is 2 GB

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The engine application owns the original mxArray and is responsible for freeing itsmemory Although the engPutVariable function sends a copy of the mxArray to theMATLAB workspace the engine application does not need to account for or free memoryfor the copy

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengGetVariable

Introduced before R2006a

1 API Reference

1-218

engSetVisible (C)Show or hide MATLAB engine session

C Syntaxinclude enginehint engSetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Value to set the Visible property to Set value to 1 to make the engine windowvisible or to 0 to make it invisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengSetVisible makes the window for the MATLAB engine session ep either visible orinvisible on the Windows desktop You can use this function to enable or disable userinteraction with the MATLAB engine session

engSetVisible (C)

1-219

ExamplesThe following code opens engine session ep and disables its visibility

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengGetVisible

1 API Reference

1-220

matClose (C and Fortran)Close MAT-file

C Syntaxinclude mathint matClose(MATFile mfp)

Fortran Syntaxinclude mathinteger4 matClose(mfp)mwPointer mfp

Argumentsmfp

Pointer to MAT-file information

ReturnsEOF in C (-1 in Fortran) for a write error and 0 if successful

DescriptionmatClose closes the MAT-file associated with mfp

ExamplesSee the following examples in matlabrootexternexampleseng_mat

matClose (C and Fortran)

1-221

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen

Introduced before R2006a

1 API Reference

1-222

matDeleteVariable (C and Fortran)Delete array from MAT-file

C Syntaxinclude mathint matDeleteVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathinteger4 matDeleteVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to delete

Returns0 if successful and nonzero otherwise

DescriptionmatDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp

matDeleteVariable (C and Fortran)

1-223

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

Introduced before R2006a

1 API Reference

1-224

MATFile (C and Fortran)Type for MAT-file

DescriptionA handle to a MAT-file object A MAT-file is the data file format MATLAB software usesfor saving data to your disk

MATFile is a C language opaque type

The MAT-file interface library contains routines for reading and writing MAT-files Callthese routines from your own CC++ and Fortran programs using MATFile to accessyour data file

The header file containing this type is

include math

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen matClose matPutVariable matGetVariable mxDestroyArray

MATFile (C and Fortran)

1-225

matGetDir (C and Fortran)List of variables in MAT-file

C Syntaxinclude mathchar matGetDir(MATFile mfp int num)

Fortran Syntaxinclude mathmwPointer matGetDir(mfp num)mwPointer mfpinteger4 num

Argumentsmfp

Pointer to MAT-file informationnum

Pointer to the variable containing the number of mxArrays in the MAT-file

ReturnsPointer to an internal array containing pointers to the names of the mxArrays in theMAT-file pointed to by mfp In C each name is a NULL-terminated string The numoutput argument is the length of the internal array (number of mxArrays in the MAT-file) If num is zero mfp contains no arrays

matGetDir returns NULL in C (0 in Fortran) If matGetDir fails sets num to a negativenumber

1 API Reference

1-226

DescriptionThis routine provides you with a list of the names of the mxArrays contained within aMAT-file

matGetDir allocates memory for the internal array of strings using a mxCalloc Freethe memory using mxFree when you are finished with the array

MATLAB variable names can be up to length mxMAXNAM defined in the C header filematrixh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo2F

Introduced before R2006a

matGetDir (C and Fortran)

1-227

matGetFp (C)File pointer to MAT-file

C Syntaxinclude mathFILE matGetFp(MATFile mfp)

Argumentsmfp

Pointer to MAT-file information

ReturnsC file handle to the MAT-file with handle mfp Returns NULL if mfp is a handle to aMAT-file in HDF5-based format

DescriptionUse matGetFp to obtain a C file handle to a MAT-file Standard C library routines likeferror and feof use file handle to investigate errors

Introduced before R2006a

1 API Reference

1-228

matGetNextVariable (C and Fortran)Next array in MAT-file

C Syntaxinclude mathmxArray matGetNextVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing the next mxArray from theMAT-file pointed to by mfp The function returns the name of the mxArray in name

matGetNextVariable returns NULL in C (0 in Fortran) for end of file or if there is anerror condition In C use feof and ferror from the Standard C Library to determinestatus

matGetNextVariable (C and Fortran)

1-229

DescriptionmatGetNextVariable allows you to step sequentially through a MAT-file and readevery mxArray in a single pass The function reads and returns the next mxArray fromthe MAT-file pointed to by mfp

Use matGetNextVariable immediately after opening the MAT-file with matOpen andnot with other MAT-file routines Otherwise the concept of the next mxArray isundefined

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariable is notguaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariableInfo matGetVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-230

matGetNextVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetNextVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing header information for thenext mxArray from the MAT-file pointed to by mfp The function returns the name of themxArray in name

matGetNextVariableInfo returns NULL in C (0 in Fortran) when the end of file isreached or if there is an error condition In C use feof and ferror from the Standard CLibrary to determine status

matGetNextVariableInfo (C and Fortran)

1-231

DescriptionmatGetNextVariableInfo loads only the array header information includingeverything except pr pi ir and jc from the current file offset

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetNextVariableInfo sets them to -1 instead These headers are forinformational use only Never pass this data back to the MATLAB workspace or save it toMAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariableInfo isnot guaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariable matGetVariableInfo

Introduced before R2006a

1 API Reference

1-232

matGetVariable (C and Fortran)Array from MAT-file

C Syntaxinclude mathmxArray matGetVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing the mxArray named byname from the MAT-file pointed to by mfp

matGetVariable returns NULL in C (0 in Fortran) if the attempt to return the mxArraynamed by name fails

matGetVariable (C and Fortran)

1-233

DescriptionThis routine allows you to copy an mxArray out of a MAT-file

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-234

matGetVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing header information for themxArray named by name from the MAT-file pointed to by mfp

matGetVariableInfo returns NULL in C (0 in Fortran) if the attempt to return headerinformation for the mxArray named by name fails

matGetVariableInfo (C and Fortran)

1-235

DescriptionmatGetVariableInfo loads only the array header information including everythingexcept pr pi ir and jc It recursively creates the cells and structures through theirleaf elements but does not include pr pi ir and jc

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetVariableInfo sets them to -1 instead These headers are for informational useonly Never pass this data back to the MATLAB workspace or save it to MAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomatGetVariable

Introduced before R2006a

1 API Reference

1-236

matlabengineconnect_matlabConnect shared MATLAB session to MATLAB Engine for Python

Syntaxeng = matlabengineconnect_matlab(name=None)eng = matlabengineconnect_matlab( ___ async)

Descriptioneng = matlabengineconnect_matlab(name=None) connects to the sharedMATLAB session name and returns a MatlabEngine object as eng The inputargument name specifies the name of a MATLAB session that is already running on yourlocal machine

bull If you specify name and the engine cannot find a shared MATLAB session of the samename then you receive an EngineError exception

bull If you do not specify name and the engine cannot find any shared MATLAB sessionsthen it starts a new shared MATLAB session If there are shared MATLAB sessionsrunning the engine connects to the first available session

bull If you do not specify name and the engine finds multiple shared MATLAB sessionsrunning then it connects to the first available session

eng = matlabengineconnect_matlab( ___ async) connects asynchronously ifasync is True

Examples

Connect to MATLAB Session

Connect to a shared MATLAB session that is already running on your local machine

matlabengineconnect_matlab

1-237

import matlabengineeng = matlabengineconnect_matlab()engsqrt(40)

20

matlabengineconnect_matlab connects to the first available shared MATLABsession If no MATLAB sessions are shared matlabengineconnect_matlab starts anew session

Connect to MATLAB Sessions by Name

When there are multiple shared MATLAB sessions on your local machine connect to twodifferent sessions one at a time by specifying their names

Connect to the first shared MATLAB session

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

Connect to the second shared MATLAB session

eng = matlabengineconnect_matlab(MATLAB_7090)engsqrt(40)

20

bull ldquoConnect Python to Running MATLAB Sessionrdquo

Input Argumentsname mdash Name of shared MATLAB sessioncharacter array

Name of the shared MATLAB session specified as a character array

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

1 API Reference

1-238

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

Output Argumentseng mdash Pythonreg variable for communicating with MATLABMatlabEngine object

Python variable for communicating with MATLAB returned as a MatlabEngine objecteng communicates with a shared MATLAB session that is already running on your localmachine

Limitationsbull Do not connect the engine multiple times to the same shared MATLAB session

See AlsomatlabengineMatlabEngine | matlabenginefind_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabengineconnect_matlab

1-239

matlabenginefind_matlabFind shared MATLAB sessions to connect to MATLAB Engine for Python

Syntaxnames = matlabenginefind_matlab()

Descriptionnames = matlabenginefind_matlab() finds all shared MATLAB sessions on yourlocal machine and returns their names in a tuple Any name in names can be the inputargument to matlabengineconnect_matlab If there are no shared sessionsrunning on your local machine matlabenginefind_matlab returns an emptytuple

Examples

Find Shared MATLAB Sessions

Identify the shared MATLAB sessions running on your local machine and connect to oneof them

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

There are two shared MATLAB sessions running so matlabenginefind_matlabreturns two names in a tuple

Connect to the first shared MATLAB session

1 API Reference

1-240

eng = matlabengineconnect_matlab(MATLAB_6830)

bull ldquoConnect Python to Running MATLAB Sessionrdquo

See Alsomatlabengineconnect_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabenginefind_matlab

1-241

matlabengineFutureResult classPackage matlabengine

Results of asynchronous call to MATLAB function stored in Python object

DescriptionThe FutureResult class stores results of an asynchronous call to a MATLAB function ina Python object

ConstructionThe MATLAB Engine for Python creates a FutureResult object when a MATLABfunction is called asynchronously There is no need to callmatlabengineFutureResult() to create FutureResult objects of your own

Methods

cancel Cancel asynchronous call to MATLAB function from Pythoncancelled Cancellation status of asynchronous call to MATLAB function from Pythondone Completion status of asynchronous call to MATLAB function from Pythonresult Result of asynchronous call to MATLAB function from Python

ExceptionsSyntaxError Python exception syntax error in function

callTypeError Python exception data type of output

argument not supported

1 API Reference

1-242

matlabengineCancelledError MATLAB engine cannot cancel functioncall

matlabengineInterruptedError Function call interruptedmatlabengineMatlabExecutionError

Function call fails to execute

matlabengineRejectedExecutionError

Engine terminated

matlabengineTimeoutError Result cannot be returned within thetimeout period

Examples

Get Result of Asynchronous MATLAB Call from Python

Call the MATLAB sqrt function from Python Set async to True to make the functioncall asynchronously

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquo

See AlsomatlabengineMatlabEngine

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from Pythonrdquo

matlabengineFutureResult class

1-243

Introduced in R2014b

1 API Reference

1-244

cancelClass matlabengineFutureResultPackage matlabengine

Cancel asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancel()

Descriptiontf = FutureResultcancel() cancels a call to a MATLAB function calledasynchronously from Python FutureResultcancel returns True if it successfullycancels the function and False if it cannot cancel the function

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status returned as either True or False The status tf is True ifFutureResultcancel successfully cancels the asynchronous function call and isFalse otherwise

Examples

Cancel an Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval function Thencancel it

cancel

1-245

import matlabengineeng = matlabenginestart_matlab()ret = engeval(while 1 endnargout=0async=True)tf = retcancel()print(tf)

True

See Also

1 API Reference

1-246

cancelledClass matlabengineFutureResultPackage matlabengine

Cancellation status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancelled()

Descriptiontf = FutureResultcancelled() returns the cancellation status of a call to aMATLAB function called asynchronously from Python FutureResultcancelledreturns True if a previous call to FutureResultcancel succeeded and Falseotherwise

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status of an asynchronous function call returned as either True or False

Examples

Check Cancellation Status of Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval functionCancel it and check that the engine stopped the loopimport matlabengineeng = matlabenginestart_matlab()

cancelled

1-247

ret = engeval(while 1 endnargout=0async=True)eval_stop = retcancel()tf = retcancelled()print(tf)

True

See Also

1 API Reference

1-248

doneClass matlabengineFutureResultPackage matlabengine

Completion status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultdone()

Descriptiontf = FutureResultdone() returns the completion status of a MATLAB functioncalled asynchronously from Python FutureResultdone returns True if the functionhas finished and False if it has not finished

Output Argumentstf mdash Completion status of asynchronous function callTrue | False

Completion status of an asynchronous function call returned as either True or False

Examples

Check If Asynchronous Call Finished

Call the MATLAB sqrt function with async = True Check the status of ret to learn ifsqrt is finished

import matlabengineeng = matlabenginestart_matlab()

done

1-249

ret = engsqrt(40async=True)tf = retdone()print(tf)

True

When retdone() returns True then you can call retresult() to return the squareroot

See Also

1 API Reference

1-250

resultClass matlabengineFutureResultPackage matlabengine

Result of asynchronous call to MATLAB function from Python

Syntaxret = FutureResultresult(timeout=None)

Descriptionret = FutureResultresult(timeout=None) returns the actual result of a call to aMATLAB function called asynchronously from Python

Input Argumentstimeout mdash Timeout value in secondsNone (default) | Python float

Timeout value in seconds specified as Python data type float to wait for result of thefunction call If timeout = None the FutureResultresult function waits until thefunction call finishes and then returns the result

Output Argumentsret mdash Result of asynchronous function callPython object

Result of an asynchronous function call returned as a Python object that is the actualoutput argument of a call to a MATLAB function

result

1-251

Examples

Get MATLAB Output Argument from Asynchronous Call

Call the MATLAB sqrt function from Python Set async to True and get the squareroot from the FutureResult object

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

See Also

1 API Reference

1-252

matlabengineMatlabEngine classPackage matlabengine

Python object using MATLAB as computational engine within Python session

DescriptionThe MatlabEngine class uses a MATLAB process as a computational engine for PythonYou can call MATLAB functions as methods of a MatlabEngine object because thefunctions are dynamically invoked when you call them You also can call functions andscripts that you define You can send data to and retrieve data from the MATLABworkspace associated with a MatlabEngine object

ConstructionThe matlabenginestart_matlab function creates a MatlabEngine object each timeit is called There is no need to call matlabengineMatlabEngine() to createMatlabEngine objects of your own

MethodsYou can call any MATLAB function as a method of a MatlabEngine object The enginedynamically invokes a MATLAB function when you call it The syntax shows positionalkeyword and output arguments of a function call

ret =MatlabEnginematlabfunc(argsnargout=1async=Falsestdout=sysstsdoutstderr=sysstderr)

Replace matlabfunc with the name of any MATLAB function (such as isprime orsqrt) Replace args with input arguments for the MATLAB function you call Thekeyword arguments specify

matlabengineMatlabEngine class

1-253

bull The number of output arguments the function returnsbull Whether the engine calls the function asynchronouslybull Where the engine sends standard output and standard error coming from the function

Specify keyword arguments only when specifying values that are not the default valuesshown in the syntax

Input Arguments to MATLAB FunctionArgument Description Python Typeargs Input arguments to

MATLAB function specifiedas positional arguments

Any Python types that theengine can convert toMATLAB types

Keyword Arguments to EngineArgument Description Python Typenargout Number of output

arguments from MATLABfunction

intDefault 1

async Flag to call MATLABfunction asynchronously

boolDefault False

stdout Standard output StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstdout

stderr Standard error StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstderr

1 API Reference

1-254

Output ArgumentsOutput Type Description Required Keyword

ArgumentsPython variable One output argument from

MATLAB functionDefault values

tuple Multiple output argumentsfrom MATLAB function

nargout=n (where n gt 1)

None No output argument fromMATLAB function

nargout=0

FutureResult object A placeholder for outputarguments fromasynchronous call toMATLAB function

async=True

ExceptionsMatlabExecutionError Function call fails to executeRejectedExecutionError MATLAB engine terminatedSyntaxError Syntax error in a function callTypeError Data type of an input or output argument

not supported

Attributesworkspace Python dictionary containing references to

MATLAB variables You can assign data toand get data from a MATLAB variablethrough the workspace The name of eachMATLAB variable you create becomes akey in the workspace dictionary The keysin workspace must be valid MATLABidentifiers (for example you cannot usenumbers as keys)

matlabengineMatlabEngine class

1-255

Examples

Call MATLAB Functions from Python

Call the MATLAB sqrt function from Python using the engine

import matlabengineeng = matlabenginestart_matlab()ret = engsqrt(40)print(ret)

20

Put Array Into MATLAB Workspace

Create an array in Python and put it into the MATLAB workspace

import matlabengineeng = matlabenginestart_matlab()px = englinspace(006281000)

px is a MATLAB array but englinspace returned it to Python To use it in MATLABput the array into the MATLAB workspace

engworkspace[mx] = px

When you add an entry to the engine workspace dictionary you create a MATLABvariable as well The engine converts the data to a MATLAB data type

Get Data from MATLAB Workspace

Get pi from the MATLAB workspace and copy it to a Python variable

import matlabengineeng = matlabenginestart_matlab()engeval(a = pinargout=0)mpi = engworkspace[a]print(mpi)

1 API Reference

1-256

314159265359

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquobull ldquoRedirect Standard Output and Error to Pythonrdquo

See AlsomatlabengineFutureResult | matlabenginestart_matlab

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from PythonrdquoldquoRedirect Standard Output and Error to Pythonrdquo

Introduced in R2014b

matlabengineMatlabEngine class

1-257

matlabenginestart_matlabStart MATLAB Engine for Python

Syntaxeng = matlabenginestart_matlab()

eng = matlabenginestart_matlab(option)eng = matlabenginestart_matlab(async)eng = matlabenginestart_matlab(background)eng = matlabenginestart_matlab( ___ )

Descriptioneng = matlabenginestart_matlab() starts a new MATLAB process and returnsPython variable eng which is a MatlabEngine object for communicating with theMATLAB process

If MATLAB cannot be started the engine raises an EngineError exception

eng = matlabenginestart_matlab(option) uses startup options specified byoption

For example call matlabenginestart_matlab(-desktop) to start the MATLABdesktop from Python

eng = matlabenginestart_matlab(async) starts MATLAB asynchronously ifasync is True

eng = matlabenginestart_matlab(background) starts MATLABasynchronously if background is True

eng = matlabenginestart_matlab( ___ ) can include any of the input argumentsin previous syntaxes

1 API Reference

1-258

Examples

Start MATLAB Engine from Python

Start an engine and a new MATLAB process from the Python command line

import matlabengineeng = matlabenginestart_matlab()

Start Multiple Engines

Start a different MATLAB process from each engine

import matlabengineeng1 = matlabenginestart_matlab()eng2 = matlabenginestart_matlab()

Start MATLAB Desktop with Engine

Start an engine with the MATLAB desktop

import matlabengineeng = matlabenginestart_matlab(-desktop)

You also can start the desktop after you start the engineimport matlabengineeng = matlabenginestart_matlab()engdesktop(nargout=0)

Note You can call MATLAB functions from both the desktop and Python

Start Engine Asynchronously

Start the engine with async=True While MATLAB starts you can enter commands atthe Python command line

matlabenginestart_matlab

1-259

import matlabenginefuture = matlabenginestart_matlab(async=True)eng = futureresult()engsqrt(4)

20

bull ldquoStart and Stop MATLAB Engine for Pythonrdquo

Input Argumentsoption mdash Startup options for MATLAB process-nodesktop (default) | string

Startup options for the MATLAB process specified as a string You can specify multiplestartup options with option

The engine supports -desktop to start MATLAB with the desktop In addition theengine supports all MATLAB startup options except for the options listed inldquoLimitationsrdquo on page 1-261Example matlabenginestart_matlab(-desktop -r format short) startsthe desktop from Python The engine passes -r format short to MATLAB

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

background mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargument background is an alias for async and will be removed in a future releaseExample matlabenginestart_matlab(background=True)

1 API Reference

1-260

Output Argumentseng mdash Python variable for communicating with MATLABMatlabEngine object | FutureResult object

Python variable for communicating with MATLAB returned as a MatlabEngine objectif async or background is set to False or a FutureResult object if async orbackground is set to True

Each time you call matlabenginestart_matlab it starts a new MATLAB process

LimitationsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

See AlsomatlabengineMatlabEngine

TopicsldquoStart and Stop MATLAB Engine for PythonrdquoldquoSpecify Startup OptionsrdquoldquoCommonly Used Startup Optionsrdquo

Introduced in R2014b

matlabenginestart_matlab

1-261

matOpen (C and Fortran)Open MAT-file

C Syntaxinclude mathMATFile matOpen(const char filename const char mode)

Fortran Syntaxinclude mathmwPointer matOpen(filename mode)character() filename mode

Argumentsfilename

Name of file to openmode

File opening mode The following table lists valid values for moder Opens file for reading only determines the current version of the MAT-

file by inspecting the files and preserves the current versionu Opens file for update both reading and writing If the file does not exist

does not create a file (equivalent to the r+ mode of fopen) Determinesthe current version of the MAT-file by inspecting the files and preservesthe current version

w Opens file for writing only deletes previous contents if anyw4 Creates a MAT-file compatible with MATLAB Versions 4 software and

earlierw6 Creates a MAT-file compatible with MATLAB Version 5 (R8) software or

earlier Equivalent to wL mode

1 API Reference

1-262

wL Opens file for writing character data using the default character set foryour system Use MATLAB Version 6 or 65 software to read theresulting MAT-file

If you do not use the wL mode switch MATLAB writes character data tothe MAT-file using Unicodereg character encoding by default

Equivalent to w6 modew7 Creates a MAT-file compatible with MATLAB Version 70 (R14) software

or earlier Equivalent to wz modewz Opens file for writing compressed data By default the MATLAB save

function compresses workspace variables as they are saved to a MAT-fileTo use the same compression ratio when creating a MAT-file with thematOpen function use the wz option

Equivalent to w7 modew73 Creates a MAT-file in an HDF5-based format that can store objects that

occupy more than 2 GB

ReturnsFile handle or NULL in C (0 in Fortran) if the open fails

DescriptionThis routine opens a MAT-file for reading and writing

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1F

matOpen (C and Fortran)

1-263

bull matdemo2F

See AlsomatClose save

Introduced before R2006a

1 API Reference

1-264

matPutVariable (C and Fortran)Array to MAT-file

C Syntaxinclude mathint matPutVariable(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariable(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library along with matGetFp to determine status

matPutVariable (C and Fortran)

1-265

DescriptionThis routine puts an mxArray into a MAT-file

matPutVariable writes mxArray pm to the MAT-file mfp If the mxArray does notexist in the MAT-file the function appends it to the end If an mxArray with the samename exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatGetVariable matGetFp

Introduced before R2006a

1 API Reference

1-266

matPutVariableAsGlobal (C and Fortran)Array to MAT-file as originating from global workspace

C Syntaxinclude mathint matPutVariableAsGlobal(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariableAsGlobal(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library with matGetFp to determine status

matPutVariableAsGlobal (C and Fortran)

1-267

DescriptionThis routine puts an mxArray into a MAT-file matPutVariableAsGlobal is likematPutVariable except that MATLAB software loads the array into the globalworkspace and sets a reference to it in the local workspace If you write to a MATLAB 4format file matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable

matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp If the mxArraydoes not exist in the MAT-file the function appends it to the end If an mxArray with thesame name exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable matGetFp

Introduced before R2006a

1 API Reference

1-268

mexAtExit (C and Fortran)Register function to call when MEX function clears or MATLAB terminates

C Syntaxinclude mexhint mexAtExit(void (ExitFcn)(void))

Fortran Syntaxinclude fintrfhinteger4 mexAtExit(ExitFcn)subroutine ExitFcn()

ArgumentsExitFcn

Pointer to function you want to run on exit

ReturnsAlways returns 0

DescriptionUse mexAtExit to register a function to call just before clearing the MEX function orterminating MATLAB mexAtExit gives your MEX function a chance to perform taskssuch as freeing persistent memory and closing files Other typical tasks include closingstreams or sockets

mexAtExit (C and Fortran)

1-269

Each MEX function can register only one active exit function at a time If you callmexAtExit more than once MATLAB uses the ExitFcn from the more recentmexAtExit call as the exit function

If a MEX function is locked you cannot clear the MEX file Therefore if you attempt toclear a locked MEX file MATLAB does not call the ExitFcn

In Fortran declare the ExitFcn as external in the Fortran routine that callsmexAtExit if it is not within the scope of the file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See AlsomexLock mexUnlock

Introduced before R2006a

1 API Reference

1-270

mexCallMATLAB (C and Fortran)Call MATLAB function user-defined function or MEX file

C Syntaxinclude mexhint mexCallMATLAB(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhinteger4 mexCallMATLAB(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

Argumentsnlhs

Number of output arguments Must be less than or equal to 50plhs

Array of pointers to output argumentsnrhs

Number of input arguments Must be less than or equal to 50prhs

Array of pointers to input argumentsfunctionName

Character string containing name of the MATLAB built-in function operator user-defined function or MEX file you are calling

mexCallMATLAB (C and Fortran)

1-271

If functionName is an operator place the operator inside a pair of single quotes forexample +

Returns0 if successful and a nonzero value if unsuccessful

DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions MATLABoperators user-defined functions or other MEX files Both mexCallMATLAB andmexEvalString execute MATLAB commands Use mexCallMATLAB for returningresults (left side arguments) back to the MEX file The mexEvalString function cannotreturn values to the MEX file

For a complete description of the input and output arguments passed to functionNamesee mexFunction

Error HandlingIf functionName detects an error MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt To trap errors use the mexCallMATLABWithTrapfunction

Limitationsbull Avoid using the mexCallMATLAB function in Simulinkreg S-functions If you do do not

store the resulting plhs mxArray pointers in any S-function block state that persistsafter the MEX function finishes Outputs of mexCallMATLAB have temporary scopeand are automatically destroyed at the end of the MEX function call

bull It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLABFor example this function returns two variables but only assigns one of them a value

function [ab] = foo(c)a = 2c

1 API Reference

1-272

If you then call foo using mexCallMATLAB the unassigned output variable is nowtype mxUNKNOWN_CLASS

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexevalstringcbull mexcallmatlabwithtrapc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxisclassc

See AlsomexFunction mexCallMATLABWithTrap mexEvalString mxDestroyArray

Tipsbull MATLAB allocates dynamic memory to store the arrays in plhs for mexCallMATLAB

MATLAB automatically deallocates the dynamic memory when you exit the MEX fileHowever if heap space is at a premium call mxDestroyArray when you are finishedwith the arrays in plhs

Note The plhs argument for mexCallMATLAB is not the same as the plhs formexFunction Do not destroy an mxArray returned in plhs for mexFunction

mexCallMATLAB (C and Fortran)

1-273

Introduced before R2006a

1 API Reference

1-274

mexCallMATLABWithTrap (C and Fortran)Call MATLAB function user-defined function or MEX-file and capture error information

C Syntaxinclude mexhmxArray mexCallMATLABWithTrap(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhmwPointer mexCallMATLABWithTrap(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

ArgumentsFor more information about arguments see mexCallMATLAB

nlhsNumber of desired output arguments

plhsArray of pointers to output arguments

nrhsNumber of input arguments

prhsArray of pointers to input arguments

functionNameCharacter string containing the name of the MATLAB built-in function operatorfunction or MEX-file that you are calling

mexCallMATLABWithTrap (C and Fortran)

1-275

ReturnsNULL if no error occurred otherwise a pointer to an mxArray of class MException

DescriptionThe mexCallMATLABWithTrap function performs the same function as mexCallMATLABHowever if MATLAB detects an error when executing functionName MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexCallMATLABWithTrap For information about MException see ldquoRespond to anExceptionrdquo

See AlsomexCallMATLAB MException

Introduced in R2008b

1 API Reference

1-276

mexErrMsgIdAndTxt (C and Fortran)Display error message with identifier and return to MATLAB prompt

C Syntaxinclude mexhvoid mexErrMsgIdAndTxt(const char errorid const char errormsg )

Fortran Syntaxinclude fintrfhsubroutine mexErrMsgIdAndTxt(errorid errormsg)character() errorid errormsg

Argumentserrorid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

errormsgString to display In C the string can include conversion specifications used by theANSIreg C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexErrMsgIdAndTxt function writes an error message to the MATLAB windowFor more information see the error function syntax statement using a message

mexErrMsgIdAndTxt (C and Fortran)

1-277

identifier After the error message prints MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt

Calling mexErrMsgIdAndTxt does not clear the MEX file from memory SomexErrMsgIdAndTxt does not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgIdAndTxt automatically frees the allocated memory

Note If you get warnings when using mexErrMsgIdAndTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errorid and errormsg the mexErrMsgIdAndTxt functiondetermines where the error occurred and displays the following information Forexample in the function foo mexErrMsgIdAndTxt displays

Error using foo

If you compile your MEX file with the MinGW-w64 compiler see the limitations withexception handling topic in ldquoTroubleshooting and Limitations Compiling CC++ MEXFiles with MinGW-w64rdquo

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrcbull matrixDividecbull timestwoFbull xtimesyF

1 API Reference

1-278

Validate char Input

The following code snippet checks if input argument prhs[0] is a string If not thecode displays a warning If there is an error reading the input string the code displaysan error message and terminates the MEX file

char bufint buflen

if (mxIsChar(prhs[0])) if (mxGetString(prhs[0] buf buflen) == 0) mexPrintf(The input string is sn buf) else mexErrMsgIdAndTxt(MyProgConvertString Could not convert string data) exit MEX file else mexWarnMsgIdAndTxt(MyProgInputString Input should be a string to print properly)

continue with processing

See Alsoerror | mexWarnMsgIdAndTxt

TopicsldquoMemory Considerations for Class DestructorsrdquoldquoTroubleshooting and Limitations Compiling CC++ MEX Files with MinGW-w64rdquo

Introduced before R2006a

mexErrMsgIdAndTxt (C and Fortran)

1-279

mexErrMsgTxt (C and Fortran)Display error message and return to MATLAB prompt

Note mexErrMsgTxt is not recommended Use mexErrMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexErrMsgTxt(const char errormsg)

Fortran Syntaxsubroutine mexErrMsgTxt(errormsg)character() errormsg

Argumentserrormsg

String containing the error message to display

DescriptionmexErrMsgTxt writes an error message to the MATLAB window After the errormessage prints MATLAB terminates the MEX-file and returns control to the MATLABprompt

Calling mexErrMsgTxt does not clear the MEX-file from memory So mexErrMsgTxtdoes not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgTxt automatically frees the allocated memory

1 API Reference

1-280

Note If you get warnings when using mexErrMsgTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errormsg the mexerrmsgtxt function determines where the erroroccurred and displays the following information If an error labeled Print my errormessage occurs in the function foo mexerrmsgtxt displays

Error using fooPrint my error message

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexErrMsgTxt (C and Fortran)

1-281

mexEvalString (C and Fortran)Execute MATLAB command in caller workspace

C Syntaxinclude mexhint mexEvalString(const char command)

Fortran Syntaxinclude fintrfhinteger4 mexEvalString(command)character() command

Argumentscommand

String containing MATLAB command to execute

Returns0 if successful and 1 if an error occurs

DescriptionCall mexEvalString to invoke a MATLAB command in the workspace of the caller

mexEvalString and mexCallMATLAB both execute MATLAB commands UsemexCallMATLAB for returning results (left side arguments) back to the MEX file ThemexEvalString function cannot return values to the MEX file

1 API Reference

1-282

All arguments that appear to the right of an equal sign in the command string must becurrent variables of the caller workspace

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction For more information see ldquoVariable Namesrdquo

Error HandlingIf command detects an error MATLAB returns control to the MEX-file andmexEvalString returns 1 If you want to trap errors use themexEvalStringWithTrap function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexevalstringc

See AlsomexCallMATLAB mexEvalStringWithTrap

Introduced before R2006a

mexEvalString (C and Fortran)

1-283

mexEvalStringWithTrap (C and Fortran)Execute MATLAB command in caller workspace and capture error information

C Syntaxinclude mexhmxArray mexEvalStringWithTrap(const char command)

Fortran Syntaxinclude fintrfhmwPointer mexEvalStringWithTrap(command)character() command

Argumentscommand

String containing the MATLAB command to execute

ReturnsObject ME of class MException

DescriptionThe mexEvalStringWithTrap function performs the same function as mexEvalStringHowever if MATLAB detects an error when executing command MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexEvalStringWithTrap

1 API Reference

1-284

See AlsomexEvalString MException mexCallMATLAB

Introduced before R2006a

mexEvalStringWithTrap (C and Fortran)

1-285

mexFunction (C and Fortran)Entry point to CC++ or Fortran MEX file

C Syntaxinclude mexhvoid mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

Fortran Syntaxinclude fintrfhsubroutine mexFunction(nlhs plhs nrhs prhs)integer nlhs nrhsmwPointer plhs() prhs()

Argumentsnlhs

Number of expected output mxArraysplhs

Array of pointers to the expected output mxArraysnrhs

Number of input mxArraysprhs

Array of pointers to the input mxArrays Do not modify any prhs values in yourMEX file Changing the data in these read-only mxArrays can produce undesiredside effects

1 API Reference

1-286

DescriptionmexFunction is not a routine you call Rather mexFunction is the name of the gatewayfunction in C (subroutine in Fortran) which every MEX file requires When you invoke aMEX function MATLAB software finds and loads the corresponding MEX file of thesame name MATLAB then searches for a symbol named mexFunction within the MEXfile If it finds one it calls the MEX function using the address of the mexFunctionsymbol MATLAB displays an error message if it cannot find a routine namedmexFunction inside the MEX file

When you invoke a MEX file MATLAB automatically seeds nlhs plhs nrhs and prhswith the calling arguments In the syntax of the MATLAB language functions have thegeneral form

[abc] = fun(def)

where the denotes more items of the same format The abc are left-sideoutput arguments and the def are right-side input arguments The argumentsnlhs and nrhs contain the number of left side and right side arguments respectivelyprhs is an array of mxArray pointers whose length is nrhs plhs is an array whoselength is nlhs where your function must set pointers for the output mxArrays

Note It is possible to return an output value even if nlhs = 0 which corresponds toreturning the result in the ans variable

To experiment with passing input arguments build the mexfunctionc examplefollowing the instructions in ldquoTable of MEX File Source Code Filesrdquo

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctioncbull mexlockfF

mexFunction (C and Fortran)

1-287

See Also

TopicsldquoIntroducing MEX Filesrdquo

Introduced before R2006a

1 API Reference

1-288

mexFunctionName (C and Fortran)Name of current MEX function

C Syntaxinclude mexhconst char mexFunctionName(void)

Fortran Syntaxinclude fintrfhcharacter() mexFunctionName()

ReturnsName of the current MEX function

DescriptionmexFunctionName returns the name of the current MEX function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

Introduced before R2006a

mexFunctionName (C and Fortran)

1-289

mexGet (C)Value of specified graphics property

Note Do not use mexGet Use mxGetProperty instead

C Syntaxinclude mexhconst mxArray mexGet(double handle const char property)

Argumentshandle

Handle to a particular graphics objectproperty

Graphics property

ReturnsValue of the specified property in the specified graphics object on success Returns NULLon failure Do not modify the return argument from mexGet Changing the data in aconst (read-only) mxArray can produce undesired side effects

DescriptionCall mexGet to get the value of the property of a certain graphics object mexGet is theAPI equivalent of the MATLAB get function To set a graphics property value callmexSet

1 API Reference

1-290

See AlsomxGetProperty mxSetProperty

mexGet (C)

1-291

mexGetVariable (C and Fortran)Copy of variable from specified workspace

C Syntaxinclude mexhmxArray mexGetVariable(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariable(workspace varname)character() workspace varname

Argumentsworkspace

Specifies where mexGetVariable searches for array varname The possible valuesarebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of the variable to copy

ReturnsCopy of the variable on success Returns NULL in C (0 on Fortran) on failure A commoncause of failure is specifying a variable that is not currently in the workspace Perhapsthe variable was in the workspace at one time but has since been cleared

1 API Reference

1-292

DescriptionCall mexGetVariable to get a copy of the specified variable The returned mxArraycontains a copy of all the data and characteristics that the variable had in the otherworkspace Modifications to the returned mxArray do not affect the variable in theworkspace unless you write the copy back to the workspace with mexPutVariable

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

See AlsomexGetVariablePtr mexPutVariable mxDestroyArray

mexGetVariable (C and Fortran)

1-293

mexGetVariablePtr (C and Fortran)Read-only pointer to variable from another workspace

C Syntaxinclude mexhconst mxArray mexGetVariablePtr(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariablePtr(workspace varname)character() workspace varname

Argumentsworkspace

Specifies which workspace you want mexGetVariablePtr to search The possiblevalues arebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of a variable in another workspace This is a variable name not an mxArraypointer

ReturnsRead-only pointer to the mxArray on success Returns NULL in C (0 in Fortran) onfailure

1 API Reference

1-294

DescriptionCall mexGetVariablePtr to get a read-only pointer to the specified variable varnameinto your MEX-file workspace This command is useful for examining an mxArrays dataand characteristics If you want to change data or characteristics use mexGetVariable(along with mexPutVariable) instead of mexGetVariablePtr

If you simply want to examine data or characteristics mexGetVariablePtr offerssuperior performance because the caller wants to pass only a pointer to the array

See AlsomexGetVariable

Introduced before R2006a

mexGetVariablePtr (C and Fortran)

1-295

mexIsLocked (C and Fortran)Determine if MEX-file is locked

C Syntaxinclude mexhbool mexIsLocked(void)

Fortran Syntaxinclude fintrfhinteger4 mexIsLocked()

ReturnsLogical 1 (true) if the MEX-file is locked logical 0 (false) if the file is unlocked

DescriptionCall mexIsLocked to determine if the MEX-file is locked By default MEX-files areunlocked meaning you can clear the MEX-file at any time

To unlock a MEX-file call mexUnlock

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-296

See AlsomexLock mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexIsLocked (C and Fortran)

1-297

mexLock (C and Fortran)Prevent clearing MEX-file from memory

C Syntaxinclude mexhvoid mexLock(void)

Fortran Syntaxinclude fintrfhsubroutine mexLock()

DescriptionBy default MEX files are unlocked meaning you can clear them at any time CallmexLock to prohibit clearing a MEX file

To unlock a MEX file call mexUnlock Do not use the munlock function

mexLock increments a lock count If you call mexLock n times call mexUnlock n timesto unlock your MEX file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-298

See AlsomexIsLocked mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexLock (C and Fortran)

1-299

mexMakeArrayPersistent (C and Fortran)Make array persist after MEX file completes

C Syntaxinclude mexhvoid mexMakeArrayPersistent(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mexMakeArrayPersistent(pm)mwPointer pm

Argumentspm

Pointer to an mxArray created by an mxCreate function

DescriptionBy default an mxArray allocated by an mxCreate function is not persistent TheMATLAB memory management facility automatically frees a nonpersistent mxArraywhen the MEX function finishes If you want the mxArray to persist through multipleinvocations of the MEX function call the mexMakeArrayPersistent function

Do not assign an array created with the mexMakeArrayPersistent function to theplhs output argument of a MEX file

Note If you create a persistent mxArray you are responsible for destroying it usingmxDestroyArray when the MEX file is cleared If you do not destroy a persistentmxArray MATLAB leaks memory See mexAtExit to see how to register a function that

1 API Reference

1-300

gets called when the MEX file is cleared See mexLock to see how to lock your MEX fileso that it is never cleared

See AlsomexAtExit mxDestroyArray mexLock mexMakeMemoryPersistent and themxCreate functions

Introduced before R2006a

mexMakeArrayPersistent (C and Fortran)

1-301

mexMakeMemoryPersistent (C and Fortran)Make memory allocated by MATLAB software persist after MEX-function completes

C Syntaxinclude mexhvoid mexMakeMemoryPersistent(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mexMakeMemoryPersistent(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of memory allocated by one of the MATLAB memoryallocation routines

DescriptionBy default memory allocated by MATLAB is nonpersistent so it is freed automaticallywhen the MEX function finishes If you want the memory to persist callmexMakeMemoryPersistent

Note If you create persistent memory you are responsible for freeing it when the MEXfunction is cleared If you do not free the memory MATLAB leaks memory To freememory use mxFree See mexAtExit to see how to register a function that gets calledwhen the MEX function is cleared See mexLock to see how to lock your MEX function sothat it is never cleared

1 API Reference

1-302

See AlsomexAtExit mexLock mexMakeArrayPersistent mxCalloc mxFree mxMallocmxRealloc

Introduced before R2006a

mexMakeMemoryPersistent (C and Fortran)

1-303

mexPrintf (C and Fortran)ANSI C PRINTF-style output routine

C Syntaxinclude mexhint mexPrintf(const char message )

Fortran Syntaxinclude fintrfhinteger4 mexPrintf(message)character() message

Argumentsmessage

String to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

ReturnsNumber of characters printed including characters specified with backslash codes suchas n and b

1 API Reference

1-304

DescriptionThis routine prints a string on the screen and in the diary (if the diary is in use) Itprovides a callback to the standard C printf routine already linked inside MATLABsoftware which avoids linking the entire stdio library into your MEX file

In a C MEX file call mexPrintf instead of printf to display a string

Note If you want the literal in your message use in the message string since hasspecial meaning to printf Failing to do so causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See Alsosprintf mexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexPrintf (C and Fortran)

1-305

mexPutVariable (C and Fortran)Array from MEX-function into specified workspace

C Syntaxinclude mexhint mexPutVariable(const char workspace const char varname const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mexPutVariable(workspace varname pm)character() workspace varnamemwPointer pm

Argumentsworkspace

Specifies scope of the array you are copying Values for workspace arebase Copy mxArray to the base workspacecaller Copy mxArray to the caller workspaceglobal Copy mxArray to the list of global variables

varnameName of mxArray in the workspace

pmPointer to the mxArray

1 API Reference

1-306

Returns0 on success 1 on failure A possible cause of failure is that pm is NULL in C (0 inFortran)

DescriptionCall mexPutVariable to copy the mxArray at pointer pm from your MEX-function intothe specified workspace MATLAB software gives the name varname to the copiedmxArray in the receiving workspace

mexPutVariable makes the array accessible to other entities such as MATLAB user-defined functions or other MEX-functions

If a variable of the same name exists in the specified workspace mexPutVariableoverwrites the previous contents of the variable with the contents of the new mxArrayFor example suppose the MATLAB workspace defines variable Peaches as

Peaches1 2 3 4

and you call mexPutVariable to copy Peaches into the same workspace

mexPutVariable(base Peaches pm)

The value passed by mexPutVariable replaces the old value of Peaches

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

mexPutVariable (C and Fortran)

1-307

See AlsomexGetVariable

1 API Reference

1-308

mexSet (C)Set value of specified graphics property

Note Do not use mexSet Use mxSetProperty instead

C Syntaxinclude mexhint mexSet(double handle const char property mxArray value)

Argumentshandle

Handle to a particular graphics objectproperty

String naming a graphics propertyvalue

Pointer to an mxArray holding the new value to assign to the property

Returns0 on success 1 on failure Possible causes of failure include

bull Specifying a nonexistent propertybull Specifying an illegal value for that property for example specifying a string value for

a numerical property

mexSet (C)

1-309

DescriptionCall mexSet to set the value of the property of a certain graphics object mexSet is theAPI equivalent of the MATLAB set function To get the value of a graphics property callmexGet

See AlsomxGetProperty mxSetProperty

1 API Reference

1-310

mexSetTrapFlag (C and Fortran)Control response of MEXCALLMATLAB to errors

C Syntaxinclude mexhvoid mexSetTrapFlag(int trapflag)

Note mexSetTrapFlag will be removed in a future version UsemexCallMATLABWithTrap instead

Fortran Syntaxsubroutine mexSetTrapFlag(trapflag)integer4 trapflag

Argumentstrapflag

Control flag Possible values are0 On error control returns to the MATLAB prompt1 On error control returns to your MEX-file

DescriptionCall mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB

If you do not call mexSetTrapFlag then whenever MATLAB detects an error in a call tomexCallMATLAB MATLAB automatically terminates the MEX-file and returns controlto the MATLAB prompt Calling mexSetTrapFlag with trapflag set to 0 is equivalentto not calling mexSetTrapFlag at all

mexSetTrapFlag (C and Fortran)

1-311

If you call mexSetTrapFlag and set the trapflag to 1 then whenever MATLABdetects an error in a call to mexCallMATLAB MATLAB does not automatically terminatethe MEX-file Rather MATLAB returns control to the line in the MEX-file immediatelyfollowing the call to mexCallMATLAB The MEX-file is then responsible for taking anappropriate response to the error

If you call mexSetTrapFlag the value of the trapflag you set remains in effect untilthe next call to mexSetTrapFlag within that MEX-file or if there are no more calls tomexSetTrapFlag until the MEX-file exits If a routine defined in a MEX-file callsanother MEX-file MATLAB

1 Saves the current value of the trapflag in the first MEX-file2 Calls the second MEX-file with the trapflag initialized to 0 within that file3 Restores the saved value of trapflag in the first MEX-file when the second MEX-

file exits

See AlsomexCallMATLAB mexCallMATLABWithTrap mexAtExit mexErrMsgTxt

Introduced in R2008b

1 API Reference

1-312

mexUnlock (C and Fortran)Allow clearing MEX-file from memory

C Syntaxinclude mexhvoid mexUnlock(void)

Fortran Syntaxinclude fintrfhsubroutine mexUnlock()

DescriptionBy default MEX-files are unlocked meaning you can clear them at any time CallingmexLock locks a MEX-file so that you cannot clear it from memory Call mexUnlock toremove the lock

mexLock increments a lock count If you called mexLock n times call mexUnlock ntimes to unlock your MEX-file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

mexUnlock (C and Fortran)

1-313

See AlsomexIsLocked mexLock mexMakeArrayPersistent mexMakeMemoryPersistentclear

1 API Reference

1-314

mexWarnMsgIdAndTxt (C and Fortran)Warning message with identifier

C Syntaxinclude mexhvoid mexWarnMsgIdAndTxt(const char warningid const char warningmsg )

Fortran Syntaxinclude fintrfhsubroutine mexWarnMsgIdAndTxt(warningid warningmsg)character() warningid warningmsg

Argumentswarningid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

warningmsgString to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexWarnMsgIdAndTxt function writes a warning message to the MATLABcommand prompt The warnings displayed are the same as warnings issued by the

mexWarnMsgIdAndTxt (C and Fortran)

1-315

MATLAB warning function To control the information displayed or suppressed call thewarning function with the desired settings before calling your MEX-file

Unlike mexErrMsgIdAndTxt calling mexWarnMsgIdAndTxt does not terminate theMEX-file

See AlsomexErrMsgIdAndTxt warning

Introduced before R2006a

1 API Reference

1-316

mexWarnMsgTxt (C and Fortran)Warning message

Note mexWarnMsgTxt is not recommended Use mexWarnMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexWarnMsgTxt(const char warningmsg)

Fortran Syntaxsubroutine mexWarnMsgTxt(warningmsg)character() warningmsg

Argumentswarningmsg

String containing the warning message to display

DescriptionmexWarnMsgTxt causes MATLAB software to display the contents of warningmsgmexWarnMsgTxt does not terminate the MEX-file

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexWarnMsgTxt (C and Fortran)

1-317

mwIndex (C and Fortran)Type for index values

DescriptionmwIndex is a type that represents index values such as indices into arrays Use thisfunction for cross-platform flexibility By default mwIndex is equivalent to int in CWhen using the mex -largeArrayDims switch mwIndex is equivalent to size_t in CIn Fortran mwIndex is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwIndex is a preprocessor macro The Fortran header file containing thistype is

include fintrfh

See Alsomex mwSize mwSignedIndex

Introduced before R2006a

1 API Reference

1-318

mwPointer (Fortran)Platform-independent pointer type

DescriptionmwPointer is a preprocessor macro that declares the appropriate Fortran typerepresenting a pointer to an mxArray or to other data that is not of a native Fortrantype such as memory allocated by mxMalloc On 32-bit platforms the Fortran type thatrepresents a pointer is INTEGER4 on 64-bit platforms it is INTEGER8 The Fortranpreprocessor translates mwPointer to the Fortran declaration that is appropriate for theplatform on which you compile your file

If your Fortran compiler supports preprocessing you can use mwPointer to declarefunctions arguments and variables that represent pointers If you cannot usemwPointer ensure that your declarations have the correct size for the platform on whichyou are compiling Fortran code

The Fortran header file containing this type is

include fintrfh

ExamplesThis example declares the arguments for mexFunction in a Fortran MEX file

subroutine mexFunction(nlhs plhs nrhs prhs)mwPointer plhs() prhs()integer nlhs nrhs

For additional examples see the Fortran files with names ending in F in thematlabrootexternexamples folder

Introduced in R2006a

mwPointer (Fortran)

1-319

mwSignedIndex (C and Fortran)Signed integer type for size values

DescriptionmwSignedIndex is a signed integer type that represents size values such as arraydimensions Use this function for cross-platform flexibility By default mwSignedIndexis equivalent to ptrdiff_t in C++ In Fortran mwSignedIndex is similarly equivalentto INTEGER4 or INTEGER8 based on platform and compilation flags

The C header file containing this type is

include matrixh

The Fortran header file containing this type is

include fintrfh

See AlsomwSize mwIndex

Introduced in R2009a

1 API Reference

1-320

mwSize (C and Fortran)Type for size values

DescriptionmwSize is a type that represents size values such as array dimensions Use this functionfor cross-platform flexibility By default mwSize is equivalent to size_t in C mwSize isan unsigned type meaning a nonnegative integer

When using the mex -compatibleArrayDims switch mwSize is equivalent to int in CIn Fortran mwSize is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwSize is a preprocessor macro The Fortran header file containing this typeis

include fintrfh

See Alsomex mwIndex mwSignedIndex

Introduced before R2006a

mwSize (C and Fortran)

1-321

mxAddField (C and Fortran)Add field to structure array

C Syntaxinclude matrixhextern int mxAddField(mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxAddField(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of the field you want to add

ReturnsField number on success or -1 if inputs are invalid or an out-of-memory conditionoccurs

1 API Reference

1-322

DescriptionCall mxAddField to add a field to a structure array Create the values with themxCreate functions and use mxSetFieldByNumber to set the individual values for thefield

See AlsomxRemoveField mxSetFieldByNumber

Introduced before R2006a

mxAddField (C and Fortran)

1-323

mxArray (C)Type for MATLAB array

DescriptionThe fundamental type underlying MATLAB data For information on how the MATLABarray works with MATLAB-supported variables see ldquoMATLAB Datardquo

mxArray is a C language opaque type

All C MEX-files start with a gateway routine called mexFunction which requiresmxArray for both input and output parameters For information about the C MEX-filegateway routine see ldquoComponents of MEX Filerdquo

Once you have MATLAB data in your MEX-file use functions in the Matrix Library tomanipulate the data and functions in the MEX Library to perform operations in theMATLAB environment You use mxArray to pass data to and from these functions

Use any of the mxCreate functions to create data and the correspondingmxDestroyArray function to free memory

The header file containing this type is

include matrixh

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomexFunction mxClassID mxCreateDoubleMatrix mxCreateNumericArraymxCreateString mxDestroyArray mxGetData mxSetData

1 API Reference

1-324

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquobull For troubleshooting mxArray errors in other MathWorks products search the

documentation for that product or see MATLAB Answerstrade topic Subscripting intoan mxArray is not supported

Introduced before R2006a

mxArray (C)

1-325

mxArrayToString (C)Array to string

C Syntaxinclude matrixhchar mxArrayToString(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string Returns NULL on failure Possible reasons for failure include out ofmemory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToString to copy the character data of an mxCHAR array into a C-stylestring The C-style string is always terminated with a NULL character and stored incolumn-major order

If the array contains multiple rows the rows are copied column-wise into a single array

This function is similar to mxGetString except that

bull It does not require the length of the string as an inputbull It supports both multi-byte and single-byte encoded characters On Windows and

Linuxreg platforms the default encoding is specified by the user locale setting

1 API Reference

1-326

mxArrayToString does not free the dynamic memory that the char pointer points toTherefore you typically free the C-style string (using mxFree) immediately after youhave finished using it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxArrayToUTF8String mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetString

Introduced before R2006a

mxArrayToString (C)

1-327

mxArrayToUTF8String (C)Array to string in UTF-8 encoding

C Syntaxinclude matrixhchar mxArrayToUTF8String(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string in UTF-8 encoding Returns NULL on failure Possible reasons for failureinclude out of memory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToUTF8String to copy the character data of an mxCHAR array into a C-style string The data is stored in column-major order If the array contains multiplerows the rows are copied column-wise into a single array

mxArrayToUTF8String does not free the dynamic memory that the char pointer pointsto Use mxFree to free memory

See AlsomxArrayToString mxFree mxCreateCharArray mxCreateString mxGetString

1 API Reference

1-328

Introduced in R2015a

mxArrayToUTF8String (C)

1-329

mxAssert (C)Check assertion value for debugging purposes

C Syntaxinclude matrixhvoid mxAssert(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionLike the ANSI C assert macro mxAssert checks the value of an assertion andcontinues execution only if the assertion holds If expr evaluates to logical 1 (true)mxAssert does nothing If expr evaluates to logical 0 (false) mxAssert terminates theMEX file and prints an error to the MATLAB command window The error contains theexpression of the failed assertion the file name and line number where the failedassertion occurred and the error_message text The error_message allows you tospecify a better description of why the assertion failed Use an empty string if you do notwant a description to follow the failed assertion message

The mex script turns off these assertions when building optimized MEX functions so useassertions for debugging purposes only To use mxAssert build the MEX file using themex -g filename syntax

Assertions are a way of maintaining internal consistency of logic Use them to keepyourself from misusing your own code and to prevent logical errors from propagating

1 API Reference

1-330

before they are caught Do not use assertions to prevent users of your code from misusingit

Assertions can be taken out of your code by the C preprocessor You can use these checksduring development and then remove them when the code works properly letting youuse them for troubleshooting during development without slowing down the finalproduct

See AlsomxAssertS mexErrMsgIdAndTxt

Introduced before R2006a

mxAssert (C)

1-331

mxAssertS (C)Check assertion value without printing assertion text

C Syntaxinclude matrixhvoid mxAssertS(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionmxAssertS is like mxAssert except mxAssertS does not print the text of the failedassertion

See AlsomxAssert

Introduced before R2006a

1 API Reference

1-332

mxCalcSingleSubscript (C and Fortran)Offset from first element to desired element

C Syntaxinclude matrixhmwIndex mxCalcSingleSubscript(const mxArray pm mwSize nsubs mwIndex subs)

Fortran Syntaxinclude fintrfhmwIndex mxCalcSingleSubscript(pm nsubs subs)mwPointer pmmwSize nsubsmwIndex subs

Argumentspm

Pointer to an mxArraynsubs

Number of elements in the subs array Typically you set nsubs equal to the numberof dimensions in the mxArray that pm points to

subsAn array of integers Each value in the array specifies that dimensions subscript InC syntax the value in subs[0] specifies the row subscript and the value insubs[1] specifies the column subscript Use zero-based indexing for subscripts Forexample to express the starting element of a two-dimensional mxArray in subs setsubs[0] to 0 and subs[1] to 0

In Fortran syntax the value in subs(1) specifies the row subscript and the value insubs(2) specifies the column subscript Use 1-based indexing for subscripts For

mxCalcSingleSubscript (C and Fortran)

1-333

example to express the starting element of a two-dimensional mxArray in subs setsubs(1) to 1 and subs(2) to 1

ReturnsThe number of elements or index between the start of the mxArray and the specifiedsubscript This number is the linear index equivalent of the subscripts Many MatrixLibrary routines (for example mxGetField) require an index as an argument

If subs describes the starting element of an mxArray mxCalcSingleSubscriptreturns 0 If subs describes the final element of an mxArray mxCalcSingleSubscriptreturns N-1 (where N is the total number of elements)

DescriptionCall mxCalcSingleSubscript to determine how many elements there are between thebeginning of the mxArray and a given element of that mxArray The function convertssubscripts to linear indices

For example given a subscript like (57) mxCalcSingleSubscript returns thedistance from the first element of the array to the (57) element Remember that themxArray data type internally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have For examplesshowing the internal representation see ldquoData Storagerdquo

Avoid using mxCalcSingleSubscript to traverse the elements of an array In C it ismore efficient to find the starting address of the array and then use pointerautoincrementing to access successive elements For example to find the startingaddress of a numerical array call mxGetPr or mxGetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

1 API Reference

1-334

See AlsomxGetCell mxSetCell

Introduced before R2006a

mxCalcSingleSubscript (C and Fortran)

1-335

mxCalloc (C and Fortran)Allocate dynamic memory for array initialized to 0 using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxCalloc(mwSize n mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxCalloc(n size)mwSize n size

Argumentsn

Number of elements to allocate This must be a nonnegative numbersize

Number of bytes per element (The C sizeof operator calculates the number of bytesper element)

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxCalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxCalloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-336

DescriptionmxCalloc allocates contiguous heap space sufficient to hold n elements of size byteseach and initializes this newly allocated memory to 0 Use mxCalloc instead of theANSI C calloc function to allocate memory in MATLAB applications

In MEX files but not MAT or engine applications mxCalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatacbull phonebookcbull revordc

mxCalloc (C and Fortran)

1-337

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxsetdimensionsc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistentmxDestroyArray mxFree mxMalloc mxRealloc

Introduced before R2006a

1 API Reference

1-338

mxChar (C)Type for string array

DescriptionMATLAB stores an mxArray string as type mxChar to represent the C-style char typeMATLAB uses 16-bit unsigned integer character encoding for Unicode characters

The header file containing this type is

include matrixh

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxcreatecharmatrixfromstrc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCharArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

mxChar (C)

1-339

Introduced before R2006a

1 API Reference

1-340

mxClassID (C)Enumerated value identifying class of array

C Syntaxtypedef enum mxUNKNOWN_CLASS mxCELL_CLASS mxSTRUCT_CLASS mxLOGICAL_CLASS mxCHAR_CLASS mxVOID_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_CLASS

Undetermined class You cannot specify this category for an mxArray however ifmxGetClassID cannot identify the class it returns this value

mxCELL_CLASSIdentifies a cell mxArray

mxSTRUCT_CLASSIdentifies a structure mxArray

mxClassID (C)

1-341

mxLOGICAL_CLASSIdentifies a logical mxArray an mxArray of mxLogical data

mxCHAR_CLASSIdentifies a string mxArray an mxArray whose data is represented as mxChar

mxVOID_CLASSReserved

mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

1 API Reference

1-342

mxINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxFUNCTION_CLASSIdentifies a function handle mxArray

DescriptionVarious Matrix Library functions require or return an mxClassID argumentmxClassID identifies how the mxArray represents its data elements

The following table shows MATLAB types with their equivalent C types Use the typefrom the right-most column for reading mxArrays with the mxClassID value shown inthe left columnMATLAB Primitive Types

mxClassID Value MATLAB Type MEX Type C Primitive TypemxINT8_CLASS int8 int8_T char bytemxUINT8_CLASS uint8 uint8_T unsigned char bytemxINT16_CLASS int16 int16_T shortmxUINT16_CLASS uint16 uint16_T unsigned shortmxINT32_CLASS int32 int32_T intmxUINT32_CLASS uint32 uint32_T unsigned intmxINT64_CLASS int64 int64_T long longmxUINT64_CLASS uint64 uint64_T unsigned long longmxSINGLE_CLASS single float floatmxDOUBLE_CLASS double double double

mxClassID (C)

1-343

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetClassID mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-344

mxClassIDFromClassName (Fortran)Identifier corresponding to class

Fortran Syntaxinclude fintrfhinteger4 mxClassIDFromClassName(classname)character() classname

Argumentsclassname

character array specifying a MATLAB class name For a list of valid classnamechoices see the mxIsClass reference page

ReturnsNumeric identifier used internally by MATLAB software to represent the MATLAB classclassname Returns unknown if classname is not a recognized MATLAB class

DescriptionUse mxClassIDFromClassName to obtain an identifier for any MATLAB class Thisfunction is most commonly used to provide a classid argument tomxCreateNumericArray and mxCreateNumericMatrix

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matsqint8F

mxClassIDFromClassName (Fortran)

1-345

See AlsomxGetClassName mxCreateNumericArray mxCreateNumericMatrix mxIsClass

Introduced before R2006a

1 API Reference

1-346

mxComplexity (C)Flag specifying whether array has imaginary components

C Syntaxtypedef enum mxComplexity mxREAL=0 mxCOMPLEX

ConstantsmxREAL

Identifies an mxArray with no imaginary componentsmxCOMPLEX

Identifies an mxArray with imaginary components

DescriptionVarious Matrix Library functions require an mxComplexity argument You can set anmxComplex argument to either mxREAL or mxCOMPLEX

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

See AlsomxCreateNumericArray mxCreateDoubleMatrix mxCreateSparse

mxComplexity (C)

1-347

Introduced before R2006a

1 API Reference

1-348

mxCopyCharacterToPtr (Fortran)CHARACTER values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyCharacterToPtr(y px n)character() ymwPointer pxmwSize n

Argumentsy

character Fortran arraypx

Pointer to character or name arrayn

Number of elements to copy

DescriptionmxCopyCharacterToPtr copies n character values from the Fortran characterarray y into the MATLAB character vector pointed to by px This subroutine is essentialfor copying character data between MATLAB pointer arrays and ordinary Fortrancharacter arrays

See AlsomxCopyPtrToCharacter mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

mxCopyCharacterToPtr (Fortran)

1-349

Introduced before R2006a

1 API Reference

1-350

mxCopyComplex16ToPtr (Fortran)COMPLEX16 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex16ToPtr(y pr pi n)complex16 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX16 Fortran arraypr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex16ToPtr copies n COMPLEX16 values from the Fortran COMPLEX16array y into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex16ToPtr (Fortran)

1-351

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyPtrToComplex16 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-352

mxCopyComplex8ToPtr (Fortran)COMPLEX8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex8ToPtr(y pr pi n)complex8 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX8 Fortran arraypr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex8ToPtr copies n COMPLEX8 values from the Fortran COMPLEX8 arrayy into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex8ToPtr (Fortran)

1-353

See AlsomxCopyPtrToComplex8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-354

mxCopyInteger1ToPtr (Fortran)INTEGER1 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger1ToPtr(y px n)integer1 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER1 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger1ToPtr copies n INTEGER1 values from the Fortran INTEGER1 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyInteger1ToPtr (Fortran)

1-355

bull matsqint8F

See AlsomxCopyPtrToInteger1 mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-356

mxCopyInteger2ToPtr (Fortran)INTEGER2 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger2ToPtr(y px n)integer2 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER2 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger2ToPtr copies n INTEGER2 values from the Fortran INTEGER2 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger2 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger2ToPtr (Fortran)

1-357

Introduced before R2006a

1 API Reference

1-358

mxCopyInteger4ToPtr (Fortran)INTEGER4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger4ToPtr(y px n)integer4 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER4 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger4ToPtr copies n INTEGER4 values from the Fortran INTEGER4 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger4 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger4ToPtr (Fortran)

1-359

Introduced before R2006a

1 API Reference

1-360

mxCopyPtrToCharacter (Fortran)CHARACTER values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToCharacter(px y n)mwPointer pxcharacter() ymwSize n

Argumentspx

Pointer to character or name arrayy

character Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToCharacter copies n character values from the MATLAB array pointedto by px into the Fortran character array y This subroutine is essential for copyingcharacter data from MATLAB pointer arrays into ordinary Fortran character arrays

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxCopyPtrToCharacter (Fortran)

1-361

See AlsomxCopyCharacterToPtr mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

Introduced before R2006a

1 API Reference

1-362

mxCopyPtrToComplex16 (Fortran)COMPLEX16 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex16(pr pi y n)mwPointer pr picomplex16 y(n)mwSize n

Argumentspr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayy

COMPLEX16 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex16 copies n COMPLEX16 values from the MATLAB arrayspointed to by pr and pi into the Fortran COMPLEX16 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex16 (Fortran)

1-363

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyComplex16ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-364

mxCopyPtrToComplex8 (Fortran)COMPLEX8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex8(pr pi y n)mwPointer pr picomplex8 y(n)mwSize n

Argumentspr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayy

COMPLEX8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex8 copies n COMPLEX8 values from the MATLAB arrays pointedto by pr and pi into the Fortran COMPLEX8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex8 (Fortran)

1-365

See AlsomxCopyComplex8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-366

mxCopyPtrToInteger1 (Fortran)INTEGER1 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger1(px y n)mwPointer pxinteger1 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER1 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger1 copies n INTEGER1 values from the MATLAB array pointed toby px either a real or imaginary array into the Fortran INTEGER1 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyPtrToInteger1 (Fortran)

1-367

bull matsqint8F

See AlsomxCopyInteger1ToPtr mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-368

mxCopyPtrToInteger2 (Fortran)INTEGER2 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger2(px y n)mwPointer pxinteger2 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER2 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger2 copies n INTEGER2 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER2 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger2ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger2 (Fortran)

1-369

Introduced before R2006a

1 API Reference

1-370

mxCopyPtrToInteger4 (Fortran)INTEGER4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger4(px y n)mwPointer pxinteger4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger4 copies n INTEGER4 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger4ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger4 (Fortran)

1-371

Introduced before R2006a

1 API Reference

1-372

mxCopyPtrToPtrArray (Fortran)Pointer values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToPtrArray(px y n)mwPointer pxmwPointer y(n)mwSize n

Argumentspx

Pointer to pointer arrayy

Fortran array of mwPointer valuesn

Number of pointers to copy

DescriptionmxCopyPtrToPtrArray copies n pointers from the MATLAB array pointed to by px intothe Fortran array y This subroutine is essential for copying the output of matGetDirinto an array of pointers After calling this function each element of y contains a pointerto a string You can convert these strings to Fortran character arrays by passing eachelement of y as the first argument to mxCopyPtrToCharacter

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToPtrArray (Fortran)

1-373

bull matdemo2F

See AlsomatGetDir mxCopyPtrToCharacter

Introduced before R2006a

1 API Reference

1-374

mxCopyPtrToReal4 (Fortran)REAL4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal4(px y n)mwPointer pxreal4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a single-precision MATLAB arrayy

REAL4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal4 copies n REAL4 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToReal4 (Fortran)

1-375

See AlsomxCopyReal4ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-376

mxCopyPtrToReal8 (Fortran)REAL8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal8(px y n)mwPointer pxreal8 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a double-precision MATLAB arrayy

REAL8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal8 copies n REAL8 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToReal8 (Fortran)

1-377

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyReal8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-378

mxCopyReal4ToPtr (Fortran)REAL4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal4ToPtr(y px n)real4 y(n)mwPointer pxmwSize n

Argumentsy

REAL4 Fortran arraypx

Pointer to the real or imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal4ToPtr copies n REAL4 values from the Fortran REAL4 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyReal4ToPtr (Fortran)

1-379

See AlsomxCopyPtrToReal4 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-380

mxCopyReal8ToPtr (Fortran)REAL8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal8ToPtr(y px n)real8 y(n)mwPointer pxmwSize n

Argumentsy

REAL8 Fortran arraypx

Pointer to the real or imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal8ToPtr copies n REAL8 values from the Fortran REAL8 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyReal8ToPtr (Fortran)

1-381

bull matdemo1F

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyPtrToReal8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-382

mxCreateCellArray (C and Fortran)N-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the created cell For example to create a three-dimensionalcell mxArray set ndim to 3

dimsDimensions array Each element in the dimensions array contains the size of themxArray in that dimension For example in C setting dims[0] to 5 and dims[1] to7 establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellArray (C and Fortran)

1-383

DescriptionUse mxCreateCellArray to create a cell mxArray with size defined by ndim and dimsFor example in C to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims[0] = 4 dims[1] = 8 dims[2] = 7

In Fortran to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims(1) = 4 dims(2) = 8 dims(3) = 7

The created cell mxArray is unpopulated mxCreateCellArray initializes each cell toNULL To put data into a cell call mxSetCell

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateCellMatrix mxGetCell mxSetCell mxIsCell

Introduced before R2006a

1 API Reference

1-384

mxCreateCellMatrix (C and Fortran)2-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellMatrix(mwSize m mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellMatrix(m n)mwSize m n

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellMatrix (C and Fortran)

1-385

DescriptionUse mxCreateCellMatrix to create an m-by-n two-dimensional cell mxArray Thecreated cell mxArray is unpopulated mxCreateCellMatrix initializes each cell to NULLin C (0 in Fortran) To put data into cells call mxSetCell

mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only butmxCreateCellArray can create mxArrays having any number of dimensions greaterthan 1

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray

Introduced before R2006a

1 API Reference

1-386

mxCreateCharArray (C and Fortran)N-D mxChar array

C Syntaxinclude matrixhmxArray mxCreateCharArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the mxArray specified as a positive number If you specify0 1 or 2 mxCreateCharArray creates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray The dims array must have at least ndimelements

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateCharArray (C and Fortran)

1-387

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateCharArray to create an N-dimensional mxChar array The createdmxArray is unpopulated that is mxCreateCharArray initializes each cell to NULL in C(0 in Fortran)

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateCharMatrixFromStrings mxCreateString

1 API Reference

1-388

mxCreateCharMatrixFromStrings (C and Fortran)2-D mxChar array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateCharMatrixFromStrings(mwSize m const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharMatrixFromStrings(m str)mwSize mcharacter() str(m)

Argumentsm

Number of rows in the mxArray The value you specify for m is the number of stringsin str

strIn C an array of strings containing at least m strings In Fortran a characternarray of size m where each element of the array is n bytes

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray Another possible reasonfor failure is that str contains fewer than m strings

mxCreateCharMatrixFromStrings (C and Fortran)

1-389

DescriptionUse mxCreateCharMatrixFromStrings to create a two-dimensional mxArray whereeach row is initialized to a string from str In C the created mxArray has dimensions m-by-max where max is the length of the longest string in str In Fortran the createdmxArray has dimensions m-by-n where n is the number of characters in str(i)

The mxArray represents its data elements as mxChar rather than as C char

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxCreateCharArray mxCreateString mxGetString

Introduced before R2006a

1 API Reference

1-390

mxCreateDoubleMatrix (C and Fortran)2-D double-precision floating-point array

C Syntaxinclude matrixhmxArray mxCreateDoubleMatrix(mwSize m mwSize n mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleMatrix(m n ComplexFlag)mwSize m ninteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsComplexFlag

If the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateDoubleMatrix (C and Fortran)

1-391

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateDoubleMatrix to create an m-by-n mxArray mxCreateDoubleMatrixinitializes each element in the pr array to 0 If you set ComplexFlag to mxCOMPLEX in C(1 in Fortran) mxCreateDoubleMatrix also initializes each element in the pi array to0

If you set ComplexFlag to mxREAL in C (0 in Fortran) mxCreateDoubleMatrixallocates enough memory to hold m-by-n real elements If you set ComplexFlag tomxCOMPLEX in C (1 in Fortran) mxCreateDoubleMatrix allocates enough memory tohold m-by-n real elements and m-by-n imaginary elements

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its associated real and complex elements

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull matrixDividecbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull matsqF

1 API Reference

1-392

bull timestwoFbull xtimesyF

See AlsomxCreateNumericArray

Introduced before R2006a

mxCreateDoubleMatrix (C and Fortran)

1-393

mxCreateDoubleScalar (C and Fortran)Scalar double-precision array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateDoubleScalar(double value)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleScalar(value)real8 value

Argumentsvalue

Value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateDoubleScalar to create a scalar double mxArray When you finish usingthe mxArray call mxDestroyArray to destroy it

1 API Reference

1-394

See AlsomxGetPr mxCreateDoubleMatrix

Alternatives

C Language

In C you can replace the statements

pa = mxCreateDoubleMatrix(1 1 mxREAL)mxGetPr(pa) = value

with a call to mxCreateDoubleScalar

pa = mxCreateDoubleScalar(value)

Fortran Language

In Fortran you can replace the statements

pm = mxCreateDoubleMatrix(1 1 0)mxCopyReal8ToPtr(value mxGetPr(pm) 1)

with a call to mxCreateDoubleScalar

pm = mxCreateDoubleScalar(value)

Introduced before R2006a

mxCreateDoubleScalar (C and Fortran)

1-395

mxCreateLogicalArray (C)N-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalArray(mwSize ndim const mwSize dims)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateLogicalArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray There are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalArray to create an N-dimensional mxArray of mxLogicalelements After creating the mxArray mxCreateLogicalArray initializes all itselements to logical 0 mxCreateLogicalArray differs from mxCreateLogicalMatrixin that the latter can create two-dimensional arrays only

1 API Reference

1-396

mxCreateLogicalArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateLogicalMatrix mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalArray (C)

1-397

mxCreateLogicalMatrix (C)2-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalMatrix(mwSize m mwSize n)

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateLogicalMatrix to create an m-by-n mxArray of mxLogical elementsmxCreateLogicalMatrix initializes each element in the array to logical 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray

1 API Reference

1-398

See AlsomxCreateLogicalArray mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalMatrix (C)

1-399

mxCreateLogicalScalar (C)Scalar logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalScalar(mxLogical value)

Argumentsvalue

Logical value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalScalar to create a scalar logical mxArraymxCreateLogicalScalar is a convenience function that replaces the following code

pa = mxCreateLogicalMatrix(1 1)mxGetLogicals(pa) = value

When you finish using the mxArray call mxDestroyArray to destroy it

1 API Reference

1-400

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxIsLogicalScalarmxIsLogicalScalarTrue mxGetLogicals mxDestroyArray

Introduced before R2006a

mxCreateLogicalScalar (C)

1-401

mxCreateNumericArray (C and Fortran)N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateNumericArray(mwSize ndim const mwSize dims mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericArray(ndim dims classid ComplexFlag)mwSize ndimmwSize dims(ndim)integer4 classid ComplexFlag

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classid

1 API Reference

1-402

value from a MATLAB class name See the Description on page 1-403 section formore information

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericArray to create an N-dimensional mxArray in which all dataelements have the numeric data type specified by classid After creating the mxArraymxCreateNumericArray initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericArray also initializes all itsimaginary data elements to 0 mxCreateNumericArray differs frommxCreateDoubleMatrix as follows

bull All data elements in mxCreateDoubleMatrix are double-precision floating-pointnumbers The data elements in mxCreateNumericArray can be any numerical typeincluding different integer precisions

bull mxCreateDoubleMatrix can create two-dimensional arrays onlymxCreateNumericArray can create arrays of two or more dimensions

mxCreateNumericArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

mxCreateNumericArray (C and Fortran)

1-403

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull doubleelementcbull matrixDividecbull matsqint8F

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-404

Introduced before R2006a

mxCreateNumericArray (C and Fortran)

1-405

mxCreateNumericMatrix (C and Fortran)2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateNumericMatrix(mwSize m mwSize n mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericMatrix(m n classid ComplexFlag)mwSize m ninteger4 classid ComplexFlag

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classidvalue from a MATLAB class name

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

1 API Reference

1-406

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which all data elements havethe numeric data type specified by classid After creating the mxArraymxCreateNumericMatrix initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericMatrix also initializes all itsimaginary data elements to 0 mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray When you finish using the mxArray call mxDestroyArrayto destroy it

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

mxCreateNumericMatrix (C and Fortran)

1-407

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrc

The following Fortran statements create a 4-by-3 matrix of REAL4 elements having noimaginary components

C Create 4x3 mxArray of REAL4 mxCreateNumericMatrix(4 3 + mxClassIDFromClassName(single) 0)

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericMatrix mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-408

mxCreateSparse (C and Fortran)2-D sparse array

C Syntaxinclude matrixhmxArray mxCreateSparse(mwSize m mwSize n mwSize nzmax mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateSparse(m n nzmax ComplexFlag)mwSize m n nzmaxinteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparse should allocate to hold the pr ir and ifComplexFlag is mxCOMPLEX in C (1 in Fortran) pi arrays Set the value of nzmax tobe greater than or equal to the number of nonzero elements you plan to put into themxArray but make sure that nzmax is less than or equal to mn nzmax is greaterthan or equal to 1

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

mxCreateSparse (C and Fortran)

1-409

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray In that case tryreducing nzmax m or n

DescriptionCall mxCreateSparse to create an unpopulated sparse double mxArray The returnedsparse mxArray contains no sparse information and cannot be passed as an argument toany MATLAB sparse functions To make the returned sparse mxArray useful initializethe pr ir jc and (if it exists) pi arrays

mxCreateSparse allocates space for

bull A pr array of length nzmaxbull A pi array of length nzmax but only if ComplexFlag is mxCOMPLEX in C (1 in

Fortran)bull An ir array of length nzmaxbull A jc array of length n+1

When you finish using the sparse mxArray call mxDestroyArray to reclaim all its heapspace

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

1 API Reference

1-410

See AlsomxDestroyArray mxSetNzmax mxSetPr mxSetPi mxSetIr mxSetJcmxComplexity

Introduced before R2006a

mxCreateSparse (C and Fortran)

1-411

mxCreateSparseLogicalMatrix (C)2-D sparse logical array

C Syntaxinclude matrixhmxArray mxCreateSparseLogicalMatrix(mwSize m mwSize n mwSize nzmax)

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparseLogicalMatrix should allocate to holdthe data Set the value of nzmax to be greater than or equal to the number of nonzeroelements you plan to put into the mxArray but make sure that nzmax is less than orequal to mn nzmax is greater than or equal to 1

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

1 API Reference

1-412

DescriptionUse mxCreateSparseLogicalMatrix to create an m-by-n mxArray of mxLogicalelements mxCreateSparseLogicalMatrix initializes each element in the array tological 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its elements

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxCreateSparse mxIsLogical

Introduced before R2006a

mxCreateSparseLogicalMatrix (C)

1-413

mxCreateString (C and Fortran)1-N array initialized to specified string

C Syntaxinclude matrixhmxArray mxCreateString(const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateString(str)character() str

Argumentsstr

String used to initialize mxArray data Only ASCII characters are supported

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateString to create an mxArray initialized to str Many MATLAB functions(for example strcmp and upper) require string array inputs

1 API Reference

1-414

mxCreateString supports both multi-byte and single-byte encoded characters OnWindows and Linux platforms the default encoding is specified by the user localesetting

Free the mxArray when you are finished using it by calling mxDestroyArray

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull revordcbull revordF

See the following examples in matlabrootexternexamplesmx

bull mxcreatestructarraycbull mxisclassc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxCreateCharMatrixFromStrings mxCreateCharArray

Introduced before R2006a

mxCreateString (C and Fortran)

1-415

mxCreateStructArray (C and Fortran)N-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructArray(mwSize ndim const mwSize dims int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructArray(ndim dims nfields fieldnames)mwSize ndimmwSize dims(ndim)integer4 nfieldscharacter() fieldnames(nfields)

Argumentsndim

Number of dimensions If you set ndim to be less than 2 mxCreateStructArraycreates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Typically the dims array should have ndim elements

nfieldsNumber of fields in each element Positive integer

fieldnamesList of field names Field names must be valid MATLAB identifiers which meansthey cannot be NULL or empty

1 API Reference

1-416

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateStructArray to create an unpopulated structure mxArray Each elementof a structure mxArray contains the same number of fields (specified in nfields) Eachfield has a name the list of names is specified in fieldnames A MATLAB structuremxArray is conceptually identical to an array of structs in the C language

Each field holds one mxArray pointer mxCreateStructArray initializes each field toNULL in C (0 in Fortran) Call mxSetField or mxSetFieldByNumber to place a non-NULL mxArray pointer in a field

When you finish using the returned structure mxArray call mxDestroyArray to reclaimits space

Any trailing singleton dimensions specified in the dims argument are automaticallyremoved from the resulting array For example if ndim equals 5 and dims equals [4 17 1 1] the resulting array is given the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

mxCreateStructArray (C and Fortran)

1-417

See AlsomxDestroyArray mxAddField mxRemoveField mxSetFieldmxSetFieldByNumber namelengthmax

Introduced before R2006a

1 API Reference

1-418

mxCreateStructMatrix (C and Fortran)2-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructMatrix(mwSize m mwSize n int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructMatrix(m n nfields fieldnames)mwSize m ninteger4 nfieldscharacter() fieldnames(nfields)

Argumentsm

Number of rows must be a positive integern

Number of columns must be a positive integernfields

Number of fields in each elementfieldnames

List of field names

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

mxCreateStructMatrix (C and Fortran)

1-419

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxCreateStructMatrix and mxCreateStructArray are almost identical The onlydifference is that mxCreateStructMatrix can create only two-dimensional mxArrayswhile mxCreateStructArray can create an mxArray having two or more dimensions

C ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray namelengthmax

Introduced before R2006a

1 API Reference

1-420

mxCreateUninitNumericArray (C)Uninitialized N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateUninitNumericArray(size_t ndim size_t dims mxClassID classid mxComplexity ComplexFlag)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateUninitNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericArray (C)

1-421

DescriptionCall mxCreateUninitNumericArray to create an N-dimensional mxArray in which alldata elements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericArray allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericMatrix mxCreateNumericArray

Introduced in R2015a

1 API Reference

1-422

mxCreateUninitNumericMatrix (C)Uninitialized 2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateUninitNumericMatrix(size_t m size_t n mxClassID classid mxComplexity ComplexFlag)

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericMatrix (C)

1-423

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreateuninitnumericmatrixc

DescriptionCall mxCreateUninitNumericMatrix to create a 2-D mxArray in which all dataelements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericMatrix allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-424

Introduced in R2015a

mxCreateUninitNumericMatrix (C)

1-425

mxDestroyArray (C and Fortran)Free dynamic memory allocated by MXCREATE functions

C Syntaxinclude matrixhvoid mxDestroyArray(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mxDestroyArray(pm)mwPointer pm

Argumentspm

Pointer to the mxArray to free If pm is a NULL pointer the function does nothing

DescriptionmxDestroyArray deallocates the memory occupied by the specified mxArray including

bull Characteristics fields of the mxArray such as size (m and n) and typebull Associated data arrays such as pr and pi for complex arrays and ir and jc for

sparse arraysbull Fields of structure arraysbull Cells of cell arrays

Do not call mxDestroyArray on an mxArray

bull returned in a left-side argument of a MEX file

1 API Reference

1-426

bull returned by the mxGetField or mxGetFieldByNumber functionsbull returned by the mxGetCell function

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexgetarrayc

See the following examples in matlabrootexternexamplesmx

bull mxisclasscbull mxcreatecellmatrixfF

See AlsomxCalloc mxMalloc mxFree mexMakeArrayPersistentmexMakeMemoryPersistent

Introduced before R2006a

mxDestroyArray (C and Fortran)

1-427

mxDuplicateArray (C and Fortran)Make deep copy of array

C Syntaxinclude matrixhmxArray mxDuplicateArray(const mxArray in)

Fortran Syntaxinclude fintrfhmwPointer mxDuplicateArray(in)mwPointer in

Argumentsin

Pointer to the mxArray you want to copy

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxDuplicateArray makes a deep copy of an array and returns a pointer to the copy Adeep copy refers to a copy in which all levels of data are copied For example a deep copyof a cell array copies each cell and the contents of each cell (if any)

1 API Reference

1-428

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxgetinfcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

Introduced before R2006a

mxDuplicateArray (C and Fortran)

1-429

mxFree (C and Fortran)Free dynamic memory allocated by mxCalloc mxMalloc mxRealloc mxArrayToString ormxArrayToUTF8String functions

C Syntaxinclude matrixhvoid mxFree(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mxFree(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of any memory parcel allocated by mxCalloc mxMalloc ormxRealloc If ptr is a NULL pointer the function does nothing

DescriptionmxFree deallocates heap space using the MATLAB memory management facility Thisfunction ensures correct memory management in error and abort (Ctrl+C) conditions

To deallocate heap space MATLAB applications in C should always call mxFree ratherthan the ANSI C free function

In MEX files but excluding MAT or engine standalone applications the MATLABmemory management facility maintains a list of all memory allocated by the followingfunctions

1 API Reference

1-430

bull mxCallocbull mxMallocbull mxReallocbull mxArrayToStringbull mxArrayToUTF8String

The memory management facility automatically deallocates all parcels managed by aMEX file when the MEX file completes and control returns to the MATLAB promptmxFree also removes the memory parcel from the memory management list of parcels

When mxFree appears in a MAT or engine standalone MATLAB application it simplydeallocates the contiguous heap space that begins at address ptr

In MEX files your use of mxFree depends on whether the specified memory parcel ispersistent or nonpersistent By default memory parcels created by mxCallocmxMalloc mxRealloc mxArrayToString and mxArrayToUTF8String arenonpersistent The memory management facility automatically frees all nonpersistentmemory whenever a MEX file completes Thus even if you do not call mxFree MATLABtakes care of freeing the memory for you Nevertheless it is good programming practiceto deallocate memory when you are through using it Doing so generally makes the entiresystem run more efficiently

If an application calls mexMakeMemoryPersistent the specified memory parcelbecomes persistent When a MEX file completes the memory management facility doesnot free persistent memory parcels Therefore the only way to free a persistent memoryparcel is to call mxFree Typically MEX files call mexAtExit to register a cleanuphandler The cleanup handler calls mxFree

Do not use mxFree for an mxArray created by any other functions in the Matrix LibraryAPI Use mxDestroyArray instead

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxcreatecharmatrixfromstrc

mxFree (C and Fortran)

1-431

bull mxisfinitecbull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxMalloc mxRealloc mxArrayToString mxArrayToUTF8String

Introduced before R2006a

1 API Reference

1-432

mxGetCell (C and Fortran)Pointer to element in cell array

C Syntaxinclude matrixhmxArray mxGetCell(const mxArray pm mwIndex index)

Fortran Syntaxinclude fintrfhmwPointer mxGetCell(pm index)mwPointer pmmwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Number of elements in the cell mxArray between the first element and the desiredone See mxCalcSingleSubscript for details on calculating an index in amultidimensional cell array

ReturnsPointer to the ith cell mxArray if successful Otherwise returns NULL in C (0 inFortran) Causes of failure include

bull Specifying the index of a cell array element that has not been populatedbull Specifying a pm that does not point to a cell mxArray

mxGetCell (C and Fortran)

1-433

bull Specifying an index to an element outside the bounds of the mxArraybull Insufficient heap space

Do not call mxDestroyArray on an mxArray returned by the mxGetCell function

DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexed element of the cellmxArray

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCellArray mxIsCell mxSetCell

Introduced before R2006a

1 API Reference

1-434

mxGetChars (C)Pointer to character array data

C Syntaxinclude matrixhmxChar mxGetChars(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first character in the mxArray Returns NULL if the specified array is not acharacter array

DescriptionCall mxGetChars to access the first character in the mxArray that array_ptr points toOnce you have the starting address you can access any other element in the mxArray

See AlsomxGetString

Introduced before R2006a

mxGetChars (C)

1-435

mxGetClassID (C and Fortran)Class of array

C Syntaxinclude matrixhmxClassID mxGetClassID(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetClassID(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumeric identifier of the class (category) of the mxArray that pm points to For a list ofC-language class identifiers see the mxClassID reference page For user-defined typesmxGetClassId returns a unique value identifying the class of the array contents UsemxIsClass to determine whether an array is of a specific user-defined type

DescriptionUse mxGetClassId to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray then mxGetClassId returns mxLOGICAL_CLASS (in C)

1 API Reference

1-436

mxGetClassId is like mxGetClassName except that the former returns the class as aninteger identifier and the latter returns the class as a string

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxClassID mxGetClassName mxIsClass

Introduced before R2006a

mxGetClassID (C and Fortran)

1-437

mxGetClassName (C and Fortran)Class of array as string

Note Use mxGetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhconst char mxGetClassName(const mxArray pm)

Fortran Syntaxinclude fintrfhcharacter() mxGetClassName(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsClass (as a string) of the mxArray pointed to by pm

DescriptionCall mxGetClassName to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray mxGetClassName returns logical

1 API Reference

1-438

mxGetClassID is like mxGetClassName except that the former returns the class as aninteger identifier as listed in the mxClassID reference page and the latter returns theclass as a string as listed in the mxIsClass reference page

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxGetClassID mxIsClass

Introduced before R2006a

mxGetClassName (C and Fortran)

1-439

mxGetData (C and Fortran)Pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxGetData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionIn C mxGetData returns a void pointer (void ) Since void pointers point to a valuethat has no type cast the return value to the pointer type that matches the type specifiedby pm To see how MATLAB types map to their equivalent C types see the table on themxClassID reference page

1 API Reference

1-440

In Fortran to copy values from the returned pointer use one of the mxCopyPtrTofunctions in the following manner

C Get the data in mxArray pm mxCopyPtrToReal8(mxGetData(pm)data + mxGetNumberOfElements(pm))

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxisfinitec

See AlsomxGetImagData mxGetPr mxClassID

Introduced before R2006a

mxGetData (C and Fortran)

1-441

mxGetDimensions (C and Fortran)Pointer to dimensions array

C Syntaxinclude matrixhconst mwSize mxGetDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element in the dimensions array Each integer in the dimensionsarray represents the number of elements in a particular dimension The array is notNULL terminated

DescriptionUse mxGetDimensions to determine how many elements are in each dimension of themxArray that pm points to Call mxGetNumberOfDimensions to get the number ofdimensions in the mxArray

To copy the values to Fortran use mxCopyPtrToInteger4 in the following manner

1 API Reference

1-442

C Get dimensions of mxArray pm mxCopyPtrToInteger4(mxGetDimensions(pm) dims + mxGetNumberOfDimensions(pm))

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetNumberOfDimensions

Introduced before R2006a

mxGetDimensions (C and Fortran)

1-443

mxGetElementSize (C and Fortran)Number of bytes required to store each data element

C Syntaxinclude matrixhsize_t mxGetElementSize(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetElementSize(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of bytes required to store one element of the specified mxArray if successfulReturns 0 on failure The primary reason for failure is that pm points to an mxArrayhaving an unrecognized class If pm points to a cell mxArray or a structure mxArraymxGetElementSize returns the size of a pointer (not the size of all the elements in eachcell or structure field)

DescriptionCall mxGetElementSize to determine the number of bytes in each data element of themxArray For example if the MATLAB class of an mxArray is int16 the mxArray

1 API Reference

1-444

stores each data element as a 16-bit (2-byte) signed integer Thus mxGetElementSizereturns 2

mxGetElementSize is helpful when using a non-MATLAB routine to manipulate dataelements For example the C function memcpy requires (for its third argument) the sizeof the elements you intend to copy

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull doubleelementcbull phonebookc

See AlsomxGetM mxGetN

Introduced before R2006a

mxGetElementSize (C and Fortran)

1-445

mxGetEps (C and Fortran)Value of EPS

C Syntaxinclude matrixhdouble mxGetEps(void)

Fortran Syntaxreal8 mxGetEps

ReturnsValue of the MATLAB eps variable

DescriptionCall mxGetEps to return the value of the MATLAB eps variable This variable holds thedistance from 10 to the next largest floating-point number As such it is a measure offloating-point accuracy The MATLAB pinv and rank functions use eps as a defaulttolerance

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

1 API Reference

1-446

See AlsomxGetInf mxGetNan

Introduced before R2006a

mxGetEps (C and Fortran)

1-447

mxGetField (C and Fortran)Pointer to field value from structure array given index and field name

C Syntaxinclude matrixhmxArray mxGetField(const mxArray pm mwIndex index const char fieldname)

Fortran Syntaxinclude fintrfhmwPointer mxGetField(pm index fieldname)mwPointer pmmwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

fieldnameName of the field whose value you want to extract

1 API Reference

1-448

ReturnsPointer to the mxArray in the specified field at the specified fieldname on successReturns NULL in C (0 in Fortran) if passed an invalid argument or if there is no valueassigned to the specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray Todetermine whether pm points to a structure mxArray call mxIsStruct

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains 10 elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent fieldname Call mxGetFieldNameByNumber ormxGetFieldNumber to get existing field names

bull Insufficient heap space

DescriptionCall mxGetField to get the value held in the specified element of the specified field Inpseudo-C terminology mxGetField returns the value at

pm[index]fieldname

mxGetFieldByNumber is like mxGetField Both functions return the same value Theonly difference is in the way you specify the field mxGetFieldByNumber takes a fieldnumber as its third argument and mxGetField takes a field name as its thirdargument

Do not call mxDestroyArray on an mxArray returned by the mxGetField function

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

mxGetField(pa index field_name)

mxGetField (C and Fortran)

1-449

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where if you have a 1-by-1 structure index is 0

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where if you have a 1-by-1 structure index is 1

ExamplesSee the following example in matlabrootexternexampleseng_mat

bull matreadstructarrayc

See AlsomxGetFieldByNumber mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-450

mxGetFieldByNumber (C and Fortran)Pointer to field value from structure array given index and field number

C Syntaxinclude matrixhmxArray mxGetFieldByNumber(const mxArray pm mwIndex index int fieldnumber)

Fortran Syntaxinclude fintrfhmwPointer mxGetFieldByNumber(pm index fieldnumber)mwPointer pmmwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for more details on calculating an indexfieldnumber

Position of the field whose value you want to extract

mxGetFieldByNumber (C and Fortran)

1-451

In C the first field within each element has a field number of 0 the second field hasa field number of 1 and so on The last field has a field number of N-1 where N is thenumber of fields

In Fortran the first 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 field number of N whereN is the number of fields

ReturnsPointer to the mxArray in the specified field for the desired element on success ReturnsNULL in C (0 in Fortran) if passed an invalid argument or if there is no value assigned tothe specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains ten elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent field number Call mxGetFieldNumber to determine thefield number that corresponds to a given field name

DescriptionCall mxGetFieldByNumber to get the value held in the specified fieldnumber at theindexed element

Do not call mxDestroyArray on an mxArray returned by the mxGetFieldByNumberfunction

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

1 API Reference

1-452

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldByNumber (C and Fortran)

1-453

mxGetFieldNameByNumber (C and Fortran)Pointer to field name from structure array given field number

C Syntaxinclude matrixhconst char mxGetFieldNameByNumber(const mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhcharacter() mxGetFieldNameByNumber(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Position of the desired field For instance in C to get the name of the first field setfieldnumber to 0 to get the name of the second field set fieldnumber to 1 and soon In Fortran to get the name of the first field set fieldnumber to 1 to get thename of the second field set fieldnumber to 2 and so on

ReturnsPointer to the nth field name on success Returns NULL in C (0 in Fortran) on failureCommon causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

1 API Reference

1-454

bull Specifying a value of fieldnumber outside the bounds of the number of fields in thestructure mxArray In C fieldnumber 0 represents the first field andfieldnumber N-1 represents the last field where N is the number of fields in thestructure mxArray In Fortran fieldnumber 1 represents the first field andfieldnumber N represents the last field

DescriptionCall mxGetFieldNameByNumber to get the name of a field in the given structuremxArray A typical use of mxGetFieldNameByNumber is to call it inside a loop to get thenames of all the fields in a given mxArray

Consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test A field number other than 0 1 or 2causes mxGetFieldNameByNumber to return NULL

In Fortran the field number 1 represents the field name field number 2 represents fieldbilling field number 3 represents field test A field number other than 1 2 or 3causes mxGetFieldNameByNumber to return 0

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

mxGetFieldNameByNumber (C and Fortran)

1-455

bull explorec

See AlsomxGetField mxGetFieldByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-456

mxGetFieldNumber (C and Fortran)Field number from structure array given field name

C Syntaxinclude matrixhint mxGetFieldNumber(const mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxGetFieldNumber(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of a field in the structure mxArray

ReturnsField number of the specified fieldname on success In C the first field has a fieldnumber of 0 the second field has a field number of 1 and so on In Fortran the first fieldhas a field number of 1 the second field has a field number of 2 and so on Returns -1 inC (0 in Fortran) on failure Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

mxGetFieldNumber (C and Fortran)

1-457

bull 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 do not know its fieldname call mxGetFieldNameByNumber

For example consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field name has a field number of 0 the field billing has a field number of 1and the field test has a field number of 2 If you call mxGetFieldNumber and specify afield name of anything other than name billing or test mxGetFieldNumber returns-1

Calling

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran the field name has a field number of 1 the field billing has a field numberof 2 and the field test has a field number of 3 If you call mxGetFieldNumber andspecify a field name of anything other than name billing or testmxGetFieldNumber returns 0

Calling

mxGetField(pm index fieldname)

is equivalent to calling

1 API Reference

1-458

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxGetField mxGetFieldByNumber mxGetFieldNameByNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldNumber (C and Fortran)

1-459

mxGetImagData (C and Fortran)Pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxGetImagData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetImagData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the imaginary data Returns NULL in C (0 in Fortran) ifthere is no imaginary data or if there is an error

DescriptionThis function is like mxGetPi except that in C it returns a void For moreinformation see the description for the mxGetData function

1 API Reference

1-460

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxGetData mxGetPi

Introduced before R2006a

mxGetImagData (C and Fortran)

1-461

mxGetInf (C and Fortran)Value of infinity

C Syntaxinclude matrixhdouble mxGetInf(void)

Fortran Syntaxreal8 mxGetInf

ReturnsValue of infinity on your system

DescriptionCall mxGetInf to return the value of the MATLAB internal inf variable inf is apermanent variable representing IEEEreg arithmetic positive infinity Your systemspecifies the value of inf you cannot modify it

Operations that return infinity include

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-462

bull mxgetinfc

See AlsomxGetEps mxGetNaN

Introduced before R2006a

mxGetInf (C and Fortran)

1-463

mxGetIr (C and Fortran)Sparse matrix IR array

C Syntaxinclude matrixhmwIndex mxGetIr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetIr(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the ir array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetIr to obtain the starting address of the ir array The ir array is an array ofintegers The length of ir is nzmax the storage allocated for the sparse array or nnz

1 API Reference

1-464

the number of nonzero matrix elements For example if nzmax equals 100 the ir arraycontains 100 integers

Each value in an ir array indicates a row (offset by 1) at which a nonzero element can befound (The jc array is an index that indirectly specifies a column where nonzeroelements can be found)

For details on the ir and jc arrays see mxSetIr and mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetJc mxGetNzmax mxSetIr mxSetJc mxSetNzmax nzmax nnz

Introduced before R2006a

mxGetIr (C and Fortran)

1-465

mxGetJc (C and Fortran)Sparse matrix JC array

C Syntaxinclude matrixhmwIndex mxGetJc(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetJc(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the jc array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetJc to obtain the starting address of the jc array The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

1 API Reference

1-466

The values in the jc array indirectly indicate columns containing nonzero elements Fora detailed explanation of the jc array see mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetIr mxGetNzmax mxSetIr mxSetJc mxSetNzmax

Introduced before R2006a

mxGetJc (C and Fortran)

1-467

mxGetLogicals (C)Pointer to logical array data

C Syntaxinclude matrixhmxLogical mxGetLogicals(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first logical element in the mxArray The result is unspecified if themxArray is not a logical array

DescriptionCall mxGetLogicals to access the first logical element in the mxArray that array_ptrpoints to Once you have the starting address you can access any other element in themxArray

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxIsLogical mxIsLogicalScalar mxIsLogicalScalarTrue

Introduced before R2006a

1 API Reference

1-468

mxGetM (C and Fortran)Number of rows in array

C Syntaxinclude matrixhsize_t mxGetM(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetM(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of rows in the mxArray to which pm points

DescriptionmxGetM returns the number of rows in the specified array The term rows always meansthe first dimension of the array no matter how many dimensions the array has Forexample if pm points to a four-dimensional array having dimensions 8-by-9-by-5-by-3mxGetM returns 8

mxGetM (C and Fortran)

1-469

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull matrixDividecbull matrixDivideComplexcbull revordcbull timestwocbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull timestwoFbull xtimesyF

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-470

bull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomxGetN mxSetM mxSetN

Introduced before R2006a

mxGetM (C and Fortran)

1-471

mxGetN (C and Fortran)Number of columns in array

C Syntaxinclude matrixhsize_t mxGetN(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetN(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of columns in the mxArray

DescriptionCall mxGetN to determine the number of columns in the specified mxArray

If pm is an N-dimensional mxArray mxGetN is the product of dimensions 2 through NFor example if pm points to a four-dimensional mxArray having dimensions 13-by-5-by-4-by-6 mxGetN returns the value 120 (5 times 4 times 6) If the specified mxArray has morethan two dimensions and you need to know exactly how many elements are in eachdimension call mxGetDimensions

1 API Reference

1-472

If pm points to a sparse mxArray mxGetN still returns the number of columns not thenumber of occupied columns

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull revordcbull timestwocbull xtimesyc

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxGetN (C and Fortran)

1-473

See AlsomxGetM mxGetDimensions mxSetM mxSetN

Introduced before R2006a

1 API Reference

1-474

mxGetNaN (C and Fortran)Value of NaN (Not-a-Number)

C Syntaxinclude matrixhdouble mxGetNaN(void)

Fortran Syntaxreal8 mxGetNaN

ReturnsValue of NaN (Not-a-Number) on your system

DescriptionCall mxGetNaN to return the value of NaN for your system NaN is the IEEE arithmeticrepresentation for Not-a-Number Certain mathematical operations return NaN as aresult for example

bull 0000bull Inf-Inf

Your system specifies the value of Not-a-Number You cannot modify it

C ExamplesSee the following examples in matlabrootexternexamplesmx

mxGetNaN (C and Fortran)

1-475

bull mxgetinfc

See AlsomxGetEps mxGetInf

Introduced before R2006a

1 API Reference

1-476

mxGetNumberOfDimensions (C and Fortran)Number of dimensions in array

C Syntaxinclude matrixhmwSize mxGetNumberOfDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNumberOfDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of dimensions in the specified mxArray The returned value is always 2 orgreater

DescriptionUse mxGetNumberOfDimensions to determine how many dimensions are in thespecified array To determine how many elements are in each dimension callmxGetDimensions

mxGetNumberOfDimensions (C and Fortran)

1-477

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsecbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See AlsomxSetM mxSetN mxGetDimensions

Introduced before R2006a

1 API Reference

1-478

mxGetNumberOfElements (C and Fortran)Number of elements in array

C Syntaxinclude matrixhsize_t mxGetNumberOfElements(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetNumberOfElements(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of elements in the specified mxArray

DescriptionmxGetNumberOfElements tells you how many elements an array has For example ifthe dimensions of an array are 3-by-5-by-10 mxGetNumberOfElements returns thenumber 150

mxGetNumberOfElements (C and Fortran)

1-479

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxgetepsfFbull mxgetinfcbull mxisfinitecbull mxsetdimensionscbull mxsetdimensionsfF

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetDimensions mxGetM mxGetN mxGetClassID mxGetClassName

Introduced before R2006a

1 API Reference

1-480

mxGetNumberOfFields (C and Fortran)Number of fields in structure array

C Syntaxinclude matrixhint mxGetNumberOfFields(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetNumberOfFields(pm)mwPointer pm

Argumentspm

Pointer to a structure mxArray

ReturnsNumber of fields on success Returns 0 on failure The most common cause of failure isthat pm is not a structure mxArray Call mxIsStruct to determine whether pm is astructure

DescriptionCall mxGetNumberOfFields to determine how many fields are in the specified structuremxArray

Once you know the number of fields in a structure you can loop through every field to setor to get field values

mxGetNumberOfFields (C and Fortran)

1-481

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxIsStruct mxSetField

Introduced before R2006a

1 API Reference

1-482

mxGetNzmax (C and Fortran)Number of elements in IR PR and PI arrays

C Syntaxinclude matrixhmwSize mxGetNzmax(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNzmax(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsNumber of elements allocated to hold nonzero entries in the specified sparse mxArray onsuccess Returns an indeterminate value on error The most likely cause of failure is thatpm points to a full (nonsparse) mxArray

DescriptionUse mxGetNzmax to get the value of the nzmax field The nzmax field holds an integervalue that signifies the number of elements in the ir pr and if it exists the pi arraysThe value of nzmax is always greater than or equal to the number of nonzero elements ina sparse mxArray In addition the value of nzmax is always less than or equal to thenumber of rows times the number of columns

mxGetNzmax (C and Fortran)

1-483

As you adjust the number of nonzero elements in a sparse mxArray MATLAB softwareoften adjusts the value of the nzmax field MATLAB adjusts nzmax to reduce the numberof costly reallocations and to optimize its use of heap space

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetnzmaxc

See AlsomxSetNzmax

Introduced before R2006a

1 API Reference

1-484

mxGetPi (C and Fortran)Imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPi(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPi(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the imaginary data elements of the specified mxArray on success ReturnsNULL in C (0 in Fortran) if there is no imaginary data or if there is an error

DescriptionUse mxGetPi on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetImagData

The pi field points to an array containing the imaginary data of the mxArray CallmxGetPi to get the contents of the pi field that is to get the starting address of thisimaginary data

mxGetPi (C and Fortran)

1-485

The best way to determine whether an mxArray is purely real is to call mxIsComplex

If any of the input matrices to a function are complex MATLAB allocates the imaginaryparts of all input matrices

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull fulltosparsec

For Fortran examples see

bull convecF

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetinfcbull mxisfinitecbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexcallmatlabc

See AlsomxGetPr mxSetPi mxSetPr mxGetImagData mxIsDouble

Introduced before R2006a

1 API Reference

1-486

mxGetPr (C and Fortran)Real data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPr(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionUse mxGetPr on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetData

Call mxGetPr to access the real data in the mxArray that pm points to Once you havethe starting address you can access any other element in the mxArray

mxGetPr (C and Fortran)

1-487

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull arrayFillGetPrcbull conveccbull doubleelementcbull findnzcbull fulltosparsecbull matrixDividecbull matrixMultiplycbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull sincallFbull timestwoFbull xtimesyF

See AlsomxGetPi mxSetPi mxSetPr mxGetData mxIsDouble

Introduced before R2006a

1 API Reference

1-488

mxGetProperty (C and Fortran)Value of public property of MATLAB object

C Syntaxinclude matrixhmxArray mxGetProperty(const mxArray pa mwIndex index const char propname)

Fortran Syntaxinclude fintrfhmwPointer mxGetProperty(pa index propname)mwPointer pamwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you want to extract

mxGetProperty (C and Fortran)

1-489

ReturnsPointer to the mxArray of the specified propname on success Returns NULL in C (0 inFortran) if unsuccessful Common causes of failure include

bull Specifying a nonexistent propnamebull Specifying a nonpublic propnamebull Specifying an index to an element outside the bounds of the mxArray To test the

index value use mxGetNumberOfElements or mxGetM and mxGetNbull Insufficient heap space

DescriptionCall mxGetProperty to get the value held in the specified element In pseudo-Cterminology mxGetProperty returns the value at

pa[index]propname

mxGetProperty makes a copy of the value If the property uses a large amount ofmemory creating a copy might be a concern There must be sufficient memory (in theheap) to hold the copy of the value

Examples

Display Name Property of timeseries Object

Create a MEX file disppropertyc in a folder on your MATLAB path================================================================= disppropertyc - Display timeseries Name property This is a MEX file for MATLAB Copyright 2013 The MathWorks Inc All rights reserved ================================================================= include mexh

void mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

1 API Reference

1-490

Check for proper number of arguments if(nrhs=1) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidNumInputs One input required) else if(nlhsgt1) mexErrMsgIdAndTxt( MATLABdisppropertymaxlhs Too many output arguments) Check for timeseries object if (mxIsClass(prhs[0] timeseries)) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidClass Input must be timeseries object) plhs[0] = mxGetProperty(prhs[0]0Name)

Build the MEX file

mex(-vdisppropertyc)

Create a timeseries object

ts = timeseries(rand(5 4)NameLaunchData)

Display name

tsname = dispproperty(ts)

tsname =LaunchData

Change Object Color

Open and build the mexgetpropertyc MEX file in the matlabrootexternexamplesmex folder

Limitationsbull mxGetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

mxGetProperty (C and Fortran)

1-491

See AlsomxSetProperty mxGetNumberOfElements mxGetM mxGetN

Introduced in R2008a

1 API Reference

1-492

mxGetScalar (C and Fortran)Real component of first data element in array

C Syntaxinclude matrixhdouble mxGetScalar(const mxArray pm)

Fortran Syntaxinclude fintrfhreal8 mxGetScalar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray cannot be a cell mxArray a structure mxArray or an emptymxArray

ReturnsThe value of the first real (nonimaginary) element of the mxArray

In C mxGetScalar returns a double If real elements in the mxArray are of a typeother than double then mxGetScalar automatically converts the scalar value into adouble To preserve the original data representation of the scalar cast the return valueto the desired data type

If pm points to a sparse mxArray then mxGetScalar returns the value of the firstnonzero real element in the mxArray If there are no nonzero elements then the functionreturns 0

mxGetScalar (C and Fortran)

1-493

DescriptionCall mxGetScalar to get the value of the first real (nonimaginary) element of themxArray

Usually you call mxGetScalar when pm points to an mxArray containing only oneelement (a scalar) However pm can point to an mxArray containing many elements Ifpm points to an mxArray containing multiple elements then the function returns thevalue of the first real element For example if pm points to a two-dimensional mxArraythen mxGetScalar returns the value of the (11) element If pm points to a three-dimensional mxArray then the function returns the value of the (111) element andso on

Use mxGetScalar on a nonempty mxArray of type numeric logical or char only To testfor these conditions use Matrix Library functions such as mxIsEmpty mxIsLogicalmxIsNumeric or mxIsChar

If the input value to mxGetScalar is type int64 or uint64 then the value might loseprecision if it is greater than flintmax

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull timestwoaltcbull xtimesyc

See the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

1 API Reference

1-494

See AlsomxGetM mxGetN mxIsScalar

mxGetScalar (C and Fortran)

1-495

mxGetString (C and Fortran)mxChar array to C-style string or Fortran character array

C Syntaxinclude matrixhint mxGetString(const mxArray pm char str mwSize strlen)

Fortran Syntaxinclude fintrfhinteger4 mxGetString(pm str strlen)mwPointer pmcharacter() strmwSize strlen

Argumentspm

Pointer to an mxChar arraystr

Starting location mxGetString writes the character data into str and then in Cterminates the string with a NULL character (in the manner of C strings) str canpoint to either dynamic or static memory

strlenSize in bytes of destination buffer pointed to by str Typically in C you set strlento 1 plus the number of elements in the mxArray to which pm points To get thenumber of elements use mxGetM or mxGetN

Do not use with ldquoMultibyte Encoded Charactersrdquo on page 1-497

1 API Reference

1-496

Returns0 on success or if strlen == 0 and 1 on failure Possible reasons for failure include

bull mxArray is not an mxChar arraybull strlen is not large enough to store the entire mxArray If so the function returns 1

and truncates the string

DescriptionCall mxGetString to copy the character data of an mxArray into a C-style string in C ora character array in Fortran The copied data starts at str and contains no more thanstrlen-1 characters in C (no more than strlen characters in Fortran) In C the C-style string is always terminated with a NULL character

If the array contains multiple rows the function copies them into a single array onecolumn at a time

Multibyte Encoded Characters

Use this function only with characters represented in single-byte encoding schemes Forcharacters represented in multibyte encoding schemes use the C functionmxArrayToString Fortran users must allocate sufficient space for the return string toavoid possible truncation

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmallocc

See the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

mxGetString (C and Fortran)

1-497

bull revordF

See AlsomxArrayToString mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetChars

Introduced before R2006a

1 API Reference

1-498

mxIsCell (C and Fortran)Determine whether input is cell array

C Syntaxinclude matrixhbool mxIsCell(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsCell(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCELL_CLASS and logical 0(false) otherwise

DescriptionUse mxIsCell to determine whether the specified array is a cell array

In C calling mxIsCell is equivalent to calling

mxGetClassID(pm) == mxCELL_CLASS

mxIsCell (C and Fortran)

1-499

In Fortran calling mxIsCell is equivalent to calling

mxGetClassName(pm) eq cell

Note mxIsCell does not answer the question ldquoIs this mxArray a cell of a cell arrayrdquo Anindividual cell of a cell array can be of any type

See AlsomxIsClass

Introduced before R2006a

1 API Reference

1-500

mxIsChar (C and Fortran)Determine whether input is mxChar array

C Syntaxinclude matrixhbool mxIsChar(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsChar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCHAR_CLASS and logical 0(false) otherwise

DescriptionUse mxIsChar to determine whether pm points to an mxChar array

In C calling mxIsChar is equivalent to calling

mxGetClassID(pm) == mxCHAR_CLASS

mxIsChar (C and Fortran)

1-501

In Fortran calling mxIsChar is equivalent to calling

mxGetClassName(pm) eq char

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull revordc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxmallocc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxIsClass mxGetClassID

Introduced before R2006a

1 API Reference

1-502

mxIsClass (C and Fortran)Determine whether array is object of specified class

C Syntaxinclude matrixhbool mxIsClass(const mxArray pm const char classname)

Fortran Syntaxinclude fintrfhinteger4 mxIsClass(pm classname)mwPointer pmcharacter() classname

Argumentspm

Pointer to an mxArrayclassname

Array category to test Specify classname as a string (not as an integer identifier)You can specify any one of the following predefined constants

Value of classname Corresponding Classcell mxCELL_CLASSchar mxCHAR_CLASSdouble mxDOUBLE_CLASSfunction_handle mxFUNCTION_CLASSint8 mxINT8_CLASSint16 mxINT16_CLASS

mxIsClass (C and Fortran)

1-503

Value of classname Corresponding Classint32 mxINT32_CLASSint64 mxINT64_CLASSlogical mxLOGICAL_CLASSsingle mxSINGLE_CLASSstruct mxSTRUCT_CLASSuint8 mxUINT8_CLASSuint16 mxUINT16_CLASSuint32 mxUINT32_CLASSuint64 mxUINT64_CLASSltclass_namegt ltclass_idgt

unknown mxUNKNOWN_CLASS

In the table ltclass_namegt represents the name of a specific MATLAB custom objectYou can also specify one of your own class names

ReturnsLogical 1 (true) if pm points to an array having category classname and logical 0(false) otherwise

DescriptionEach mxArray is tagged as being a certain type Call mxIsClass to determine whetherthe specified mxArray has this type MATLAB does not check if the class is derived froma base class

In C

mxIsClass(pm double)

is equivalent to calling either of these forms

1 API Reference

1-504

mxIsDouble(pm)

strcmp(mxGetClassName(pm) double)

In Fortran

mxIsClass(pm double)

is equivalent to calling either one of the following

mxIsDouble(pm)

mxGetClassName(pm) eq double

It is most efficient to use the mxIsDouble form

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxClassID mxGetClassID mxIsEmpty mxGetClassName

Introduced before R2006a

mxIsClass (C and Fortran)

1-505

mxIsComplex (C and Fortran)Determine whether data is complex

C Syntaxinclude matrixhbool mxIsComplex(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsComplex(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm is a numeric array containing complex data and logical 0 (false)otherwise If pm points to a cell array or a structure array mxIsComplex returns false

DescriptionUse mxIsComplex to determine whether an imaginary part is allocated for an mxArrayIf an mxArray is purely real and does not have any imaginary data the imaginarypointer pi is NULL in C (0 in Fortran) If an mxArray is complex pi points to an array ofnumbers

1 API Reference

1-506

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxgetinfc

See the following examples in matlabrootexternexamplesrefbook

bull conveccbull convecFbull fulltosparseFbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorecbull yprimecbull mexlockc

See AlsomxIsNumeric

Introduced before R2006a

mxIsComplex (C and Fortran)

1-507

mxIsDouble (C and Fortran)Determine whether mxArray represents data as double-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsDouble(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsDouble(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as double-precision floating-pointnumbers and logical 0 (false) otherwise

DescriptionCall mxIsDouble to determine whether the specified mxArray represents its real andimaginary data as double-precision floating-point numbers

Older versions of MATLAB software store all mxArray data as double-precision floating-point numbers However starting with MATLAB Version 5 software MATLAB can storereal and imaginary data in various numerical formats

1 API Reference

1-508

In C calling mxIsDouble is equivalent to calling

mxGetClassID(pm) == mxDOUBLE_CLASS

In Fortran calling mxIsDouble is equivalent to calling

mxGetClassName(pm) eq double

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsDouble (C and Fortran)

1-509

mxIsEmpty (C and Fortran)Determine whether array is empty

C Syntaxinclude matrixhbool mxIsEmpty(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsEmpty(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is empty and logical 0 (false) otherwise

DescriptionUse mxIsEmpty to determine whether an mxArray contains no data An mxArray isempty if the size of any of its dimensions is 0

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-510

bull mxisfinitec

See AlsomxIsClass

Introduced before R2006a

mxIsEmpty (C and Fortran)

1-511

mxIsFinite (C and Fortran)Determine whether input is finite

C Syntaxinclude matrixhbool mxIsFinite(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsFinite(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is finite and logical 0 (false) otherwise

DescriptionCall mxIsFinite to determine whether value is finite A number is finite if it is greaterthan -Inf and less than Inf

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-512

bull mxisfinitec

See AlsomxIsInf mxIsNan

Introduced before R2006a

mxIsFinite (C and Fortran)

1-513

mxIsFromGlobalWS (C and Fortran)Determine whether array was copied from MATLAB global workspace

C Syntaxinclude matrixhbool mxIsFromGlobalWS(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsFromGlobalWS(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array was copied out of the global workspace and logical 0(false) otherwise

DescriptionmxIsFromGlobalWS is useful for standalone MAT-file programs

1 API Reference

1-514

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnsc

Introduced before R2006a

mxIsFromGlobalWS (C and Fortran)

1-515

mxIsInf (C and Fortran)Determine whether input is infinite

C Syntaxinclude matrixhbool mxIsInf(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsInf(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is infinite and logical 0 (false) otherwise

DescriptionCall mxIsInf to determine whether value is equal to infinity or minus infinityMATLAB software stores the value of infinity in a permanent variable named Inf whichrepresents IEEE arithmetic positive infinity The value of the variable Inf is built intothe system you cannot modify it

Operations that return infinity include

1 API Reference

1-516

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

If value equals NaN (Not-a-Number) mxIsInf returns false In other words NaN is notequal to infinity

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxIsFinite mxIsNaN

Introduced before R2006a

mxIsInf (C and Fortran)

1-517

mxIsInt16 (C and Fortran)Determine whether array represents data as signed 16-bit integers

C Syntaxinclude matrixhbool mxIsInt16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt16 to determine whether the specified array represents its real andimaginary data as 16-bit signed integers

In C calling mxIsInt16 is equivalent to calling

mxGetClassID(pm) == mxINT16_CLASS

1 API Reference

1-518

In Fortran calling mxIsInt16 is equivalent to calling

mxGetClassName(pm) == int16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt16 (C and Fortran)

1-519

mxIsInt32 (C and Fortran)Determine whether array represents data as signed 32-bit integers

C Syntaxinclude matrixhbool mxIsInt32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt32 to determine whether the specified array represents its real andimaginary data as 32-bit signed integers

In C calling mxIsInt32 is equivalent to calling

mxGetClassID(pm) == mxINT32_CLASS

1 API Reference

1-520

In Fortran calling mxIsInt32 is equivalent to calling

mxGetClassName(pm) == int32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt32 (C and Fortran)

1-521

mxIsInt64 (C and Fortran)Determine whether array represents data as signed 64-bit integers

C Syntaxinclude matrixhbool mxIsInt64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt64 to determine whether the specified array represents its real andimaginary data as 64-bit signed integers

In C calling mxIsInt64 is equivalent to calling

mxGetClassID(pm) == mxINT64_CLASS

1 API Reference

1-522

In Fortran calling mxIsInt64 is equivalent to calling

mxGetClassName(pm) == int64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt64 (C and Fortran)

1-523

mxIsInt8 (C and Fortran)Determine whether array represents data as signed 8-bit integers

C Syntaxinclude matrixhbool mxIsInt8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 8-bit integers and logical 0 (false)otherwise

DescriptionUse mxIsInt8 to determine whether the specified array represents its real andimaginary data as 8-bit signed integers

In C calling mxIsInt8 is equivalent to calling

mxGetClassID(pm) == mxINT8_CLASS

1 API Reference

1-524

In Fortran calling mxIsInt8 is equivalent to calling

mxGetClassName(pm) eq int8

See AlsomxIsClass mxGetClassID mxIsInt16 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt8 (C and Fortran)

1-525

mxIsLogical (C and Fortran)Determine whether array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogical(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsLogical(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a logical mxArray Otherwise it returns logical 0(false)

DescriptionUse mxIsLogical to determine whether MATLAB software treats the data in themxArray as Boolean (logical) If an mxArray is logical MATLAB treats all zeros asmeaning false and all nonzero values as meaning true

1 API Reference

1-526

See AlsomxIsClass

TopicsldquoLogical Operationsrdquo

Introduced before R2006a

mxIsLogical (C and Fortran)

1-527

mxIsLogicalScalar (C)Determine whether scalar array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogicalScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is of class mxLogical and has 1-by-1 dimensionsOtherwise it returns logical 0 (false)

DescriptionUse mxIsLogicalScalar to determine whether MATLAB treats the scalar data in themxArray as logical or numerical

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalarTrue

TopicsldquoLogical Operationsrdquo

1 API Reference

1-528

Introduced before R2006a

mxIsLogicalScalar (C)

1-529

mxIsLogicalScalarTrue (C)Determine whether scalar array of type mxLogical is true

C Syntaxinclude matrixhbool mxIsLogicalScalarTrue(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the value of the mxArray logical scalar element is true Otherwise itreturns logical 0 (false)

DescriptionUse mxIsLogicalScalarTrue to determine whether the value of a scalar mxArray istrue or false

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalar

TopicsldquoLogical Operationsrdquo

1 API Reference

1-530

Introduced before R2006a

mxIsLogicalScalarTrue (C)

1-531

mxIsNaN (C and Fortran)Determine whether input is NaN (Not-a-Number)

C Syntaxinclude matrixhbool mxIsNaN(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsNaN(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is NaN (Not-a-Number) and logical 0 (false) otherwise

DescriptionCall mxIsNaN to determine whether value is NaN NaN is the IEEE arithmeticrepresentation for Not-a-Number A NaN is obtained as a result of mathematicallyundefined operations such as

bull 0000bull Inf-Inf

1 API Reference

1-532

The system understands a family of bit patterns as representing NaN NaN is not a singlevalue it is a family of numbers that MATLAB software (and other IEEE-compliantapplications) uses to represent an error condition or missing data

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsec

See AlsomxIsFinite mxIsInf

Introduced before R2006a

mxIsNaN (C and Fortran)

1-533

mxIsNumeric (C and Fortran)Determine whether array is numeric

C Syntaxinclude matrixhbool mxIsNumeric(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsNumeric(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array can contain numeric data The following class IDs representstorage types for arrays that can contain numeric data

bull mxDOUBLE_CLASSbull mxSINGLE_CLASSbull mxINT8_CLASSbull mxUINT8_CLASSbull mxINT16_CLASSbull mxUINT16_CLASS

1 API Reference

1-534

bull mxINT32_CLASSbull mxUINT32_CLASSbull mxINT64_CLASSbull mxUINT64_CLASS

Logical 0 (false) if the array cannot contain numeric data

DescriptionCall mxIsNumeric to determine whether the specified array contains numeric data Ifthe specified array has a storage type that represents numeric data mxIsNumericreturns logical 1 (true) Otherwise mxIsNumeric returns logical 0 (false)

Call mxGetClassID to determine the exact storage type

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxGetClassID

Introduced before R2006a

mxIsNumeric (C and Fortran)

1-535

mxIsScalar (C)Determine whether array is scalar array

C Syntaxinclude matrixhbool mxIsScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray has 1-by-1 dimensions Otherwise it returns logical 0(false)

Note Only use mxIsScalar for mxArray classes with IDs documented by mxClassID

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxisscalarc

See AlsomxClassID | mxGetScalar

1 API Reference

1-536

Introduced in R2015a

mxIsScalar (C)

1-537

mxIsSingle (C and Fortran)Determine whether array represents data as single-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsSingle(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSingle(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as single-precision floating-point numbersand logical 0 (false) otherwise

DescriptionUse mxIsSingle to determine whether the specified array represents its real andimaginary data as single-precision floating-point numbers

In C calling mxIsSingle is equivalent to calling

mxGetClassID(pm) == mxSINGLE_CLASS

1 API Reference

1-538

In Fortran calling mxIsSingle is equivalent to calling

mxGetClassName(pm) eq single

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsSingle (C and Fortran)

1-539

mxIsSparse (C and Fortran)Determine whether input is sparse array

C Syntaxinclude matrixhbool mxIsSparse(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSparse(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a sparse mxArray and logical 0 (false) otherwise Afalse return value means that pm points to a full mxArray or that pm does not point to avalid mxArray

DescriptionUse mxIsSparse to determine whether pm points to a sparse mxArray Many routines(for example mxGetIr and mxGetJc) require a sparse mxArray as input

1 API Reference

1-540

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

See Alsosparse mxGetIr mxGetJc mxCreateSparse

Introduced before R2006a

mxIsSparse (C and Fortran)

1-541

mxIsStruct (C and Fortran)Determine whether input is structure array

C Syntaxinclude matrixhbool mxIsStruct(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsStruct(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a structure mxArray and logical 0 (false) otherwise

DescriptionUse mxIsStruct to determine whether pm points to a structure mxArray Many routines(for example mxGetFieldNameByNumber and mxSetField) require a structuremxArray as an argument

1 API Reference

1-542

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldNameByNumbermxGetField mxSetField

Introduced before R2006a

mxIsStruct (C and Fortran)

1-543

mxIsUint16 (C and Fortran)Determine whether array represents data as unsigned 16-bit integers

C Syntaxinclude matrixhbool mxIsUint16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint16 to determine whether the specified mxArray represents its real andimaginary data as 16-bit unsigned integers

In C calling mxIsUint16 is equivalent to calling

mxGetClassID(pm) == mxUINT16_CLASS

1 API Reference

1-544

In Fortran calling mxIsUint16 is equivalent to calling

mxGetClassName(pm) eq uint16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint16 (C and Fortran)

1-545

mxIsUint32 (C and Fortran)Determine whether array represents data as unsigned 32-bit integers

C Syntaxinclude matrixhbool mxIsUint32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint32 to determine whether the specified mxArray represents its real andimaginary data as 32-bit unsigned integers

In C calling mxIsUint32 is equivalent to calling

mxGetClassID(pm) == mxUINT32_CLASS

1 API Reference

1-546

In Fortran calling mxIsUint32 is equivalent to calling

mxGetClassName(pm) eq uint32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint64

Introduced before R2006a

mxIsUint32 (C and Fortran)

1-547

mxIsUint64 (C and Fortran)Determine whether array represents data as unsigned 64-bit integers

C Syntaxinclude matrixhbool mxIsUint64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint64 to determine whether the specified mxArray represents its real andimaginary data as 64-bit unsigned integers

In C calling mxIsUint64 is equivalent to calling

mxGetClassID(pm) == mxUINT64_CLASS

1 API Reference

1-548

In Fortran calling mxIsUint64 is equivalent to calling

mxGetClassName(pm) eq uint64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint32

Introduced before R2006a

mxIsUint64 (C and Fortran)

1-549

mxIsUint8 (C and Fortran)Determine whether array represents data as unsigned 8-bit integers

C Syntaxinclude matrixhbool mxIsUint8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 8-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint8 to determine whether the specified mxArray represents its real andimaginary data as 8-bit unsigned integers

In C calling mxIsUint8 is equivalent to calling

mxGetClassID(pm) == mxUINT8_CLASS

1 API Reference

1-550

In Fortran calling mxIsUint8 is equivalent to calling

mxGetClassName(pm) eq uint8

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint8 (C and Fortran)

1-551

mxLogical (C)Type for logical array

DescriptionAll logical mxArrays store their data elements as mxLogical rather than as bool

The header file containing this type is

include matrixh

See AlsomxCreateLogicalArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

Introduced before R2006a

1 API Reference

1-552

mxMalloc (C and Fortran)Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxMalloc(mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxMalloc(n)mwSize n

Argumentsn

Number of bytes to allocate for n greater than 0

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxMalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxMalloc is unsuccessful when there is insufficient free heap space

If you call mxMalloc in C with value n = 0 MATLAB returns either NULL or a validpointer

mxMalloc (C and Fortran)

1-553

DescriptionmxMalloc allocates contiguous heap space sufficient to hold n bytes To allocate memoryin MATLAB applications use mxMalloc instead of the ANSI C malloc function

In MEX files but not MAT or engine applications mxMalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

1 API Reference

1-554

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxRealloc

Introduced before R2006a

mxMalloc (C and Fortran)

1-555

mxRealloc (C and Fortran)Reallocate dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxRealloc(void ptr mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxRealloc(ptr size)mwPointer ptrmwSize size

Argumentsptr

Pointer to a block of memory allocated by mxCalloc mxMalloc or mxReallocsize

New size of allocated memory in bytes

ReturnsPointer to the start of the reallocated block of memory if successful If unsuccessful in aMAT or engine standalone application mxRealloc returns NULL in C (0 in Fortran) andleaves the original memory block unchanged (Use mxFree to free the original memoryblock) If unsuccessful in a MEX file the MEX file terminates and control returns to theMATLAB prompt

mxRealloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-556

DescriptionmxRealloc changes the size of a memory block that has been allocated with mxCallocmxMalloc or mxRealloc To allocate memory in MATLAB applications use mxReallocinstead of the ANSI C realloc function

mxRealloc changes the size of the memory block pointed to by ptr to size bytes Thecontents of the reallocated memory are unchanged up to the smaller of the new and oldsizes The reallocated memory might be in a different location from the original memoryso the returned pointer can be different from ptr If the memory location changesmxRealloc frees the original memory block pointed to by ptr

If size is greater than 0 and ptr is NULL in C (0 in Fortran) mxRealloc behaves likemxMalloc mxRealloc allocates a new block of memory of size bytes and returns apointer to the new block

If size is 0 and ptr is not NULL in C (0 in Fortran) mxRealloc frees the memorypointed to by ptr and returns NULL in C (0 in Fortran)

In MEX files but not MAT or engine applications mxRealloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

mxRealloc (C and Fortran)

1-557

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxMalloc

Introduced before R2006a

1 API Reference

1-558

mxRemoveField (C and Fortran)Remove field from structure array

C Syntaxinclude matrixhvoid mxRemoveField(mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhsubroutine mxRemoveField(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Number of the field you want to remove In C to remove the first field setfieldnumber to 0 to remove the second field set fieldnumber to 1 and so on InFortran to remove the first field set fieldnumber to 1 to remove the second fieldset fieldnumber to 2 and so on

DescriptionCall mxRemoveField to remove a field from a structure array If the field does not existnothing happens This function does not destroy the field values To destroy the actualfield values call mxRemoveField and then call mxDestroyArray

Consider a MATLAB structure initialized to

mxRemoveField (C and Fortran)

1-559

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test In Fortran the field number 1represents the field name field number 2 represents field billing field number 3represents field test

See AlsomxAddField mxDestroyArray mxGetFieldByNumber

Introduced before R2006a

1 API Reference

1-560

mxSetCell (C and Fortran)Set contents of cell array

C Syntaxinclude matrixhvoid mxSetCell(mxArray pm mwIndex index mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetCell(pm index value)mwPointer pm valuemwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Index from the beginning of the mxArray Specify the number of elements betweenthe first cell of the mxArray and the cell you want to set The easiest way to calculateindex in a multidimensional cell array is to call mxCalcSingleSubscript

valuePointer to new value for the cell You can put an mxArray of any type into a cell Youcan even put another cell mxArray into a cell

DescriptionCall mxSetCell to put the designated value into a particular cell of a cell mxArray

mxSetCell (C and Fortran)

1-561

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxDestroyArray on the pointer returned by mxGetCellbefore you call mxSetCell

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray mxCreateCellMatrix mxGetCell mxIsCellmxDestroyArray

Introduced before R2006a

1 API Reference

1-562

mxSetClassName (C)Structure array to MATLAB object array

Note Use mxSetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhint mxSetClassName(mxArray array_ptr const char classname)

Argumentsarray_ptr

Pointer to an mxArray of class mxSTRUCT_CLASSclassname

Object class to which to convert array_ptr

Returns0 if successful and nonzero otherwise One cause of failure is that array_ptr is not astructure mxArray Call mxIsStruct to determine whether array_ptr is a structure

DescriptionmxSetClassName converts a structure array to an object array to be saved later to aMAT-file MATLAB does not register or validate the object until it is loaded by the LOADcommand If the specified classname is an undefined class within MATLAB LOADconverts the object back to a simple structure array

mxSetClassName (C)

1-563

See AlsomxIsClass mxGetClassID mxIsStruct

Introduced before R2006a

1 API Reference

1-564

mxSetData (C and Fortran)Set pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxSetData(mxArray pm void pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetData(pm pr)mwPointer pm pr

Argumentspm

Pointer to an mxArraypr

Pointer to an array Each element in the array contains the real component of avalue The array must be in dynamic memory call mxCalloc to allocate thismemory Do not use the ANSI C calloc function which can cause memoryalignment issues leading to program termination

DescriptionmxSetData is like mxSetPr except that in C its second argument is a void Use thisfunction on numeric arrays with contents other than double

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetData before you callmxSetData

mxSetData (C and Fortran)

1-565

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatac

See AlsomxCalloc mxFree mxGetData mxSetPr

Introduced before R2006a

1 API Reference

1-566

mxSetDimensions (C and Fortran)Modify number of dimensions and size of each dimension

C Syntaxinclude matrixhint mxSetDimensions(mxArray pm const mwSize dims mwSize ndim)

Fortran Syntaxinclude fintrfhinteger4 mxSetDimensions(pm dims ndim)mwPointer pmmwSize ndimmwSize dims(ndim)

Argumentspm

Pointer to an mxArraydims

Dimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray In most cases there are ndim elements in the dimsarray

ndimNumber of dimensions

mxSetDimensions (C and Fortran)

1-567

Returns0 on success and 1 on failure mxSetDimensions allocates heap space to hold the inputsize array So it is possible (though unlikely) that increasing the number of dimensionscan cause the system to run out of heap space

DescriptionCall mxSetDimensions to reshape an existing mxArray mxSetDimensions is likemxSetM and mxSetN however mxSetDimensions provides greater control for reshapingan mxArray that has more than two dimensions

mxSetDimensions does not allocate or deallocate any space for the pr or pi arrays Soif your call to mxSetDimensions increases the number of elements in the mxArrayenlarge the pr (and pi if it exists) arrays accordingly

If your call to mxSetDimensions reduces the number of elements in the mxArray youcan optionally reduce the size of the pr and pi arrays using mxRealloc

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetdimensionsfF

See AlsomxGetNumberOfDimensions mxSetM mxSetN mxRealloc

Introduced before R2006a

1 API Reference

1-568

mxSetField (C and Fortran)Set field value in structure array given index and field name

C Syntaxinclude matrixhvoid mxSetField(mxArray pm mwIndex index const char fieldname mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetField(pm index fieldname pvalue)mwPointer pm pvaluemwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of an element in the array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an index

mxSetField (C and Fortran)

1-569

fieldnameName of a field in the structure The field must exist in the structure CallmxGetFieldNameByNumber or mxGetFieldNumber to determine existing fieldnames

pvaluePointer to an mxArray containing the data you want to assign to fieldname

DescriptionUse mxSetField to assign the contents of pvalue to the field fieldname of elementindex

If you want to replace the contents of fieldname first free the memory of the existingdata Use the mxGetField function to get a pointer to the field call mxDestroyArray onthe pointer then call mxSetField to assign the new value

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then call mxSetFieldon each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

1 API Reference

1-570

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldmxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetFieldByNumber mxDestroyArray mxCalcSingleSubscript

Alternatives

C Language

In C you can replace the statements

field_num = mxGetFieldNumber(pa fieldname)mxSetFieldByNumber(pa index field_num new_value_pa)

with a call to mxSetField

mxSetField(pa index fieldname new_value_pa)

Fortran Language

In Fortran you can replace the statements

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

with a call to mxSetField

mxSetField(pm index fieldname newvalue)

Introduced before R2006a

mxSetField (C and Fortran)

1-571

mxSetFieldByNumber (C and Fortran)Set field value in structure array given index and field number

C Syntaxinclude matrixhvoid mxSetFieldByNumber(mxArray pm mwIndex index int fieldnumber mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetFieldByNumber(pm index fieldnumber pvalue)mwPointer pm pvaluemwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an indexfieldnumber

Position of the field in the structure The field must exist in the structure

1 API Reference

1-572

In C the first field within each element has a fieldnumber of 0 The fieldnumberof the last is N-1 where N is the number of fields

In Fortran the first field within each element has a fieldnumber of 1 Thefieldnumber of the last is N where N is the number of fields

pvaluePointer to the mxArray containing the data you want to assign

DescriptionUse mxSetFieldByNumber to assign the contents of pvalue to the field specified byfieldnumber of element index mxSetFieldByNumber is like mxSetField howeverthe function identifies the field by position number not by name

If you want to replace the contents at fieldnumber first free the memory of the existingdata Use the mxGetFieldByNumber function to get a pointer to the field callmxDestroyArray on the pointer then call mxSetFieldByNumber to assign the newvalue

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then callmxSetFieldByNumber on each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

mxSetFieldByNumber (C and Fortran)

1-573

Alternatives

C Language

In C calling

mxSetField(pa index field_name new_value_pa)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxSetFieldByNumber(pa index field_num new_value_pa)

Fortran Language

In Fortran calling

mxSetField(pm index fieldname newvalue)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldByNumbermxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxDestroyArray mxCalcSingleSubscript

Introduced before R2006a

1 API Reference

1-574

mxSetImagData (C and Fortran)Set pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxSetImagData(mxArray pm void pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetImagData(pm pi)mwPointer pm pi

Argumentspm

Pointer to an mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory errors will result when the array is destroyed

DescriptionmxSetImagData is like mxSetPi except that in C its pi argument is a void Usethis function on numeric arrays with contents other than double

mxSetImagData (C and Fortran)

1-575

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetImagData beforeyou call mxSetImagData

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxCalloc mxFree mxGetImagData mxSetPi

Introduced before R2006a

1 API Reference

1-576

mxSetIr (C and Fortran)IR array of sparse array

C Syntaxinclude matrixhvoid mxSetIr(mxArray pm mwIndex ir)

Fortran Syntaxinclude fintrfhsubroutine mxSetIr(pm ir)mwPointer pm ir

Argumentspm

Pointer to a sparse mxArrayir

Pointer to the ir array The ir array must be sorted in column-major order

DescriptionUse mxSetIr to specify the ir array of a sparse mxArray The ir array is an array ofintegers the length of the ir array equals the value of nzmax the storage allocated forthe sparse array or nnz the number of nonzero matrix elements

Each element in the ir array indicates a row (offset by 1) at which a nonzero elementcan be found (The jc array is an index that indirectly specifies a column where nonzeroelements can be found See mxSetJc for more details on jc)

mxSetIr (C and Fortran)

1-577

For example suppose that you create a 7-by-3 sparse mxArray named Sparrowcontaining six nonzero elements by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The pr array holds the real data for the sparse matrix which in Sparrow is the five 1sand the one 2 If there is any nonzero imaginary data it is in a pi arraySubscript ir pr jc Comments(21) 1 1 0 Column 1 ir is 1 because row is 2(51) 4 1 2 Column 1 ir is 4 because row is 5(32) 2 1 3 Column 2 ir is 2 because row is 3(23) 1 2 6 Column 3 ir is 1 because row is 2(53) 4 1 Column 3 ir is 4 because row is 5(63) 5 1 Column 3 ir is 5 because row is 6

Notice how each element of the ir array is always 1 less than the row of thecorresponding nonzero element For instance the first nonzero element is in row 2therefore the first element in ir is 1 (that is 2 ndash 1) The second nonzero element is inrow 5 therefore the second element in ir is 4 (5 ndash 1)

The ir array must be in column-major order The ir array must define the row positionsin column 1 (if any) first then the row positions in column 2 (if any) second and so onthrough column N Within each column row position 1 must appear before row position2 and so on

mxSetIr does not sort the ir array for you you must specify an ir array that is alreadysorted

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetIr before you callmxSetIr

1 API Reference

1-578

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateSparse mxGetIr mxGetJc mxSetJc mxFree nzmax nnz

Introduced before R2006a

mxSetIr (C and Fortran)

1-579

mxSetJc (C and Fortran)JC array of sparse array

C Syntaxinclude matrixhvoid mxSetJc(mxArray pm mwIndex jc)

Fortran Syntaxinclude fintrfhsubroutine mxSetJc(pm jc)mwPointer pm jc

Argumentspm

Pointer to a sparse mxArrayjc

Pointer to the jc array

DescriptionUse mxSetJc to specify a new jc array for a sparse mxArray The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

If the jth column of the sparse mxArray has any nonzero elements

bull jc[j] is the index in ir pr and pi (if it exists) of the first nonzero element in thejth column

bull jc[j+1]-1 is the index of the last nonzero element in the jth column

1 API Reference

1-580

bull For the jth column of the sparse matrix jc[j] is the total number of nonzeroelements in all preceding columns

The number of nonzero elements in the jth column of the sparse mxArray is

jc[j+1] - jc[j]

For the jth column of the sparse mxArray jc[j] is the total number of nonzeroelements in all preceding columns The last element of the jc array jc[number ofcolumns] is equal to nnz which is the number of nonzero elements in the entire sparsemxArray

For example consider a 7-by-3 sparse mxArray named Sparrow containing six nonzeroelements created by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The following table lists the contents of the ir jc and pr arraysSubscript ir pr jc Comment(21) 1 1 0 Column 1 contains two nonzero

elements with rows designated byir[0] and ir[1]

(51) 4 1 2 Column 2 contains one nonzeroelement with row designated by ir[2]

(32) 2 1 3 Column 3 contains three nonzeroelements with rows designated byir[3]ir[4] and ir[5]

(23) 1 2 6 There are six nonzero elements in all(53) 4 1 (63) 5 1

mxSetJc (C and Fortran)

1-581

As an example of a much sparser mxArray consider a 1000-by-8 sparse mxArray namedSpacious containing only three nonzero elements The ir pr and jc arrays containthe values listed in this tableSubscript ir pr jc Comment(732) 72 1 0 Column 1 contains no nonzero

elements(503) 49 1 0 Column 2 contains one nonzero

element with row designated by ir[0](645) 63 1 1 Column 3 contains one nonzero

element with row designated by ir[1] 2 Column 4 contains no nonzero

elements 2 Column 5 contains one nonzero

element with row designated by ir[2] 3 Column 6 contains no nonzero

elements 3 Column 7 contains no nonzero

elements 3 Column 8 contains no nonzero

elements 3 There are three nonzero elements in all

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetJc before you callmxSetJc

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-582

See AlsomxCreateSparse mxGetIr mxGetJc mxSetIr mxFree

Introduced before R2006a

mxSetJc (C and Fortran)

1-583

mxSetM (C and Fortran)Set number of rows in array

C Syntaxinclude matrixhvoid mxSetM(mxArray pm mwSize m)

Fortran Syntaxinclude fintrfhsubroutine mxSetM(pm m)mwPointer pmmwSize m

Argumentspm

Pointer to an mxArraym

Number of rows

DescriptionCall mxSetM to set the number of rows in the specified mxArray The term rows meansthe first dimension of an mxArray regardless of the number of dimensions Call mxSetNto set the number of columns

You typically use mxSetM to change the shape of an existing mxArray The mxSetMfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So ifyour calls to mxSetM and mxSetN increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays Call mxRealloc to enlarge them

1 API Reference

1-584

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetN mxRealloc

Introduced before R2006a

mxSetM (C and Fortran)

1-585

mxSetN (C and Fortran)Set number of columns in array

C Syntaxinclude matrixhvoid mxSetN(mxArray pm mwSize n)

Fortran Syntaxinclude fintrfhsubroutine mxSetN(pm n)mwPointer pmmwSize n

Argumentspm

Pointer to an mxArrayn

Number of columns

DescriptionCall mxSetN to set the number of columns in the specified mxArray The term columnsalways means the second dimension of a matrix Calling mxSetN forces an mxArray tohave two dimensions For example if pm points to an mxArray having three dimensionscalling mxSetN reduces the mxArray to two dimensions

You typically use mxSetN to change the shape of an existing mxArray The mxSetNfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So if

1 API Reference

1-586

your calls to mxSetN and mxSetM increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetM

Introduced before R2006a

mxSetN (C and Fortran)

1-587

mxSetNzmax (C and Fortran)Set storage space for nonzero elements

C Syntaxinclude matrixhvoid mxSetNzmax(mxArray pm mwSize nzmax)

Fortran Syntaxinclude fintrfhsubroutine mxSetNzmax(pm nzmax)mwPointer pmmwSize nzmax

Argumentspm

Pointer to a sparse mxArraynzmax

Number of elements mxCreateSparse should allocate to hold the arrays pointed toby ir pr and pi (if it exists) Set nzmax greater than or equal to the number ofnonzero elements in the mxArray but set it to be less than or equal to the number ofrows times the number of columns If you specify an nzmax value of 0 mxSetNzmaxsets the value of nzmax to 1

DescriptionUse mxSetNzmax to assign a new value to the nzmax field of the specified sparsemxArray The nzmax field holds the maximum number of nonzero elements in the sparsemxArray

1 API Reference

1-588

The number of elements in the ir pr and pi (if it exists) arrays must be equal tonzmax Therefore after calling mxSetNzmax you must change the size of the ir pr andpi arrays To change the size of one of these arrays

1 Call mxRealloc with a pointer to the array setting the size to the new value ofnzmax

2 Call the appropriate mxSet routine (mxSetIr mxSetPr or mxSetPi) to establishthe new memory area as the current one

Ways to determine how large to make nzmax are

bull Set nzmax equal to or slightly greater than the number of nonzero elements in asparse mxArray This approach conserves precious heap space

bull Make nzmax equal to the total number of elements in an mxArray This approacheliminates (or at least reduces) expensive reallocations

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetNzmax mxRealloc

Introduced before R2006a

mxSetNzmax (C and Fortran)

1-589

mxSetPi (C and Fortran)Set new imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPi(mxArray pm double pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetPi(pm pi)mwPointer pm pi

Argumentspm

Pointer to a full (nonsparse) mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory leaks and other memory errors might result

DescriptionUse mxSetPi to set the imaginary data of the specified mxArray

Most mxCreate functions optionally allocate heap space to hold imaginary data If youtell an mxCreate function to allocate heap spacemdashfor example by setting theComplexFlag to mxCOMPLEX in C (1 in Fortran) or by setting pi to a non-NULL value in

1 API Reference

1-590

C (a nonzero value in Fortran)mdashyou do not ordinarily use mxSetPi to initialize thecreated mxArrays imaginary elements Rather you call mxSetPi to replace the initialimaginary values with new ones

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPi before you callmxSetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetImagData mxSetPr mxFree

Introduced before R2006a

mxSetPi (C and Fortran)

1-591

mxSetPr (C and Fortran)Set new real data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPr(mxArray pm double pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetPr(pm pr)mwPointer pm pr

Argumentspm

Pointer to a full (nonsparse) mxArraypr

Pointer to the first element of an array Each element in the array contains the realcomponent of a value The array must be in dynamic memory call mxCalloc toallocate this memory Do not use the ANSI C calloc function which can causememory alignment issues leading to program termination If pr points to staticmemory memory leaks and other memory errors can result

DescriptionUse mxSetPr to set the real data of the specified mxArray

All mxCreate calls allocate heap space to hold real data Therefore you do notordinarily use mxSetPr to initialize the real elements of a freshly created mxArrayRather you call mxSetPr to replace the initial real values with new ones

1 API Reference

1-592

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPr before you callmxSetPr

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

See the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetData mxSetPi mxFree

Introduced before R2006a

mxSetPr (C and Fortran)

1-593

mxSetProperty (C and Fortran)Set value of public property of MATLAB object

C Syntaxinclude matrixhvoid mxSetProperty(mxArray pa mwIndex index const char propname const mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetProperty(pa index propname value)mwPointer pa valuemwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you are assigning

valuePointer to the mxArray you are assigning

1 API Reference

1-594

DescriptionUse mxSetProperty to assign a value to the specified property In pseudo-Cterminology mxSetProperty performs the assignment

pa[index]propname = value

Property propname must be an existing public property and index must be within thebounds of the mxArray To test the index value use mxGetNumberOfElements ormxGetM and mxGetN functions

mxSetProperty makes a copy of the value before assigning it as the new property valueMaking a copy might be a concern if the property uses a large amount of memory Theremust be sufficient memory (in the heap) to hold the copy of the value

Limitationsbull mxSetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

See AlsomxGetProperty

Introduced in R2008a

mxSetProperty (C and Fortran)

1-595

Page 4: C and Fortran API Reference

API Reference1

v

Contents

API Reference

1

matlabdataArrayDimensionsType specifying array dimensions

DescriptionUse the ArrayDimensions type to specify the size of an array ArrayDimensions isspecified as

using ArrayDimensions = stdvectorltsize_tgt

Free Function

getNumElementsinline size_t getNumElements(const ArrayDimensionsamp dims)

Determine the number of elements based on the ArrayDimensions

const ArrayDimensionsampdims

Array dimensions

inline size_t Number of elements

None

See Also

TopicsldquoMATLAB Data API Typesrdquo

1 API Reference

1-2

Introduced in R2017b

matlabdataArrayDimensions

1-3

matlabdataArrayElementRefC++ class representing element of Array or ReferenceltArraygt object

DescriptionAn ArrayElementRef object is created when using operator[] into an Array or aReferenceltArraygt It is untyped since Array and ReferenceltArraygt do not havetype information It collects up the indexes specified by the user and can be cast to anelement if the array holds primitive data or can be used to create a ReferenceltTgtinstance

Indexing is zero-based

Class DetailsNamespace matlabdataInclude ArrayElementRefhpp

Template Parametersbool is_const_ref Indicates if this reference is const The non-const

version of this class supports assignment

Other Operatorsbull ldquooperator[]rdquo on page 1-4bull ldquooperator Trdquo on page 1-5bull ldquooperator=rdquo on page 1-6

operator[]ArrayElementRefltis_const_refgt operator[](size_t idx)

ArrayElementRefltis_const_refgt operator[](stdstring idx)

1 API Reference

1-4

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indices in anindexing operation

stdstring idx Index to add Array must support string indexing

TooManyIndicesProvidedException

Too many indices provided The number of size_tindices is more than the number of dimensions in thearray

StringIndexMustBeLastException

String index is not the last index A size_t index isprovided after a string index

StringIndexNotValidException

An stdstring index is not valid for this array

CanOnlyUseOneStringIndexException

More than one stdstring index provided

double val = arr[2][7][f1]

operator Ttemplate lttypename Tgtoperator T() const

Cast a value Throws an error if not arithmetic complex or stdstring

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain the type specifiedby T

Array dblArray_const = factorycreateArrayltdoublegt(22)double val = dblArray_const[1][2]

matlabdataArrayElementRef

1-5

operator=template lttypename TgtArrayElementRefltis_const_refgtamp operator= (T rhs)

Assign a primitive or complex type to an element of an Array The Array must be non-const

If the Array contains other Arrays then operator= can assign an Array into theelement

T rhs The value to assign to an element in the Array specifiedas a primitive or complex type or as an Array

ArrayElementRefltis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain a primitive orcomplex type or does not contain other Arrays

Assign numeric types to Array arr

Array arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55arr[1][2] = stdcomplexltdoublegt(54 31)

Assign an Array to cell_arr then create a ReferenceltArraygt ref to the element

Array cell_arr = factorycreateArrayltArraygt(13)cell_arr[2] = factorycreateScalar(true)ReferenceltArraygt ref = cell_arr[2]

See AlsoArray | ArrayElementTypedRef | Reference | TypedArrayRef

1 API Reference

1-6

Introduced in R2017b

matlabdataArrayElementRef

1-7

matlabdataArrayElementTypedRefC++ class representing element of TypedArray or TypedArrayRef object

DescriptionAn ArrayElementTypedRef object is created when using operator[] into aTypedArrayltTgt or a TypedArrayRefltTgt It collects up the indexes specified by theuser and can be cast to ltTgt without the added cost of type checking that exists whenusing ArrayElementRef Primitive types can be cast to Tamp which is not supported withArrayElementRef The non-const version of this class supports assignment

Class DetailsNamespace matlabdataInclude ArrayElementTypedRefhpp

Template ParametersT Element typesbool is_const_ref TBD

Other Operatorsbull ldquooperator[]rdquo on page 1-8bull ldquooperator referencerdquo on page 1-9bull ldquooperator=rdquo on page 1-10

operator[]ArrayElementTypedRefltT is_const_refgt operator[](size_t idx)

ArrayElementTypedRefltArray is_const_refgt operator[](stdstringidx)

1 API Reference

1-8

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indicesin an indexing operation

stdstring idx Index to add Array must support string indexing

ArrayElementTypedRefltArray is_const_refgt

New instance with the additional index

TooManyIndicesProvidedException

Too many indices provided

StringIndexMustBeLastException

String index is not the last index

double val = arr[2][7][3]

operator referenceoperator reference() const

operator stdstring() const

Cast to reference to its primitive value

T

stdstring

The value

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

double val = dblArray[1][2]

stdstring val = strArray[1][2]

matlabdataArrayElementTypedRef

1-9

operator=ArrayElementTypedRefltT is_const_refgtamp operator= (T rhs)

ArrayElementTypedRefltT is_const_refgtamp operator= (stdstring rhs)

Assign a value into an Array The Array must be non-const

T rhs

stdstring rhs

Value to assign to an element in the Array

ArrayElementTypedRefltTis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

arr[1][2] = stdcomplexltdoublegt(54 31)

arr[1][2] = MyString

ExamplesTBD

TypedArrayltdoublegt arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55doubleamp val = arr[0][0]CellArray cell_arr = factorycreateArrayltArraygt(12)cell_arr[0] = factorycreateScalar(105)cell_arr[1] = factorycreateScalar(false)ArrayRef ref_to_element = cell_arr[0]TypedArrayRefltdoublegt typed_ref_to_element = cell_arr[0]

1 API Reference

1-10

Array const shared_copy_of_element = cell_arr[1]TypedArrayltboolgt const typed_shared_copy_of_element = cell_arr[1]

See AlsoArray | ArrayElementRef | ArrayElementTypedRef | Reference |TypedArrayRef | TypedIterator

Introduced in R2017b

matlabdataArrayElementTypedRef

1-11

matlabdataArrayFactoryC++ class to create arrays

DescriptionUse ArrayFactory to create matlabdataArray objects

Class DetailsNamespace matlabdataInclude ArrayFactoryhpp

Constructors

Default Constructor

ArrayFactory()

FailedToLoadLibMatlabDataArrayException

Concrete implementation has not been loaded

Destructor~ArrayFactory()

Member Functionsbull ldquocreateArrayrdquo on page 1-13bull ldquocreateScalarrdquo on page 1-14bull ldquocreateCellArrayrdquo on page 1-15

1 API Reference

1-12

bull ldquocreateCharArrayrdquo on page 1-16bull ldquocreateStructArrayrdquo on page 1-17bull ldquocreateEnumArrayrdquo on page 1-18bull ldquocreateSparseArrayrdquo on page 1-19bull ldquocreateEmptyArrayrdquo on page 1-20bull ldquocreateBufferrdquo on page 1-21bull ldquocreateArrayFromBufferrdquo on page 1-21

createArraytemplate lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims)

template lttypename ItType typename TgtTypedArrayltTgt createArray(ArrayDimensions dims ItType begin ItType end)

template lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims const T const begin const T const end)

template lttypename Tgt TypedArrayltTgt createArray(ArrayDimensions dims stdinitializer_listltTgt data)

Creates a TypedArrayltTgt with the given dimensions Fills the array with data ifspecified Data is copied and must be in column major order

bull ItType - Iterator types specified as stditeratorbull T - Element types specified as one of the following C++ data types

bool int8_t int16_t int32_t int64_t uint8_tuint16_t uint32_t uint64_t float double char16_t

matlabdataArrayFactory

1-13

matlabdataString

stdcomplexltdoublegt

stdcomplexltfloatgt

stdcomplexltint8_tgt

stdcomplexltuint8_tgt

stdcomplexltint16_tgt

stdcomplexltuint16_tgt

stdcomplexltint32_tgt

stdcomplexltuint32_tgt

stdcomplexltint64_tgt

stdcomplexltuint64_tgt

matlabdataMATLABString

ArrayDimensionsdims

Dimensions for the array

ItType begin

ItType end

Start and end of the user supplied data The data type isdetermined by the value_type of the iterator

const T constbegin

const T const end

Start and end of the user supplied data specified as C-stylepointer Supports all primitive types complex types andstring types

stdinitializer_listltTgt

Initializer list containing the data

matlabOutOfMemoryException

The array could not be allocated

createScalartemplate lttypename TgtTypedArrayltTgt createScalar(const T val)

TypedArrayltStringgt createScalar(const String val)

TypedArrayltStringgt createScalar(const stdstring val)

Creates a scalar TypedArrayltTgt with the given value This method supports arithmetictypes complex types and string types

const T val Value to be inserted into the scalar If valis 7-bit ASCII data then the methodconverts it to UTF16

const String valconst stdstring val

1 API Reference

1-14

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory

Create a vector containing 2 scalar values stdvectorltmatlabdataArraygt args( factorycreateScalarltint16_tgt(100) factorycreateScalarltint16_tgt(60)) return 0

ldquoCall Function with Single Returned Argumentrdquo

createCellArrayCellArrayltArraygt createCellArray(ArrayDimensions dims)

template lttypename TargsgtCellArrayltArraygt createCellArray(ArrayDimensions dims Targs data)

Creates a CellArray with the specified data Data is specified in column major order

Targs Variadic template of

bull arithmetic typebull complex typebull matlabdataStringbull stdstringbull matlabdataArray

matlabdataArrayFactory

1-15

ArrayDimensionsdims

Dimensions of the cell array

Targs data Elements to be inserted into the cell array specified as aprimitive complex type string or Array

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f CellArray myArray = fcreateCellArray( 12 fcreateCharArray(MATLAB Cell Array) fcreateArrayltdoublegt( 22 12 22 32 42 ))

return 0

createCharArrayCharArray createCharArray(String str)

CharArray createCharArray(stdstring str)

Creates a 1xn CharArray from the specified input where n is the string length

matlabdataString str

Data to be filled into the array

stdstring str

matlabOutOfMemoryException

The array could not be allocated

1 API Reference

1-16

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) return 0

createStructArrayStructArray createStructArray(ArrayDimensions dims stdvectorltstdstringgt fieldNames)

Creates a StructArray with the given dimensions and field names

ArrayDimensions dims Dimensions for the arraystdvectorltstdstringgtfieldNames

Vector of the field names for the structure

matlabOutOfMemoryException

The array could not be allocated

DuplicateFieldNameInStructArrayException

Duplicate field names specified

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f

Create StructArray equivalent to MATLAB structure s s = struct(loc east west data [1 2 3] [4 5 6 7 8]) StructArray S = fcreateStructArray( 12 loc data ) S[0][loc] = fcreateCharArray(east) S[0][data] = fcreateArrayltuint8_tgt( 1 3 1 2 3 )

matlabdataArrayFactory

1-17

S[1][loc] = fcreateCharArray(west) S[1][data] = fcreateArrayltdoublegt( 1 5 4 5 6 7 8 )

Access the value defined by the MATLAB statement s(1)data ReferenceltArraygt val = S[0][data] return 0

createEnumArrayEnumArray createEnumArray(ArrayDimensions dims stdstring className stdvectorltstdstringgt enums)

EnumArray createEnumArray(ArrayDimensions dims stdstring className)

Creates an EnumArray of type className If specified the array is initialized with thelist of enumeration names

ArrayDimensionsdims

Dimensions for the array

stdstringclassName

Class name of the enumeration array

stdvectorltstdstringgt enums

List of the enumeration names

matlabOutOfMemoryException

The array could not be allocated

MustSpecifyClassNameException

Class name not specified

WrongNumberOfEnumsSuppliedException

The wrong number of enumerations provided

include MatlabDataArrayhppinclude ltvectorgt

1 API Reference

1-18

int main() using namespace matlabdata ArrayFactory f auto blue = fcreateEnumArray( 11 TextColor Blue )

Create an argument vector stdvectorltArraygt args( fcreateCharArray(My text) stdmove(blue) )

return 0

createSparseArraytemplate lttypename TgtSparseArrayltTgt createSparseArray(ArrayDimensions dims size_t nnz buffer_ptr_tltTgt data buffer_ptr_tltsize_tgt rows buffer_ptr_tltsize_tgt cols)

Creates a SparseArrayltTgt with rows-by-cols dimensions Only two dimensions areallowed for sparse arrays The buffer is not copied and the array takes ownership

T Element types specified as double bool orstdcomplexltdoublegt

ArrayDimensionsdims

Dimensions for the array

size_t nnz Number of nonzero elementsbuffer_ptr_tltTgtdata

Buffer containing the nonzero elements

buffer_ptr_tltsize_tgt rows

Buffer containing the row value for each element

buffer_ptr_tltsize_tgt cols

Buffer containing the column value for each element

matlabdataArrayFactory

1-19

matlabOutOfMemoryException

The array could not be allocated

InvalidDimensionsInSparseArrayException

More than two dimensions are specified

include MatlabDataArrayhpp

int main() stdvectorltdoublegt data = 35 1298 2176 stdvectorltsize_tgt rows = 001 stdvectorltsize_tgt cols = 048 size_t nnz = 3

matlabdataArrayFactory factory auto data_p = factorycreateBufferltdoublegt(nnz) auto rows_p = factorycreateBufferltsize_tgt(nnz) auto cols_p = factorycreateBufferltsize_tgt(nnz)

double dataPtr = data_pget() size_t rowsPtr = rows_pget() size_t colsPtr = cols_pget() stdfor_each(databegin() dataend() [amp](const doubleamp e) (dataPtr++) = e ) stdfor_each(rowsbegin() rowsend() [amp](const size_tamp e) (rowsPtr++) = e ) stdfor_each(colsbegin() colsend() [amp](const size_tamp e) (colsPtr++) = e )

matlabdataSparseArrayltdoublegt arr = factorycreateSparseArrayltdoublegt( 29 nnz stdmove(data_p) stdmove(rows_p) stdmove(cols_p)) return 0

createEmptyArrayArray createEmptyArray()

Creates an empty Array containing no elements

Array Empty array

1 API Reference

1-20

matlabOutOfMemoryException

The array could not be allocated

createBuffertemplate lttypename Tgtbuffer_ptr_tltTgt createBuffer(size_t numberOfElements)

Creates a buffer which can be passed into createArrayFromBuffer No data copies aremade when creating an array from a buffer Data must be in column major order

T Primitive types

size_t numberOfElements Number of elements not the actualbuffer size

buffer_ptr_tltTgt Unique_ptr containing the buffer

matlabOutOfMemoryException

The array could not be allocated

createArrayFromBuffertemplate lttypename TgtTypedArrayltTgt createArrayFromBuffer(ArrayDimensions dims buffer_ptr_tltTgt buffer)

Creates a TypedArrayltTgt using the given buffer

T Primitive types

ArrayDimensions dims Dimensions for the arraybuffer_ptr_tltTgt buffer Buffer containing the data The buffer is not

copied The TypedArrayltTgt object takesownership of the buffer Data must be in columnmajor order

matlabdataArrayFactory

1-21

matlabOutOfMemoryException

The array could not be allocated

See Also

Introduced in R2017b

1 API Reference

1-22

matlabdataReferenceltArraygtC++ class to get reference to Array

DescriptionUse the ReferenceltArraygt class to get a reference to an Array element of a containerobject such as a MATLAB structure or cell array The class is a base class for allreference types that refer to arrays and provides basic array information ArrayRef isdefined as

using ArrayRef = ReferenceltArraygt

Class DetailsNamespace matlabdataInclude ArrayReferenceExthpp

Member Functionsbull ldquogetTyperdquo on page 1-23bull ldquogetDimensionsrdquo on page 1-24bull ldquogetNumberOfElementsrdquo on page 1-24bull ldquoisEmptyrdquo on page 1-24

getTypeArrayType getType() const

ArrayType Type of the array

NotEnoughIndicesProvidedException

Not enough indices provided

matlabdataReferenceltArraygt

1-23

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

InvalidArrayTypeException

Array type not recognized

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Array dimensions vector

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

getNumberOfElementssize_t getNumberOfElements() const

size_t Number of elements in array

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

isEmptybool isEmpty() const

bool Returns true if array is empty otherwise returns false

NotEnoughIndicesProvidedException

Not enough indices provided

1 API Reference

1-24

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-25bull ldquogetWritableElementsrdquo on page 1-25

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are const

const ReferenceltArraygtampref

ReferenceltArraygt

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are non-const

ReferenceltArraygtamp ref ReferenceltArraygt

matlabdataReferenceltArraygt

1-25

RangeltTypedIterator Tgt Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayType

Introduced in R2017b

1 API Reference

1-26

matlabdataArrayTypeC++ array type enumeration class

DescriptionUse ArrayType objects to identify the data type and other attributes of a MATLABarray

Class DetailsNamespace matlabdataInclude ArrayTypehpp

Enumerationenum class ArrayType UNKNOWN LOGICAL CHAR DOUBLE SINGLE INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 COMPLEX_DOUBLE COMPLEX_SINGLE COMPLEX_INT8 COMPLEX_UINT8 COMPLEX_INT16 COMPLEX_UINT16 COMPLEX_INT32 COMPLEX_UINT32

matlabdataArrayType

1-27

COMPLEX_INT64 COMPLEX_UINT64 CELL STRUCT OBJECT VALUE_OBJECT HANDLE_OBJECT_REF ENUM SPARSE_LOGICAL SPARSE_DOUBLE SPARSE_COMPLEX_DOUBLE MATLAB_STRING

C++ Data Type ConversionMATLAB ArrayType Value C++ Type DescriptionDOUBLE double double-precision (64-bit)

floating-point numberSINGLE float single-precision (32-bit)

floating-point numberINT8 int8_t signed 8-bit integerUINT8 uint8_t unsigned 8-bit integerINT16 int16_t signed 16-bit integerUINT16 uint16_t unsigned 16-bit integerINT32 int32_t signed 32-bit integerUINT32 uint32_t unsigned 32-bit integerINT64 int64_t signed 64-bit integerUINT64 uint64_t unsigned 64-bit integerCHAR char16_t 16-bit characterLOGICAL bool logicalCOMPLEX_DOUBLE stdcomplexltdoublegt complex double-precision

(64-bit) floating-pointnumber

1 API Reference

1-28

MATLAB ArrayType Value C++ Type DescriptionCOMPLEX_SINGLE stdcomplexltfloatgt complex single precision

(32-bit) floating-pointnumber

COMPLEX_INT8 stdcomplexltint8_tgt complex signed 8-bitinteger

COMPLEX_UINT8 stdcomplexltuint8_tgt complex unsigned 8-bitinteger

COMPLEX_INT16 stdcomplexltint16_tgt complex signed 16-bitinteger

COMPLEX_UINT16 stdcomplexltuint16_tgt complex unsigned 16-bitinteger

COMPLEX_INT32 stdcomplexltint32_tgt complex signed 32-bitinteger

COMPLEX_UINT32 stdcomplexltuint32_tgt complex unsigned 32-bitinteger

COMPLEX_INT64 stdcomplexltint64_tgt complex signed 64-bitinteger

COMPLEX_UINT64 stdcomplexltuint64_tgt complex unsigned 64-bitinteger

CELL matlabdataArray Array containing otherArrays

STRUCT matlabdataStruct Array with named fieldsthat can contain data ofvarying types and sizes

OBJECT matlabdataObject MATLAB objectVALUE_OBJECT matlabdataObject MATLAB value objectHANDLE_OBJECT_REF matlabdataObject Reference to an existing

handle object in MATLABENUM matlabdataEnumerat

ionArray of enumerationvalues

SPARSE_LOGICAL bool Sparse array of logicalSPARSE_DOUBLE double Sparse array of double

matlabdataArrayType

1-29

MATLAB ArrayType Value C++ Type DescriptionSPARSE_COMPLEX_DOUBLE stdcomplexltdoublegt Sparse array of complex

doubleMATLAB_STRING matlabdataMATLABSt

ringMATLAB string

See AlsoArrayVisitors

Introduced in R2017b

1 API Reference

1-30

matlabdataArrayVisitorsFunctions for defining visitor pattern

DetailsNamespace matlabdataInclude ArrayVisitorshpp

Functionsbull ldquoapply_visitorrdquo on page 1-31bull ldquoapply_visitor_refrdquo on page 1-31

apply_visitorauto apply_visitor(Array a V visitor)

TBD

TBD

InvalidArrayTypeException

apply_visitor_refauto apply_visitor_ref(const ArrayRefamp a V visitor)

Apply functor V to Array a

Result of V

matlabdataArrayVisitors

1-31

InvalidArrayTypeException

See Also

Introduced in R2017b

1 API Reference

1-32

matlabdataCellArrayC++ class to access MATLAB cell arrays

DescriptionA CellArray is a TypedArray with Array as the element type Use CellArray objectsto access MATLAB cell arrays To create a CellArray call createCellArrayCellArray is defined as

using CellArray = TypedArrayltArraygt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

ExamplesCreate Cell Array

Create a cell array with two elements

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CellArray cellArray1 = factorycreateCellArray( 12 factorycreateCharArray(MATLAB Cell Array) factorycreateArrayltdoublegt( 22 12 22 32 42 ))

matlabdataCellArray

1-33

return 0

See AlsocreateCellArray

Introduced in R2017b

1 API Reference

1-34

matlabdataCharArrayC++ class to access MATLAB character arrays

DescriptionUse CharArray objects to work with MATLAB character arrays To create a CharArraycall createCharArray

Class DetailsNamespace matlabdataBase class TypedArrayltchar16_tgtInclude CharArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-35bull ldquoCopy Assignment Operatorsrdquo on page 1-36bull ldquoMove Constructorsrdquo on page 1-37bull ldquoMove Assignment Operatorsrdquo on page 1-37

Copy Constructors

CharArray(const CharArrayamp rhs)

CharArray(const Arrayamp rhs)

Creates a shared data copy of a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

matlabdataCharArray

1-35

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray B(A) return 0

createCharArray on page 1-16

Copy Assignment OperatorsCharArrayamp operator=(const CharArrayamp rhs)

CharArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray C = factorycreateCharArray()

1 API Reference

1-36

Arrays A and C refer to the same data C = A

return 0

Move Constructors

CharArray(CharArrayampamp rhs)

CharArray(Arrayampamp rhs)

Moves contents of a CharArray object to a new instance

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move constructor - Creates B copies data from A A not valid CharArray B(stdmove(A))

return 0

Move Assignment Operators

CharArrayamp operator=(CharArrayampamp rhs)

CharArrayamp operator=(Arrayampamp rhs)

matlabdataCharArray

1-37

Assigns the input to this CharArray object

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move assignment - Data from A moved to C A no longer valid CharArray C = factorycreateCharArray() C = stdmove(A)

return 0

Member Functionsbull ldquotoUTF16rdquo on page 1-38bull ldquotoAsciirdquo on page 1-39

toUTF16String toUTF16() const

matlabdataString Contents of CharArray as matlabdataString

None

1 API Reference

1-38

toAsciistdstring toAscii() const

stdstring Contents of CharArray as ASCII string

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f auto arr = fcreateCharArray(helloworld) stdstring s = arrtoAscii()

return 0

ldquoEvaluate Mathematical Function in MATLABrdquo

See AlsoldquocreateCharArrayrdquo on page 1-16 | TypedArray | matlabdataString

Introduced in R2017b

matlabdataCharArray

1-39

matlabdataReferenceltCharArraygtC++ class to get reference to CharArray

DescriptionThe CharArrayExt class extends the APIs available to a reference to a CharArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquotoUTF16rdquo on page 1-40bull ldquotoAsciirdquo on page 1-40

toUTF16String toUTF16() const

matlabdataString Contents of reference to CharArray as a utf16 string

None

toAsciistdstring toAscii() const

stdstring Contents of reference to CharArray asmatlabdataString

1 API Reference

1-40

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

See AlsoCharArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltCharArraygt

1-41

matlabdataEnumArrayC++ class to access MATLAB enumeration arrays

DescriptionUse EnumArray objects to access enumeration arrays To create an EnumArray callcreateEnumArray

Class DetailsNamespace matlabdataBase class TypedArrayltEnumerationgtInclude EnumArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-42bull ldquoCopy Assignment Operatorsrdquo on page 1-43bull ldquoMove Constructorsrdquo on page 1-43bull ldquoMove Assignment Operatorsrdquo on page 1-43

Copy Constructors

EnumArray(const EnumArrayamp rhs)

EnumArray(const Arrayamp rhs)

Creates a shared data copy of an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as EnumArray object

1 API Reference

1-42

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Copy Assignment OperatorsEnumArrayamp operator=(const EnumArrayamp rhs)

EnumArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move ConstructorsEnumArray(EnumArrayampamp rhs)

EnumArray(Arrayampamp rhs)

Moves contents of an EnumArray object to a new instance

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move Assignment OperatorsEnumArrayamp operator=(EnumArrayampamp rhs)

matlabdataEnumArray

1-43

EnumArrayamp operator=(Arrayampamp rhs)

Assigns the input to this EnumArray object

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Member Functions

getClassNamestdstring getClassName() const

Return class name for this EnumArray

stdstring The class name

None

See AlsoldquocreateEnumArrayrdquo on page 1-18 | TypedArray

Introduced in R2017b

1 API Reference

1-44

matlabdataReferenceltEnumArraygtC++ class to get reference to EnumArray

DescriptionThe EnumArrayExt class extends the APIs available to a reference to an EnumArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functions

getClassNamestdstring getClassName() const

Return class name for this reference to an EnumArray object

stdstring Class name

None

See AlsoEnumArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltEnumArraygt

1-45

matlabdataEnumerationElement type for MATLAB enumeration arrays

DescriptionEnumeration is the element type for an EnumArray object

Class DetailsNamespace matlabdataInclude Enumerationhpp

See AlsoEnumArray

TopicsldquoMATLAB Data API Typesrdquo

Introduced in R2017b

1 API Reference

1-46

matlabExceptionC++ base class for exceptions

DescriptionAll MATLAB C++ exceptions can be caught as matlabException

Class DetailsNamespace matlabInclude Exceptionhpp

See Also

TopicsldquoMATLAB Data API Exceptionsrdquo

Introduced in R2017b

matlabException

1-47

matlabdataForwardIteratorltTgtTemplated C++ class to provide forward iterator support for StructArray field names

DescriptionUse ForwardIterator objects to access a range of field name elements in aStructArray

Class DetailsNamespace matlabdataInclude ForwardIteratorhpp

Template ParametersT matlabdataMATLABFieldIdentifier

Constructorsbull ldquoCopy Constructorsrdquo on page 1-48bull ldquoCopy Assignment Operatorsrdquo on page 1-49

Copy Constructors

ForwardIterator(const ForwardIteratorltTgtamp rhs)

Creates a shared data copy of a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to copy

ForwardIterator New instance

1 API Reference

1-48

None

Copy Assignment Operators

ForwardIteratorltTgtamp operator=(const ForwardIteratorltTgtamp rhs)

Assigns a shared data copy to a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to assign

ForwardIteratorltTgt Updated instance

None

Other Operatorsbull ldquooperator++rdquo on page 1-49bull ldquooperator--rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperatorrdquo on page 1-51bull ldquooperator-gtrdquo on page 1-51bull ldquooperator[]rdquo on page 1-51

operator++ForwardIteratorltTgtamp operator++()

Pre-increment operator

ForwardIteratorltTgtamp Reference to updated value

matlabdataForwardIteratorltTgt

1-49

None

operator--ForwardIteratorltTgt operator--(int)

Post-increment operator

ForwardIteratorltTgt New object

None

operator=bool operator==(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if the iterators point to the same elementOtherwise returns false

None

operator=bool operator=(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if this iterator points to a differentelement Otherwise returns false

None

1 API Reference

1-50

operatorreference operator() const

reference Shared copy of element that iterator points to specifiedas

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataForwardIteratorltTgt

1-51

See AlsoMATLABFieldIdentifier | StructArray

Introduced in R2017b

1 API Reference

1-52

matlabdataGetArrayTypeC++ struct TBD

DescriptionUse GetArrayType objects to TBD

Class DetailsNamespace matlabdataInclude GetArrayTypehpp

See Also

Introduced in R2017b

matlabdataGetArrayType

1-53

matlabdataGetReturnTypeC++ struct TBD

DescriptionUse GetReturnType to convert a template argument to the appropriate templateargument when creating a TypedArray

Class DetailsNamespace matlabdataInclude GetReturnTypehpp

See Also

Introduced in R2017b

1 API Reference

1-54

matlabdataMATLABFieldIdentifierC++ class used to identify field names in MATLAB struct array

Description

Class DetailsNamespace matlabdataInclude MATLABFieldIdentifierhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-55bull ldquoConstructorrdquo on page 1-55bull ldquoDestructorrdquo on page 1-56bull ldquoCopy Constructorsrdquo on page 1-56bull ldquoCopy Assignment Operatorsrdquo on page 1-56bull ldquoMove Constructorsrdquo on page 1-57bull ldquoMove Assignment Operatorsrdquo on page 1-57

Default ConstructorMATLABFieldIdentifier()

Construct an empty MATLABFieldIdentifier

None

ConstructorMATLABFieldIdentifier(stdstring str)

matlabdataMATLABFieldIdentifier

1-55

Construct a MATLABFieldIdentifier from stdstring

stdstring str String that contains the field name

Destructor

~MATLABFieldIdentifier()

Destroy a MATLABFieldIdentifier

None

Copy Constructors

MATLABFieldIdentifier(const MATLABFieldIdentifieramp rhs)

Creates a shared data copy of a MATLABFieldIdentifier object

constMATLABFieldIdentifieramprhs

Value to copy

None

Copy Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifier constamp rhs)

Assigns a shared data copy to a MATLABFieldIdentifier object

MATLABFieldIdentifierconstamp rhs

Value to move

1 API Reference

1-56

MATLABFieldIdentifieramp Updated instance

None

Move Constructors

MATLABFieldIdentifier(MATLABFieldIdentifierampamp rhs)

Moves contents a MATLABFieldIdentifier object to a new instance

MATLABFieldIdentifierampamprhs

Value to move

None

Move Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifierampamp rhs)

MATLABFieldIdentifierampamprhs

Value to move

MATLABFieldIdentifieramp Updated instance

None

Destructor~MATLABFieldIdentifier()

Description

Destroy a MATLABFieldIdentifier

matlabdataMATLABFieldIdentifier

1-57

Other Operators

operator stdstringoperator stdstring() const

stdstring Representation of the MATLABFieldIdentifier object

None

Free Functions

operator==bool operator==(const MATLABFieldIdentifieramp rhs) const

Check if two MATLABFieldIdentifier objects are identical

constMATLABFieldIdentifieramprhs

Value to be compared

bool Returns true if the objects are identical Otherwisereturns false

None

See AlsoForwardIterator | StructArray

Introduced in R2017b

1 API Reference

1-58

matlabdataMATLABStringElement type for MATLAB string arrays

DescriptionMATLABString is defined as

using MATLABString = OptionalltStringgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataString

Introduced in R2017b

matlabdataMATLABString

1-59

matlabdataReferenceltMATLABStringgtC++ class to get reference to element of StringArray

DescriptionA ReferenceltMATLABStringgt object is created when using operator[] into anStringArray or dereferenceing a String arrary iterator

Class DetailsNamespace matlabdataInclude MATLABStringReferenceExthpp

Cast

String()operator String() const

matlabdataString Element of a MATLABString array converted toString

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

stdruntime_error Array element does not have a value

1 API Reference

1-60

Member Functionsbull ldquoboolrdquo on page 1-61bull ldquohas_valuerdquo on page 1-61

booloperator bool() const

Check whether string contains a value

operator True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

has_valuebool has_value() const

Check whether string contains a value

bool True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

matlabdataReferenceltMATLABStringgt

1-61

See Also

Introduced in R2017b

1 API Reference

1-62

matlabdataArrayC++ base class for all array types

DescriptionUse Array objects to represent single and multi-dimensional arrays The Array classprovides methods for users to be able to query generic information about all arrays suchas dimensions and type and has methods to create deep copies and shared data copiesUse ArrayFactory methods to construct Arrays Once an Array has been constructedit can be moved or cloned (deep-copied) or a shared-data copy can be created Arrayssupport copy-on-write semantics

Class DetailsNamespace matlabdataInclude MDArrayhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-63bull ldquoCopy Constructorsrdquo on page 1-64bull ldquoCopy Assignment Operatorsrdquo on page 1-64bull ldquoMove Constructorsrdquo on page 1-64bull ldquoMove Assignment Operatorsrdquo on page 1-65

Default Constructor

Array()

None

matlabdataArray

1-63

Copy Constructors

Array(const Arrayamp rhs)

Creates a shared data copy of an Array object

const Arrayamp rhs Value to copy

None

Copy Assignment Operators

Arrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an Array object

const Arrayamp rhsrhs Value to copy

Arrayamp Updated instance

None

Move Constructors

Array(Arrayampamp rhs)

Moves contents of an Array object to a new instance

Arrayampamp rhs Value to move

None

1 API Reference

1-64

Move Assignment Operators

Arrayamp operator=(Arrayampamp rhs)

Assigns the input to this Array object

Arrayampamp rhs Value to move

Arrayamp Updated instance

None

Destructorvirtual ~Array()

Indexing Operators

operator[]ArrayElementRefltfalsegt operator[](size_t idx)

ArrayElementReflttruegt operator[](size_t idx) const

Enables [] indexing on const and non-const arrays Indexing is 0-based

size_t idx First array index

ArrayElementRefltfalsegt Temporary object containing the index specified Thereturn value allows the element of the array to bemodified or retrieved

matlabdataArray

1-65

ArrayElementReflttruegt Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Member Functionsbull ldquogetTyperdquo on page 1-66bull ldquogetDimensionsrdquo on page 1-66bull ldquogetNumberOfElementsrdquo on page 1-66bull ldquoisEmptyrdquo on page 1-67

getTypeArrayType getType() const

ArrayType Array type

None

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Vector of each dimension in the array

None

getNumberOfElementssize_t getNumberOfElements() const

size_t The number of elements in the array

1 API Reference

1-66

None

isEmptybool isEmpty() const

bool True if array is empty False if array is not empty

None

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-67bull ldquogetWritableElementsrdquo on page 1-67

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const Arrayamp arr)

Get a range containing the elements of the Array Iterators contained in the range areconst

const Arrayamp arr Array

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(Arrayamp arr)

matlabdataArray

1-67

Get a range containing the elements of the Array Iterators contained in the range arenon-const

Arrayamp arr Array

RangeltTypedIterator Tgt Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayFactory

Introduced in R2017b

1 API Reference

1-68

matlabdataObjectElement type for MATLAB object arrays

DescriptionObject is the element type for an ObjectArray

Class DetailsNamespace matlabdataInclude Objecthpp

See AlsoObjectArray

Introduced in R2017b

matlabdataObject

1-69

matlabdataObjectArrayC++ class to access MATLAB object arrays

DescriptionUse ObjectArray objects to access MATLAB object arrays You do not create anObjectArray only MATLAB functions create ObjectArrays You can pass anObjectArray to a MATLAB function

ObjectArray is defined as

using ObjectArray = TypedArrayltObjectgt

Class DetailsNamespace matlabdataInclude ObjectArrayhpp

See AlsoObject

Introduced in R2017b

1 API Reference

1-70

matlabdataOptionalltTgtTemplated C++ class representing optional values

DescriptionUse Optional objects to represent values that might or might not exist

Class DetailsNamespace matlabdataInclude Optionalhpp

Template ParametersT Array type specified as matlabdataString

Constructorsbull ldquoDefault Constructorsrdquo on page 1-71bull ldquoCopy Constructorsrdquo on page 1-71bull ldquoCopy Assignment Operatorsrdquo on page 1-72bull ldquoMove Constructorsrdquo on page 1-72bull ldquoMove Assignment Operatorsrdquo on page 1-72

Default Constructors

optional()

Copy Constructors

optional(const optionalamp other)

matlabdataOptionalltTgt

1-71

Creates a shared data copy

const optionalamp other Value to copy

None

Copy Assignment OperatorsoptionalltTgtamp operator=(const optionalltTgtamp other)

Assigns a shared data copy

const optionalltTgtamp other Value to copy

optionalltTgtamp Updated instance

None

Move Constructorsoptional(optionalampamp other)

optional(Tampamp value)

Moves contents of an Optional object to a new instance

optionalampamp other Value to moveTampamp value Value of type T to move

None

Move Assignment OperatorsoptionalltTgtamp operator=(optionalltTgtampamp other)

1 API Reference

1-72

optionalltTgtamp operator=(Tampamp value)

Assigns the input to this instance

optionalltTgtampamp other

Tampamp value

Value to move

optionalltTgtamp Updated instance

None

Other Operatorsbull ldquooperator=rdquo on page 1-73bull ldquooperator-gtrdquo on page 1-74bull ldquooperatorrdquo on page 1-74bull ldquooperator Trdquo on page 1-74

operator=optionalltTgtamp operator=(nullopt_t)

optionalltTgtamp operator=(const optionalltTgtamp other)

optionalltTgtamp operator=(optionalltTgtampamp other)

optionalltTgtamp operator=(Tampamp value)

optionalltTgtamp operator=(const Tamp value)

Assignment operators

optionalltTgtamp Updated instance

None

matlabdataOptionalltTgt

1-73

operator-gtconst T operator-gt() const

T operator-gt()

const T

T

Pointer to the element

stdruntime_error Optional object does not contain a value

operatorconst Tamp operator() const

Tamp operator()

const Tamp

Tamp

Reference to the element

stdruntime_error Optional object does not contain a value

operator Toperator T() const

Cast optionalltTgt value to T

operator Value contained in optionalltTgt if it exists

stdruntime_error There is no value

1 API Reference

1-74

Member Functionsbull ldquoboolrdquo on page 1-75bull ldquohas_valuerdquo on page 1-75bull ldquoswaprdquo on page 1-75bull ldquoresetrdquo on page 1-76

boolexplicit operator bool() const

Check whether object contains a value

operator True if object contains a value

None

has_valuebool has_value() const

Check whether object contains a value

bool True if object contains a value

None

swapvoid swap(optional ampother)

Swap value of this optional instance with value contained in the parameter

optional ampother Value to swap

matlabdataOptionalltTgt

1-75

None

resetvoid reset()

Reset optional value to missing

None

See Also

Introduced in R2017b

1 API Reference

1-76

matlabdataRangeltItTypeElemTypegtTemplated C++ class to provide range-based operation support

DescriptionRange objects wrap begin and end functions to enable range-based operations

Class DetailsNamespace matlabdataInclude Rangehpp

Template ParametersIteratorType Iterator typeElementType Element type

Constructorsbull ldquoConstructorrdquo on page 1-77bull ldquoMove Constructorsrdquo on page 1-78bull ldquoMove Assignment Operatorsrdquo on page 1-78

Constructor

Range(IteratorTypeltElementTypegt begin IteratorTypeltElementTypegtend)

Creates a Range object

matlabdataRangeltItTypeElemTypegt

1-77

IteratorTypeltElementTypegt begin

IteratorTypeltElementTypegt end

First and last elements of range

Range New instance

None

Move Constructors

Range(Rangeampamp rhs)

Moves contents of a Range object to a new instance

Rangeampamp rhs Range to move

Range New instance

None

Move Assignment Operators

Rangeamp operator=(Rangeampamp rhs)

Assigns the input to this Range object

Rangeampamp rhs Range to move

Rangeamp Updated instance

None

1 API Reference

1-78

beginIteratorTypeltElementTypegtamp begin()

ReturnsIteratorTypeltElementTypegtamp

First element in range

None

endIteratorTypeltElementTypegtamp end()

ReturnsIteratorTypeltElementTypegtamp

End of range

None

See Also

Introduced in R2017b

matlabdataRangeltItTypeElemTypegt

1-79

matlabdataReferenceltTgtTemplated C++ class to get references to Array elements

DescriptionA Reference object is a reference to an element of an Array without making a copy AReference is

bull Not a shared copybull Valid as long as the array that contains the reference is validbull Not thread-safe

Class DetailsNamespace matlabdataInclude Referencehpp

Template ParametersT Type of element referred to specified as

bull Arraybull Structbull Enumerationbull MATLABStringbull All stdcomplex types

Constructorsbull ldquoCopy Constructorrdquo on page 1-81bull ldquoCopy Assignment Operatorsrdquo on page 1-81bull ldquoMove Assignment Operatorsrdquo on page 1-81

1 API Reference

1-80

bull ldquoMove Constructorsrdquo on page 1-81

Copy ConstructorReference(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

Copy Assignment OperatorsReferenceltTgtamp operator=(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

ReferenceltTgtamp Updated instance

Move Assignment OperatorsReferenceltTgtamp operator=(ReferenceltTgtampamp rhs)

ReferenceltTgtampamp rhs Value to move

ReferenceltTgtamp Updated instance

None

Move ConstructorsReference(ReferenceltTgtampamp rhs)

Moves contents of a Reference object to a new instance

ReferenceltTgtampamp rhs Value to move

None

matlabdataReferenceltTgt

1-81

Other Operatorsbull ldquooperator=rdquo on page 1-82bull ldquooperatorltltrdquo on page 1-82bull ldquooperator T()rdquo on page 1-83bull ldquooperator stdstring()rdquo on page 1-83

operator=ReferenceltTgtamp operator=(T rhs)

ReferenceltTgtamp operator=(stdstring rhs)

ReferenceltTgtamp operator=(String rhs)

T rhs Value to assign The array being indexed must be non-const

stdstring rhs String to assign The array must be non-const andallow strings to be assigned

String rhs String to assign to StringArray The array beingindexed must be non-const

ReferenceltTgtamp Updated instance

None

operatorltlt

stdostreamamp operator ltlt(stdostreamamp os ReferenceltTgt constamp rhs)

stdostreamamp os ReferenceltTgt constamp rhs

stdostreamamp

1 API Reference

1-82

operator T()operator T() const

Cast to element from the array

T Shared copy of element from the array

None

operator stdstring()operator stdstring() const

Cast to stdstring from the array Makes a copy of the stdstring Only valid fortypes that can be cast to a stdstring

stdstring The string

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

stdruntime_error MATLABString is missing

Free Functions

operator==inline bool operator ==(ReferenceltMATLABStringgt constamp lhsstdstring constamp rhs)

inline bool operator ==(stdstring constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhs Stringconstamp rhs)

matlabdataReferenceltTgt

1-83

inline bool operator ==(String constamp lhs ReferenceltMATLABStringgtconstamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsMATLABString constamp rhs)

inline bool operator ==(MATLABString constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsReferenceltMATLABStringgt constamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhs Tconstamp rhs)

templatelttypename Tgt bool operator ==(T constamp lhs ReferenceltTgtconstamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhsReferenceltTgt constamp rhs)

ReferenceltMATLABStringgtconstamp lhs

stdstring constamp rhs Values tocompare

stdstring constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

String constamp rhs

String constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

MATLABString constamp rhs

MATLABString constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

ReferenceltMATLABStringgtconstamp rhs

ReferenceltTgt constamp lhs T constamp rhsT constamp lhs ReferenceltTgt constamp rhsReferenceltTgt constamp lhs ReferenceltTgt constamp rhs

1 API Reference

1-84

bool Returns true if values are equal

stdruntime_error Cannot compare argument to MATLABString

See Also

TopicsldquoAccess C++ Data Array Container Elementsrdquo

Introduced in R2017b

matlabdataReferenceltTgt

1-85

matlabdataSparseArrayltTgtTemplated C++ class to access data in MATLAB sparse arrays

DescriptionUse SparseArray objects to work with sparse MATLAB arrays To create aSparseArray call createSparseArray

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude SparseArrayhpp

Template ParametersT Type of element referred to specified as

bull boolbull doublebull stdcomplexltdoublegt

Constructorsbull ldquoCopy Constructorsrdquo on page 1-86bull ldquoCopy Assignment Operatorsrdquo on page 1-87bull ldquoMove Constructorsrdquo on page 1-87bull ldquoMove Assignment Operatorsrdquo on page 1-88

Copy Constructors

SparseArray(const SparseArrayltTgtamp rhs)

1 API Reference

1-86

SparseArray(const Arrayamp rhs)

Creates a shared data copy of a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array ofArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Copy Assignment OperatorsSparseArrayamp operator=(const SparseArrayltTgtamp rhs)

SparseArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

Move ConstructorsSparseArray(SparseArrayampamp rhs)

matlabdataSparseArrayltTgt

1-87

SparseArray(Arrayampamp rhs)

Moves contents a SparseArray object to a new instance

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Move Assignment Operators

SparseArrayamp operator=(SparseArrayltTgtampamp rhs)

SparseArrayamp operator=(Arrayampamp rhs)

Assigns the input to this SparseArray object

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

1 API Reference

1-88

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-89bull ldquoEnd Iteratorsrdquo on page 1-89

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functionsbull ldquogetNumberOfNonZeroElementsrdquo on page 1-90

matlabdataSparseArrayltTgt

1-89

bull ldquogetIndexrdquo on page 1-90

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array

size_t Number of nonzero elements in the array

None

getIndexSparseIndex getIndex(const TypedIteratorltTgtamp it)

SparseIndex getIndex(const TypedIteratorltT constgtamp it)

Returns the row-column coordinates of the nonzero entry that the iterator is pointing to

const TypedIteratorltTgtampit

Iterator pointing to the current entry in the sparsematrix

const TypedIteratorltTconstgtamp it

SparseIndex Row-column coordinates of the nonzero entry that theiterator is pointing to SparseIndex is defined asstdpairltsize_t size_tgt

None

See AlsoArray | createSparseArray

1 API Reference

1-90

Introduced in R2017b

matlabdataSparseArrayltTgt

1-91

matlabdataReferenceltSparseArrayltTgtgtTemplated C++ class to get reference to SparseArray

DescriptionUse the ReferenceltSparseArraygt class to get a reference to a SparseArray elementof a container object such as a MATLAB structure or cell array

Class DetailsNamespace matlabdataInclude SparseArrayRefhpp

Template ParametersT Type of elements in SparseArray specified as bool

double or stdcomplexltdoublegt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-92bull ldquoEnd Interatorsrdquo on page 1-93

Begin Interatorsiterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array Iterates over non-zeroelements of the SparseArray

1 API Reference

1-92

None

End Interators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functions

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array Since sparse arrays only storenonzero elements this method returns the actual array size It is different from arraydimensions that specify the full array size

size_t Number of nonzero elements in the array

None

See Also

Introduced in R2017b

matlabdataReferenceltSparseArrayltTgtgt

1-93

matlabdataStringType representing strings as stdbasic_stringltchar16_tgt

DescriptionThe String class defines the element type of a StringArray String is defined as

using String = stdbasic_stringltchar16_tgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

1 API Reference

1-94

matlabdataStringArrayC++ class to access MATLAB string arrays

DescriptionUse StringArray objects to access MATLAB string arrays StringArray is defined as

using StringArray = TypedArrayltMATLABStringgt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

matlabdataStringArray

1-95

matlabdataStructArrayC++ class to access MATLAB struct arrays

DescriptionUse StructArray objects to work with MATLAB struct arrays To access a field for asingle element in the array use the field name To create a StructArray object callcreateStructArray

Class DetailsNamespace matlabdataBase class TypedArrayltStructgtInclude StructArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-96bull ldquoCopy Assignment Operatorsrdquo on page 1-97bull ldquoMove Constructorsrdquo on page 1-97bull ldquoMove Assignment Operatorsrdquo on page 1-98

Copy Constructors

StructArray(const StructArrayamp rhs)

StructArray(const Arrayamp rhs)

Creates a shared data copy of a StructArray object

const StructArrayamp rhs Value to copy

1 API Reference

1-96

const Arrayamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Copy Assignment Operators

StructArrayamp operator=(const StructArrayamp rhs)

StructArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a StructArray object

const StructArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeSTRUCT object

StructArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Move Constructors

StructArray(StructArrayampamp rhs)

StructArray(Arrayampamp rhs)

Moves contents of a StructArray object to a new instance

StructArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

matlabdataStructArray

1-97

Move Assignment OperatorsStructArrayamp operator=(StructArrayampamp rhs)

Assigns the input to this StructArray object

StructArrayampamp rhs Value to move

StructArrayamp Updated instance

None

Destructor~StructArray()

Description

Free memory for StructArray object

Member Functionsbull ldquogetFieldNamesrdquo on page 1-98bull ldquogetNumberOfFieldsrdquo on page 1-99

getFieldNamesRangeltForwardIterator MatlabFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enable access to allfields in StructArray object

None

1 API Reference

1-98

getNumberOfFieldssize_t getNumberOfFields() const

size_t Number of fields

None

ExamplesCreate StructArray

Suppose that you have the following MATLAB structure

s = struct(loc east west data [1 2 3] [4 5 6 7 8])

Create a variable containing the data for loc east

val = s(1)data

The following C++ code creates these variables

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory

StructArray S = factorycreateStructArray( 12 loc data ) S[0][loc] = factorycreateCharArray(east) S[0][data] = factorycreateArrayltuint8_tgt( 1 3 1 2 3 ) S[1][loc] = factorycreateCharArray(west) S[1][data] = factorycreateArrayltdoublegt( 1 5 4 5 6 7 8 )

ReferenceltArraygt val = S[0][data] return 0

bull ldquoCreate Structure Array and Send to MATLABrdquo

matlabdataStructArray

1-99

See AlsoMATLABFieldIdentifier | Range | createStructArray

TopicsldquoCreate Structure Array and Send to MATLABrdquo

Introduced in R2017b

1 API Reference

1-100

matlabdataReferenceltStructArraygtC++ class to get reference to StructArray

DescriptionThe StructArrayExt class extends the APIs available to a reference to a StructArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquogetFieldNamesrdquo on page 1-101bull ldquogetNumberOfFieldsrdquo on page 1-101

getFieldNamesRangeltForwardIterator MATLABFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enables access to allfields in StructArray object

None

getNumberOfFieldssize_t getNumberOfFields() const

matlabdataReferenceltStructArraygt

1-101

size_t Number of fields

None

See AlsoReferenceltTypedArrayltTgtgt | StructArray

Introduced in R2017b

1 API Reference

1-102

matlabdataStructElement type for MATLAB struct arrays

DescriptionStruct is the element type for a StructArray object

Class DetailsNamespace matlabdataInclude Structhpp

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-103bull ldquoEnd Iteratorsrdquo on page 1-103

Begin Iteratorsconst_iterator begin() const

const_iterator cbegin() const

const_iterator Iterator to beginning of list of fields specified asTypedIteratorltArray constgt

None

End Iteratorsconst_iterator end() const

const_iterator cend() const

matlabdataStruct

1-103

const_iterator Iterator to end of list of fields specified asTypedIteratorltArray constgt

None

Indexing Operators

operator[]Array operator[](stdstring idx) const

Enables [] indexing on a StructArray object Indexing is 0-based

stdstring idx Field name

Array Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in this StructArray

See AlsoldquocreateStructArrayrdquo on page 1-17 | StructArray

Introduced in R2017b

1 API Reference

1-104

matlabdataReferenceltStructgtC++ class to get reference to element of StructArray

DescriptionUse the ReferenceltStructgt class to access an element of a StructArray

Class DetailsNamespace matlabdataInclude StructRefhpp

Indexing Operators

operator[]ReferenceltArraygt operator[](stdstring idx)

Array operator[](stdstring idx) const

Index into the Struct with a field name

stdstring idx Field name

ReferenceltArraygt Reference to Array found at specified fieldArray Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in the struct

matlabdataReferenceltStructgt

1-105

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-106bull ldquoEnd Iteratorsrdquo on page 1-106

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

1 API Reference

1-106

Cast

Struct()operator Struct() const

Create a shared copy of the Struct

Struct Shared copy

None

See Also

Introduced in R2017b

matlabdataReferenceltStructgt

1-107

matlabdataTypedArrayltTgtTemplated C++ class to access array data

DescriptionThe templated TypedArray class provides typesafe APIs to handle all array types(except sparse arrays) inside an array This class defines the following iterator types

using iterator = TypedIteratorltTgt

using const_iterator = TypedIteratorltT constgt

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude TypedArrayhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_t

1 API Reference

1-108

uint64_tchar16_tboolstdcomplexltdoublegtstdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorrdquo on page 1-109bull ldquoCopy Assignment Operatorrdquo on page 1-110bull ldquoMove Constructorrdquo on page 1-110bull ldquoMove Assignment Operatorrdquo on page 1-111

Copy ConstructorTypedArray(const TypedArrayltTgtamp rhs)

TypedArray(const Arrayamp rhs)

Creates a shared data copy of the input

matlabdataTypedArrayltTgt

1-109

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Copy Assignment Operator

TypedArrayltTgtamp operator=(const TypedArrayltTgtamp rhs)

TypedArrayltTgtamp operator=(const Arrayamp rhs)

Assigns a shared data copy of the input to this TypedArrayltTgt

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Move Constructor

TypedArray(TypedArrayltTgtampamp rhs)

TypedArray(Arrayampamp rhs)

Moves contents of the input to a new instance

TypedArrayltTgtampamp rhs Value to be movedArrayampamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input does not match

1 API Reference

1-110

Move Assignment Operator

TypedArrayltTgtamp operator=(TypedArrayltTgtampamp rhs)

TypedArrayltTgtamp operator=(Arrayampamp rhs)

Moves the input to this TypedArrayltTgt object

TypedArrayltTgtampamp rhs Value to move

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Destructorvirtual ~TypedArray()

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-111bull ldquoEnd Iteratorsrdquo on page 1-112

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

matlabdataTypedArrayltTgt

1-111

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

Indexing Operators

operator[]ArrayElementTypedRefltT stdis_constltTgtvaluegt operator[](size_tidx)

ArrayElementTypedRefltT truegt operator[](size_t idx) const

Enables [] indexing on a TypedArray Indexing is 0-based

size_t idx First array index

1 API Reference

1-112

ArrayElementTypedRefltTstdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltTtruegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Suppose that you have a cell array c Assign a value to a ReferenceltArraygt object andcall the member function getType

ReferenceltArraygt r = c[0][0]auto t = c[0][0]getType

Member Functions

releasebuffer_ptr_tltTgt release()

Release the underlying buffer from the Array If the Array is shared a copy of the bufferis made otherwise no copy is made After the buffer is released the array contains noelements

buffer_ptr_tltTgt A unique_ptr with the data pointer

InvalidArrayTypeException

This TypedArray does not support releasing the buffer

matlabdataTypedArrayltTgt

1-113

ExamplesAssign Values to Array Elements

Create an array equivalent to the MATLAB array [1 2 3 4] then replace eachelement of the array with a single value

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory Create an array equivalent to the MATLAB array [1 2 3 4] matlabdataTypedArrayltdoublegt D = factorycreateArrayltdoublegt( 22 1324 ) Change the values for (autoamp elem D) elem = 55 return 0

bull ldquoBring Result of MATLAB Calculation Into C++rdquo

See AlsoArray | ArrayType

TopicsldquoBring Result of MATLAB Calculation Into C++rdquo

Introduced in R2017b

1 API Reference

1-114

matlabdataReferenceltTypedArrayltTgtgtC++ class to get reference to TypedArray

DescriptionThe ReferenceltTypedArrayltTgtgt class extends the APIs available to a reference to anArray It derives from the ReferenceltArraygt class and provides iterators and type-safe indexing ReferenceltTypedArrayltTgtgt is not thread-safe - do not pass referencesto TypedArray objects between threads

TypedArrayRef is defined in TypedArrayRefhpp as

template lttypename Tgtusing TypedArrayRef = ReferenceltTypedArrayltTgtgt

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

ConstructorReference(const ReferenceltArraygtamp rhs)

Description

Create a ReferenceltTypedArrayltTgtgt object from a ReferenceltArraygt object

Parametersconst ReferenceltArraygtamprhs

Value to copy

matlabdataReferenceltTypedArrayltTgtgt

1-115

ThrowsTypeMismatchException Element of Array does not match ltTgt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-116bull ldquoEnd Iteratorsrdquo on page 1-116

Begin Interators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

1 API Reference

1-116

None

Indexing Operators

operator[]ArrayElementTypedRefltarr_elem_type stdis_constltTgtvaluegtoperator[](size_t idx)

ArrayElementTypedRefltarr_elem_type truegt operator[](size_t idx)const

Enables [] indexing on a reference to an Array Indexing is 0-based

size_t idx First array index

ArrayElementTypedRefltarr_elem_typestdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltarr_elem_type truegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

InvalidFieldNameException

Field name is invalid for a struct

Other Operators

operator=ReferenceltTypedArrayltTgtgtamp operator= (TypedArrayltTgt rhs)

matlabdataReferenceltTypedArrayltTgtgt

1-117

Assign a TypedArray to an element of the referenced Array The Array being indexedmust be non-const

TypedArrayltTgt rhs Value to assign

ReferenceltTypedArrayltTgtgtamp

Updated instance

None

See Also

Introduced in R2017b

1 API Reference

1-118

matlabdataTypedIteratorltTgtTemplated C++ class to provide random access iterator

DescriptionTypedIterator is the return type of all begin and end functions that support randomaccess

Class DetailsNamespace matlabdataInclude TypedIteratorhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tchar16_tboolstdcomplexltdoublegt

matlabdataTypedIteratorltTgt

1-119

stdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorsrdquo on page 1-120bull ldquoCopy Assignment Operatorsrdquo on page 1-121bull ldquoMove Constructorsrdquo on page 1-121bull ldquoMove Assignment Operatorsrdquo on page 1-121

Copy Constructors

TypedIterator(const TypedIteratorltTgtamp rhs)

Creates a shared data copy of a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

None

1 API Reference

1-120

Copy Assignment OperatorsTypedIteratorltTgtamp operator=(const TypedIteratorltTgtamp rhs)

Assigns a shared data copy to a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

TypedIteratorltTgtamp Updated instance

None

Move ConstructorsTypedIterator(TypedIteratorltTgt ampamprhs)

Moves contents of a TypedIterator object to a new instance

TypedIteratorltTgtampamp rhs Value to move

None

Move Assignment OperatorsTypedIteratorltTgtamp operator=(TypedIteratorltTgtampamp rhs)

Assigns the input to this TypedIterator object

TypedIteratorltTgtampamp rhs Value to move

TypedIteratorltTgtamp Updated instance

None

matlabdataTypedIteratorltTgt

1-121

Other Operatorsbull ldquooperator++rdquo on page 1-122bull ldquooperator--rdquo on page 1-122bull ldquooperator++rdquo on page 1-123bull ldquooperator--rdquo on page 1-123bull ldquooperator+=rdquo on page 1-123bull ldquooperator-=rdquo on page 1-124bull ldquooperator=rdquo on page 1-124bull ldquooperatorltrdquo on page 1-124bull ldquooperatorgtrdquo on page 1-125bull ldquooperatorlt=rdquo on page 1-125bull ldquooperatorgt=rdquo on page 1-125bull ldquooperator+rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperatorrdquo on page 1-127bull ldquooperator-gtrdquo on page 1-127bull ldquooperator[]rdquo on page 1-127

operator++TypedIteratorltTgtamp operator++()

Pre-increment operator

TypedIteratorltTgtamp Original iterator

None

operator--TypedIteratorltTgtamp operator--()

1 API Reference

1-122

Pre-decrement operator

TypedIteratorltTgtamp Original iterator

None

operator++TypedIteratorltTgt operator++(int)

Post-increment operator

TypedIteratorltTgt Copy of original iterator

None

operator--TypedIteratorltTgt operator--(int)

Post-decrement operator

TypedIteratorltTgt Copy of original iterator

None

operator+=TypedIteratorltTgtamp operator+=(difference_type d)

Addition assignment operator

difference_type d Amount to add specified as stdptrdiff_t

matlabdataTypedIteratorltTgt

1-123

TypedIteratorltTgtamp Updated instance

None

operator-=TypedIteratorltTgtamp operator-=(difference_type d)

Subtraction assignment operator

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgtamp Updated instance

None

operator=bool operator=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if iterators do not point to same element

None

operatorltbool operatorlt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

1 API Reference

1-124

bool Returns true if left-side iterator is less than right-sideiterator

operatorgtbool operatorgt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than right-side iterator

operatorlt=bool operatorlt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is less than or equal toright-side iterator

None

operatorgt=bool operatorgt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than orequal to right-side iterator

None

matlabdataTypedIteratorltTgt

1-125

operator+TypedIteratorltTgt operator+(difference_type d) const

Creates an iterator that is added to this one by the amount passed in

difference_type d Amount to add specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-TypedIteratorltTgt operator-(difference_type d) const

Creates an iterator that is decremented from this one by the amount passed in

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-difference_type operator-(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

difference_type Difference between iterators specified asstdptrdiff_t

None

1 API Reference

1-126

operatorreference operator() const

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataTypedIteratorltTgt

1-127

Free Function

operator==bool operator==(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if both iterators point to same element

None

See Also

Introduced in R2017b

1 API Reference

1-128

matlabdataapply_visitorCall Visitor class on arrays

Descriptionauto apply_visitor(Array a V visitor) dispatch to visitor class operationsbased on array type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersmatlabdataArray a

The matlabdataArray to operate on with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

matlabdataapply_visitor

1-129

matlabdataapply_visitor_refCall Visitor class on array references

Descriptionauto apply_visitor_ref(const ArrayRefamp a V visitor) dispatch to visitorclass operations based on array reference type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersconstmatlabdataArrayRefamp a

A matlabdataArrayRef reference to the array to operateon with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

1 API Reference

1-130

matlabengineMATLABEngineEvaluate MATLAB functions from C++ program

DescriptionThe matlabengineMATLABEngine class uses a MATLAB process as acomputational engine for C++ This class provides an interface between the C++language and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom C++ programs

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Factory MethodsThe matlabengineMATLABEngine class provides methods to start MATLAB and toconnect to a shared MATLAB session synchronously or asynchronously

bull matlabenginestartMATLAB mdash Start MATLAB synchronouslybull matlabenginestartMATLABAsync mdash Start MATLAB asynchronouslybull matlabengineconnectMATLAB mdash Connect to shared MATLAB session

synchronouslybull matlabengineconnectMATLABAsync mdash Connect to shared MATLAB session

asynchronously

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -h

matlabengineMATLABEngine

1-131

bull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup OptionsrdquoFor an example of how to use MATLAB startup options when starting engineapplications see ldquoStart MATLAB with Startup Optionsrdquo

Method Summary

Member Functionsldquofevalrdquo on page 1-133

Evaluate MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-136

Evaluate MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-138 Evaluate MATLAB statement as a string synchronouslyldquoevalAsyncrdquo on page1-139

Evaluate MATLAB statement as a string asynchronously

ldquogetVariablerdquo onpage 1-140

Get variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-141

Get variable from the MATLAB base workspace asynchronously

ldquosetVariablerdquo onpage 1-142

Put variable into the MATLAB base workspace synchronously

ldquosetVariableAsyncrdquoon page 1-142

Put variable into the MATLAB base workspace asynchronously

ldquogetPropertyrdquo onpage 1-143

Get object property value

ldquogetPropertyAsyncrdquoon page 1-144

Get object property value asynchronously

1 API Reference

1-132

ldquosetPropertyrdquo onpage 1-145

Set object property value

ldquosetPropertyAsyncrdquoon page 1-146

Set object property value asynchronously

Member Function Details

fevalstdvectorltmatlabdataArraygt feval(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

ResultType feval(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs )

ResultType feval(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB functions with input arguments synchronously Use feval when youwant to pass arguments from C++ to MATLAB and when you want to return a resultfrom MATLAB to C++

Inputs and outputs can be types defined by the MATLAB Data Array API or can benative C++ types

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

matlabengineMATLABEngine

1-133

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

stdvectorltmatlabdataArraygt

Outputs returned from MATLAB function

matlabdataArray Single output returned from MATLAB functionResultType Output returned from MATLAB function as a user-specified

type Can be a stdtuple if returning multiple arguments

matlabengineMATLABNotAvailableException

The MATLAB session is not available

1 API Reference

1-134

matlabengineMATLABExecutionException

There is a MATLAB runtime error in the function

matlabengineTypeConversionException

The result of a MATLAB function cannot be converted tothe specified type

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

This example passes an array of numeric values to a MATLAB function The codeperforms these steps

bull Creates a matlabdataArray with the dimensions 2-by-3 from a vector ofnumeric values of type double

bull Starts a shared MATLAB sessionbull Passes the data array to the MATLAB sqrt function and returns the result to C++

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabengine

stdvectorltdoublegt cppData 4 8 12 16 20 24

Create a 2-by-3 matlab data array matlabdataArrayFactory factory auto inputArray = factorycreateArray( 2 3 cppDatacbegin() cppDatacend())

Start MATLAB engine stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Pass data array to MATLAB sqrt function And return results auto result = matlabPtr-gtfeval(usqrt inputArray)

When calling feval using native C++ types the input arguments are restricted to scalarvalues For example this code returns the square root of a scalar value

include MatlabEnginehppusing namespace matlabengine

Start MATLAB engine synchronously stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Call sqrt function double result = matlabPtr-gt fevalltdoublegt(usqrt double(27))

matlabengineMATLABEngine

1-135

For functions that return multiple output arguments you can use the MATLAB data APIor if using C++ types a stdtuple For an example see ldquoCall Function with Native C++ Typesrdquo

ldquoCall MATLAB Functions from C++rdquo

ldquoMATLAB Data APIrdquo

fevalAsyncFutureResultltstdvectorltmatlabdataArraygtgt fevalAsync(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt amp output = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amp error = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs)

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB function with input arguments and returned values asynchronously

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

1 API Reference

1-136

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

FutureResult A FutureResult object used to get the result of calling theMATLAB function

None

This example passes the scalar double 127 to the MATLAB sqrt functionasynchronously The FutureResult is then used to get the result

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() matlabdataArrayFactory factory matlabdataArray argument = factorycreateScalarltdoublegt(127) FutureResultltmatlabdataArraygt future = matlabPtr-gt fevalAsync(convertUTF8StringToUTF16String(sqrt) stdmove(argument))

matlabengineMATLABEngine

1-137

matlabdataTypedArrayltdoublegt result = futureget()

ldquoCall Function Asynchronouslyrdquo

evalvoid eval(const matlabengineString ampstatement const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string synchronously

constmatlabengineString ampstatement

MATLAB statement to evaluate

conststdshared_ptrltmatlabengineStreamBuffergtampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergtamperror

Stream buffer used to store the error message from theMATLAB command

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

There is a runtime error in the MATLAB statement

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB statement

This example evaluates the following MATLAB statement

a = sqrt(127)

1 API Reference

1-138

The statement creates the variable a in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

evalAsyncFutureResultltvoidgt evalAsync(const matlabengineString ampstr const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string asynchronously

const Stringamp str MATLAB statement to evaluateconststdshared_ptrltmatlabengineStreamBuffergt ampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergt amperror

Stream buffer used to store the error message from theMATLAB command

FutureResult A FutureResult object used to wait for the completion of theMATLAB statement

None

This example evaluates the following MATLAB statement asynchronouslya = sqrt(127)

The statement creates the variable a in the MATLAB base workspace

matlabengineMATLABEngine

1-139

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltvoidgt future = matlabPtr-gt evalAsync(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

getVariablematlabdataArray getVariable(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace

constmatlabengineStringamp varName

Name of a variable in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variablefrom For more information see global

matlabdataArray

Variable obtained from the MATLAB base or global workspace

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The requested variable does not exist in the specifiedMATLAB base or global workspace

This example gets a variable named varName from the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray varName = matlabPtr-gtgetVariable(convertUTF8StringToUTF16String(varName))

1 API Reference

1-140

ldquoPass Variables from MATLAB to C++rdquo

getVariableAsyncFutureResultltmatlabdataArraygt getVariableAsync(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace asynchronously

constmatlabengineStringamp varName

Name of the variable in MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variable fromFor more information see global

FutureResult A FutureResult object that you can use to get the variableobtained from the MATLAB workspace as amatlabdataArray

None

This example gets a variable named varName from the MATLAB base workspaceasynchronously

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltmatlabdataArraygt future = matlabPtr-gt getVariableAsync(convertUTF8StringToUTF16String(varName))matlabdataArray varName = futureget()

ldquoPass Variables from MATLAB to C++rdquo

matlabengineMATLABEngine

1-141

setVariablevoid setVariable(const matlabengineString ampvarName const matlabdataArray ampvar WorkspaceType workspaceType = WorkspaceTypeBASE)

Put a variable into the MATLAB base or global workspace If a variable with the samename exists in the MATLAB workspace setVariable overwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

matlabengineMATLABNotAvailableException

The MATLAB session is not available

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from C++ to MATLABrdquo

setVariableAsyncFutureResultltvoidgt setVariableAsync(const matlabengineString ampvarName const matlabdataArray var WorkspaceType workspaceType = WorkspaceTypeBASE)

1 API Reference

1-142

Put a variable into the MATLAB base or global workspace asynchronously If a variablewith the same name exists in the MATLAB base workspace setVariableAsyncoverwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

None

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )FutureResultltvoidgt future = matlabPtr-gt setVariableAsync(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from MATLAB to C++rdquo

getPropertymatlabdataArray getProperty(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property

matlabengineMATLABEngine

1-143

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

matlabdataArray

Value of the named property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetProperty returns the exception messageproperty value as a matlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(try surf(4) catch me end))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))matlabdataCharArray message = matlabPtr-gt getProperty(mException convertUTF8StringToUTF16String(message))stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

getPropertyAsyncFutureResultltmatlabdataArraygt getPropertyAsync(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property asynchronously

1 API Reference

1-144

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

FutureResult FutureResult object that is used to synchronize the operation

None

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetPropertyAsync returns a FutureResultthat you use to get the exception message property value as amatlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(trysurf(4)catch meend))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))FutureResultltmatlabdataArraygt future = matlabPtr-gt getPropertyAsync(mException convertUTF8StringToUTF16String(message))matlabdataCharArray message = futureget()stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

setPropertyvoid setProperty(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property

matlabdataArray ampobject

MATLAB object

matlabengineMATLABEngine

1-145

const StringamppropertyName

Name of the property to set

constmatlabdataArray amppropertyValue

Value assigned to the property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example shows how to set a MATLAB object property It creates a MATLAB graphand returns the line handle object Setting the value of the line LineStyle property tothe character changes the property value of the line object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray()matlabPtr-gtsetProperty(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

setPropertyAsyncFutureResultltvoidgt setPropertyAsync(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property asynchronously

matlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property to set

1 API Reference

1-146

constmatlabdataArray amppropertyValue

Value assigned to the property

None

This example shows how to set a MATLAB object property asynchronously It creates aMATLAB graph and returns the line handle object Setting the line LineStyle propertyto the character changes the property value of the object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray() FutureResultltvoidgt future = matlabPtr-gt setPropertyAsync(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

See Also

Introduced in R2017b

matlabengineMATLABEngine

1-147

matlabengineconnectMATLABConnect to shared MATLAB session synchronously

Descriptionstdunique_ptrltMATLABEnginegt connectMATLAB()

stdunique_ptrltMATLABEnginegt connectMATLAB(constmatlabengineStringamp name)

Connect synchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-148

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to a MATLABEngine object

ExceptionsmatlabengineEngineException

Throws exception if function fails to connect to the specified MATLABsession

Examples

Connect to Shared MATLAB Session

Connect to a shared MATLAB session named my_matlab

stdunique_ptrltMATLABEnginegt matlabPrt = connectMATLAB(convertUTF8StringToUTF16String(my_matlab))

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineconnectMatlabAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

matlabengineconnectMATLAB

1-149

matlabengineconnectMATLABAsyncConnect to shared MATLAB session asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync()

FutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync(constmatlabengineStringamp name)

Connect asynchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-150

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object that you can use to get the pointer to theMATLABEngine

Examples

Connect to Shared MATLAB Session Asynchronously

Connect to a shared MATLAB session named my_matlab asynchronously Use theFutureResult get method to retrieve the pointer to the MATLABEngine objectFutureResultsltstdunique_ptrltMATLABEnginegtgt future = connectMATLABAsync(convertUTF8StringToUTF16String(my_matlab))stdunique_ptrltMATLABEnginegt matlabPtr = futureget()

bull ldquoConnect C++ to Running MATLAB Sessionrdquo

See AlsomatlabengineconnectMatlab

TopicsldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

matlabengineconnectMATLABAsync

1-151

matlabengineconvertUTF8StringToUTF16StringConvert UTF-8 string to UTF-16 string

Descriptionstdbasic_stringltchar16_tgt convertUTF8StringToUTF16String(conststdstringamp utf8string)

Convert a UTF-8 string to a UTF-16 string Use this function to convert ASCII strings tomatlabengineString strings which are required by MATLAB C++ Enginefunctions

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdstringamputf8string

A UTF-8 string

Return Valuestdbasic_stringltchar16_tgt

A UTF-16 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-152

matlabengineTypeConversionException

The input type cannot be converted tostdbasic_stringltchar16_tgt

Examples

Convert String

Convert a UTF-8 string to a matlabengineString (UTF-16 string)

matlabengineString matlabStatement = convertUTF8StringToUTF16String(sqrt(127))

See AlsomatlabengineString |matlabengineconvertUTF16StringToUTF8String

Introduced in R2017b

matlabengineconvertUTF8StringToUTF16String

1-153

matlabengineconvertUTF16StringToUTF8StringConvert UTF-16 string to UTF-8 string

Descriptionstdstring convertUTF16StringToUTF8String(conststdbasic_stringltchar16_tgtamp utf16string)

Convert a UTF-16 string to a UTF-8 string

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdbasic_stringltchar16_tgtamputf16string

A UTF-16 string

Return Valuestdstring A UTF-8 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-154

matlabengineTypeConversionException

The input type cannot be converted to stdstring

Examples

Convert String

Convert a matlabengineString (UTF-16 string) to a stdstring (UTF-8string)

matlabengineString matlabStatement = (usqrt(127))stdstring cmdString = convertUTF16StringToUTF8String(matlabStatement)

See AlsomatlabengineString |matlabengineconvertUTF8StringToUTF16String

Introduced in R2017b

matlabengineconvertUTF16StringToUTF8String

1-155

matlabenginefindMATLABFind shared MATLAB sessions synchronously

DescriptionstdvectorltStringgt findMATLAB()

Find all shared MATLAB sessions on the local machine

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValuestdvectorltStringgt

A vector of the names of all shared MATLAB sessions on the localmachine or an empty vector if no shared MATLAB sessions areavailable

ExceptionsmatlabengineEngineException

Throws exception if the call fails while searching for shared MATLABsessions

Examples

1 API Reference

1-156

Find Shared MATLAB Session Synchronously

stdvectorltStringgt names = findMATLAB()

See AlsomatlabenginefindMATLABAsync

Introduced in R2017b

matlabenginefindMATLAB

1-157

matlabenginefindMATLABAsyncFind shared MATLAB sessions asynchronously

DescriptionFutureResultltstdvectorltStringgtgt findMATLABAsync()

Find all shared MATLAB sessions on the local machine asynchronously

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValueFutureResultltstdvectorltStringgtgt

A FutureResult object that you can use to get the names of sharedMATLAB sessions on the local machine

Examples

Find Shared MATLAB Session Asynchronously

Find the names of all shared MATLAB sessions on the local machine asynchronouslyUse the FutureResult get method to retrieve the names

1 API Reference

1-158

FutureResultltstdvectorltStringgtgt futureNames = findMATLABAsync()stdvectorltStringgt matlabSessions = futureNamesget()

See AlsomatlabenginefindMATLAB

Introduced in R2017b

matlabenginefindMATLABAsync

1-159

matlabengineFutureResultRetrieve result from asynchronous operation

DescriptionA future result is an object that you can use to retrieve the result of MATLAB functionsor statements The FutureResult class provides all member functions of the C++stdfuture class

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Functions Delegated to stdfutureoperator= share get wait wait_for wait_until

1 API Reference

1-160

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement You cannot cancelasynchronous operations that use matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution had already begun

bool Was command canceled if execution had already begun

bool flag = futurecancel()

No exceptions thrown

matlabengineFutureResult

1-161

See Also

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

1 API Reference

1-162

matlabenginestartMATLABStart MATLAB synchronously

Descriptionstdunique_ptrltMATLABEnginegt startMATLAB(const stdvectorltStringgtampoptions = stdvectorltStringgt())

Start MATLAB synchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtampoptions

Options used to start MATLAB See ldquoSpecify Startup Optionsrdquo

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to the MATLABEngine object

matlabenginestartMATLAB

1-163

ExceptionsmatlabengineEngineException

MATLAB failed to start

Examples

Start MATLAB Synchronously

Start MATLAB synchronously and return a unique pointer to the MATLABEngine object

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Start MATLAB with Startup Options

Start MATLAB with the -nojvm option and return a unique pointer to theMATLABEngine object

stdvectorltStringgt optionVecoptionVecpush_back(convertUTF8StringToUTF16String(-nojvm))stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB(optionVec)

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineMATLABEngine | matlabenginestartMATLABAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

1 API Reference

1-164

matlabenginestartMATLABAsyncStart MATLAB asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt startMATLABAsync(conststdvectorltStringgtamp options = stdvectorltStringgt())

Start MATLAB asynchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtamp options

Startup options used to launch MATLAB

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object used to get the pointer to theMATLABEngine

Examples

matlabenginestartMATLABAsync

1-165

Start MATLAB Asynchronously

Start MATLAB asynchronously and return a FutureResult object Use theFutureResult to get a pointer to the MATLABEngine objectFutureResultltstdunique_ptrltMATLABEnginegtgt matlabFuture = startMATLAB()stdunique_ptrltMATLABEnginegt matlabPtr = matlabFutureget()

bull ldquoSpecify Startup Optionsrdquo

See AlsomatlabenginestartMATLAB

TopicsldquoSpecify Startup Optionsrdquo

Introduced in R2017b

1 API Reference

1-166

matlabengineterminateEngineClientFree engine resources during runtime

Descriptionvoid matlabengineterminateEngineClient releases all MATLAB engineresources during runtime when you no longer need the MATLAB engine in yourapplication program

Note Programs cannot start a new MATLAB engine or connect to a shared MATLABsession after calling terminateEngineClient

IncludeNamespace matlabengineInclude MatlabEnginehpp

ExamplesTerminate the engine session to free resources Start MATLAB sessionstdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Terminate MATLAB sessionmatlabengineterminateEngineClient()

See AlsomatlabenginestartMATLAB

Introduced in R2017b

matlabengineterminateEngineClient

1-167

matlabengineWorkspaceTypeType of MATLAB workspace

DescriptionThe matlabengineWorkspaceType enum class specifies the MATLAB workspaceto pass variables to or get variables fromBASE Variables scoped to the MATLAB base workspace

(command line and nonfunction scripts)GLOBAL Variables scoped to the MATLAB global workspace

(command line functions and scripts)

MATLAB scopes variables by workspace Variables that are scoped to the baseworkspace must be passed to functions as arguments Variables scoped to the globalworkspace can be accessed by any function that defines the specific variable name asglobal

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

ExamplesThis example

bull Connects to a shared MATLAB sessionbull Creates a matlabdataArray containing numeric values of type doublebull Puts the array in the MATLAB global workspaceinclude MatlabDataArrayhppinclude MatlabEnginehppinclude ltiostreamgt

static void putGlobalVar()

1 API Reference

1-168

using namespace matlabengine

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

Create matlab data array factory matlabdataArrayFactory factory

Create data variable matlabdataArray data = factorycreateArrayltdoublegt ( 1 5 40 110 47 362 723 )

Put data variable in MATLAB global workspace matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data WorkspaceTypeGLOBAL)

See AlsomatlabdataArrayFactory | matlabengineMATLABEngine |matlabengineconvertUTF8StringToUTF16String

TopicsldquoPass Variables from C++ to MATLABrdquoldquoPass Variables from MATLAB to C++rdquo

Introduced in R2017b

matlabengineWorkspaceType

1-169

matlabengineStringDefine UTF16 string

DescriptionType definition for stdbasic_stringltchar16_tgt

ExamplesThis example defines a variable containing the name of a shared MATLAB session Passthis string to the matlabengineconnectMATLAB function to connect to the namedsessionmatlabengineString session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

See AlsomatlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoMATLAB Engine API for C++rdquoldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

1 API Reference

1-170

matlabengineStreamBufferDefine stream buffer

DescriptionType definition for stdbasic_streafbufltchar16_tgt

ExamplesThis example defines string buffers to return output from the evaluation of a MATLABfunction by the MATLABEngineeval member function This function uses a bufferderived from matlabengineStreamBuffer to return output from MATLAB to C++include MatlabEnginehppinclude MatlabDataArrayhppinclude ltiostreamgt

using namespace matlabengineusing SBuf = stdbasic_stringbufltchar16_tgt

void printFromBuf(const stdshared_ptrltSBufgt buf) Get text from buf auto text_ = buf-gtstr() stdcout ltlt ltlt convertUTF16StringToUTF8String(text_) ltlt ltlt stdendl

int main()

Create Array factory matlabdataArrayFactory factory

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

auto outBuf = stdmake_sharedltSBufgt() auto errBuf = stdmake_sharedltSBufgt()

matlabPtr-gteval(convertUTF8StringToUTF16String(matlabengineengineName) outBuf errBuf) printFromBuf(outBuf) printFromBuf(errBuf) return 0

matlabengineStreamBuffer

1-171

See AlsomatlabengineconnectMATLAB |matlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoRedirect MATLAB Command Window Output to C++rdquo

Introduced in R2017b

1 API Reference

1-172

matlabengineSharedFutureResultRetrieve result from asynchronous operation as shared future

DescriptionA shared future result is an object that you use to retrieve the result of MATLABfunctions or statements any number of times

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using one of these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Function Delegated to stdshared_futureoperator= get valid wait wait_for wait_until

matlabengineSharedFutureResult

1-173

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement

Note that you cannot cancel asynchronous start connection or find operations which areinitiated using these functions matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution has already begun

bool True if the MATLAB command can be canceled

bool flag = futurecancel()

None

1 API Reference

1-174

See AlsomatlabengineFutureResult

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

matlabengineSharedFutureResult

1-175

commathworksengineMatlabEngine classPackage commathworksengine

Java class using MATLAB as a computational engine

DescriptionThe commathworksengineMatlabEngine class uses a MATLAB process as acomputational engine for Javareg This class provides an interface between the Javalanguage and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom Java

Constructor SummaryThe MatlabEngine class provides static methods to start MATLAB and to connect to ashared MATLAB session synchronously or asynchronously Only these static methodscan instantiate this class

bull Start MATLAB synchronously mdash ldquostartMatlabrdquo on page 1-178bull Connect to shared MATLAB session synchronously mdash ldquoconnectMatlabrdquo on page 1-180bull Start MATLAB asynchronously mdash ldquostartMatlabAsyncrdquo on page 1-179bull Connect to shared MATLAB session asynchronously mdash ldquoconnectMatlabAsyncrdquo on

page 1-181

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -n

1 API Reference

1-176

bull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup Optionsrdquo

Method Summary

Static MethodsldquostartMatlabrdquo onpage 1-178

Start MATLAB synchronously

ldquostartMatlabAsyncrdquoon page 1-179

Start MATLAB asynchronously

ldquofindMatlabrdquo onpage 1-179

Find all available shared MATLAB sessions from a local machinesynchronously

ldquofindMatlabAsyncrdquoon page 1-180

Find all available shared MATLAB sessions from a local machineasynchronously

ldquoconnectMatlabrdquo onpage 1-180

Connect to a shared MATLAB session on a local machinesynchronously

ldquoconnectMatlabAsyncrdquo on page 1-181

Connect to a shared MATLAB session on a local machineasynchronously

Member VariableNULL_WRITER Use a writer that ignores the contents from the MATLAB

command window

Member Functionsldquofevalrdquo on page 1-182

Evaluate a MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-183

Evaluate a MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-184 Evaluate a MATLAB expression as a string synchronously

commathworksengineMatlabEngine class

1-177

ldquoevalAsyncrdquo on page1-185

Evaluate a MATLAB expression as a string asynchronously

ldquogetVariablerdquo onpage 1-186

Get a variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-187

Get a variable from the MATLAB base workspace asynchronously

ldquoputVariablerdquo onpage 1-187

Put a variable into the MATLAB base workspace synchronously

ldquoputVariableAsyncrdquoon page 1-188

Put a variable into the MATLAB base workspace asynchronously

ldquodisconnectrdquo on page1-188

Disconnect from the current MATLAB session synchronously

ldquodisconnectAsyncrdquoon page 1-189

Disconnect from the current MATLAB session asynchronously

ldquoquitrdquo on page 1-189 Force the shutdown of the current MATLAB sessionsynchronously

ldquoquitAsyncrdquo on page1-189

Force the shutdown of the current MATLAB sessionasynchronously

ldquocloserdquo on page 1-190

Disconnect or terminate the current MATLAB session

Method Details

startMatlabstatic MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Start MATLAB synchronously

String[] options Startup options used to start MATLAB engine For options seeldquoStartup and Shutdownrdquo

1 API Reference

1-178

Instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start

MatlabEngine engine = MatlabEnginestartMatlab()

ldquoStart and Close MATLAB Session from Javardquo

startMatlabAsyncstatic FutureltMatlabEnginegt startMatlabAsync(String[] options)

static FutureltMatlabEnginegt startMatlabAsync()

Start MATLAB asynchronously

String[] options Startup options used to start MATLAB For options seeldquoStartup and Shutdownrdquo

Instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEnginestartMatlabAsync()

ldquoStart and Close MATLAB Session from Javardquo

findMatlabstatic String[] findMatlab()

Find all shared MATLAB sessions on the local machine synchronously

commathworksengineMatlabEngine class

1-179

An array of the names of all shared MATLAB sessions on the local machine or an emptyvector if there are no shared MATLAB sessions available on the local machine

commathworksengineEngineException

If there is a failure during the search for MATLAB sessions

String[] engines = MatlabEnginefindMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

findMatlabAsyncstatic FutureltSting[]gt findMatlabAsync()

Find all shared MATLAB sessions on local machine asynchronously

An instance of FutureltString[]gt

FutureltString[]gt future = MatlabEnginefindMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabstatic MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Connect to a shared MATLAB session on local machine synchronously

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session with default options

1 API Reference

1-180

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

String name Name of the shared MATLAB session Use ldquofindMatlabrdquo on page1-179 to get the names of shared MATLAB sessions

An instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start or connect

MatlabEngine engine = MatlabEngineconnectMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabAsyncstatic FutureltMatlabEnginegt connectMatlabAsync(String name)

static FutureltMatlabEnginegt connectMatlabAsync

Connect to a shared MATLAB session on local machine asynchronously The behavior isthe same as that of connectMatlab except the mechanism is asynchronous

String name Name of the shared MATLAB session

An instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEngineconnectMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

commathworksengineMatlabEngine class

1-181

fevalltTgt T feval(int nlhs String func Writer output Writer errorObjecthellip args)

ltTgt T feval(int nlhs String func Objecthellip args)

ltTgt T feval(String func Writer output Writer error Objecthellip args)

ltTgt T feval(String func Objecthellip args)

Evaluate MATLAB functions with input arguments synchronously

String func Name of the MATLAB function or script to evaluateint nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

Result of executing the MATLAB function

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

1 API Reference

1-182

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is a MATLAB runtime error in the function

commathworksengineUnsupportedTypeExeption

There is an unsupported data type

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB function

double result = enginefeval(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

fevalAsyncltTgt FutureltTgt fevalAsync(int nlhs String func Writer outputWriter error Objecthellip args)

ltTgt FutureltTgt fevalAsync(int nlhs String func Objecthellip args)

ltTgt FutureltTgt fevalAsync(String func Writer output Writer errorObjecthellip args)

ltTgt FutureltTgt fevalAsync(String func Objecthellip args)

Evaluate MATLAB functions with input arguments asynchronously

String func Name of the MATLAB function or script to evaluate

commathworksengineMatlabEngine class

1-183

int nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginefevalAsync(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

evalvoid eval(String command Writer output Writer error)

void eval(String command)

Evaluate a MATLAB statement as a string synchronously

1 API Reference

1-184

String command MATLAB statement to evaluateWriter output Stream used to store the standard output from the MATLAB

statement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABstatement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is an error in the MATLAB statement duringruntime

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB statement

engineeval(result = sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

evalAsyncFutureltVoidgt evalAsync(String command Writer output Writer error)

FutureltVoidgt evalAsync(String command)

Evaluate a MATLAB statement as a string asynchronously

String command MATLAB statement to evaluate

commathworksengineMatlabEngine class

1-185

Writer output Stream used to store the standard output from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the output from the MATLABcommand window

Writer error Stream used to store the standard error from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the error message from theMATLAB command window

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineevalAsync(sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

getVariableltTgt T getVariable(String varName)

Get a variable from the MATLAB base workspace

String varName Name of a variable in the MATLAB base workspace

Variable passed from the MATLAB base workspace

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

1 API Reference

1-186

javalangIllegalStateException

The MATLAB session is not available

double myVar = enginegetVariable(myVar)

ldquoPass Variables from MATLAB to Javardquo

getVariableAsyncltTgt FutureltTgt getVariableAsync(String varName)

Get a variable from the MATLAB base workspace asynchronously

String varName Name of a variable in MATLAB base workspace

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginegetVariableAsync(myVar)

ldquoPass Variables from MATLAB to Javardquo

putVariablevoid putVariable(String varName T varData)

Put a variable into the MATLAB base workspace

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

commathworksengineMatlabEngine class

1-187

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

javalangIllegalStateException

The MATLAB session is not available

engineputVariable(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

putVariableAsyncFutureltVoidgt putVariableAsync(String varName T varData)

Put a variable into the MATLAB base workspace asynchronously

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineputVariableAsync(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

disconnectvoid disconnect()

Disconnect from the current MATLAB session

1 API Reference

1-188

commathworksengineEngineException

The current MATLAB session cannot be disconnected

enginedisconnect()

ldquoClose MATLAB Engine Sessionrdquo

disconnectAsyncFutureltVoidgt disconnectAsync()

Disconnect from the current MATLAB session

FutureltVoidgt future = enginedisconnectAsync()

ldquoClose MATLAB Engine Sessionrdquo

quitviod quit()

Force the shutdown of the current MATLAB session

commathworksengineEngineException

The current MATLAB session cannot be shut down

enginequit()

ldquoClose MATLAB Engine Sessionrdquo

quitAsyncFutureltVoidgt quitAsync()

commathworksengineMatlabEngine class

1-189

Force the shutdown of the current MATLAB session asynchronously without waiting fortermination

An instance of FutureltVoidgt

FutureltVoidgt future = enginequitAsync()

ldquoClose MATLAB Engine Sessionrdquo

closevoid close()

MatlabEngine provides the close() method to implement thejavalangAutoCloseable interface for MatlabEngine objects This close()method enables you to use a try-with-resources statement to automatically disconnect orterminate the MATLAB session at the end of the statement

The MatlabEngine close() method disconnects or terminates the current MATLABsession depending on the context

bull If a Java process starts the MATLAB session as a default non-shared sessionclose() terminates MATLAB

bull If the MATLAB session is a shared session close() disconnects MATLAB from thisJava process MATLAB terminates when there are no other connections

To force the shutdown or disconnection of the current MATLAB session explicitly callMatlabEnginequit() MatlabEnginedisconnect() or their asynchronouscounterparts

engineclose()

ldquoClose MATLAB Engine Sessionrdquo

1 API Reference

1-190

Examples

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously The workflowis

bull Open a MATLAB sessionbull Invoke the MATLAB sqrt function with arguments asynchronouslybull Get the result of the MATLAB functionbull Close the MATLAB engine

import commathworksengineMatlabEngine

FutureltMatlabEnginegt engFuture = MatlabEnginestartMatlabAsync()MatlabEngine engine = engFutureget()double myVar = 4FutureltDoublegt future = enginefevalAsync(sqrt myVar)double result = futureget()Systemoutprintln(result)

See AlsomatlabengineengineName | matlabengineisEngineShared |matlabengineshareEngine

TopicsldquoBuild Java Engine ProgramsrdquoldquoStart and Close MATLAB Session from Javardquo

Introduced in R2016b

commathworksengineMatlabEngine class

1-191

commathworksmatlabtypesComplex classPackage commathworksmatlabtypes

Java class to pass complex data to and from MATLAB

DescriptionThe Complex class provides Java support for MATLAB complex arrays Use this class topass complex data to MATLAB The MATLAB engine passes complex data to Java as aninstance of Complex

All MATLAB numeric types are converted to double in Java

Constructor SummaryComplex(double real double imag) constructs an instance of Complex with thespecified real and imaginary values

Field Summarydouble real The real part of the complex datadouble imag The imaginary part of the complex data

Examples

Pass Complex Variable to MATLAB Function

import commathworksengineMatlabEngine

MatlabEngine engine = MatlabEnginestartMatlab()

1 API Reference

1-192

Complex c = new Complex(23)Complex cj = enginefeval(conjc)

bull ldquoUsing Complex Variables in Javardquo

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoUsing Complex Variables in Javardquo

Introduced in R2016b

commathworksmatlabtypesComplex class

1-193

commathworksmatlabtypesHandleObject classPackage commathworksmatlabtypes

Java class to represent MATLAB handle objects

DescriptionJava represents handle objects that are passed from MATLAB as instances of theHandleObject class When passing a handle object back to MATLAB Java passes areference to the HandleObject instance This reference can be either an array or ascalar depending on the original handle object passed to Java from MATLAB

You can pass a handle object only to the MATLAB session in which it was originallycreated You cannot construct a HandleObject in Java

Examples

Get Handle Object from MATLAB

This example starts a shared MATLAB session and creates a containersMap object inthe MATLAB workspace The statement evaluated in the MATLAB workspace returns ahandle variable that refers to the Map object

The engine getVariable function returns the MATLAB handle variable as aHandleObject instance This instance is used to call the MATLABcontainersMapkeys function to obtain the Map keys

import commathworksengineMatlabEngineimport commathworksmatlabtypes

MatlabEngine engine = MatlabEnginestartMatlab()engineeval(cm = containersMap(idname11mw))

1 API Reference

1-194

HandleObject handle = enginegetVariable(cm)String[] cells = enginefeval(keys handle)

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex | commathworksmatlabtypesStruct

TopicsldquoUsing MATLAB Handle Objects in Javardquo

Introduced in R2016b

commathworksmatlabtypesHandleObject class

1-195

commathworksmatlabtypesStruct classPackage commathworksmatlabtypes

Java class to pass MATLAB struct to and from MATLAB

DescriptionThe Struct class provides support for passing data between MATLAB and Java as aMATLAB struct The Struct class implements the javautilMap interface

The Struct class is designed as an immutable type Attempting to change the mappingskeys or values of the returned Struct causes an UnsupportedOperationExceptionCalling these methods can cause the exception put() putAll() remove()entrySet() keySet() and values()

For an example see ldquoUsing MATLAB Structures in Javardquo

Constructor SummaryStruct s = new Struct(field1value1field2value2 ) creates aninstance of Struct with the specified field names and values

Method SummarycontainsKey(Object key) Returns true if this map contains a

mapping for the specified keycontainsValue(Object value) Returns true if this map maps one or more

keys to the specified valueentrySet() Returns a Set view of the mappings

contained in this mapequals(Object o) Compares the specified object with this

map for equality

1 API Reference

1-196

get(Object key) Returns the value to which the specifiedkey is mapped or null if this map containsno mapping for the key

hashCode() Returns the hash code value for this mapisEmpty() Returns true if this map contains no key-

value mappingskeySet() Returns a Set view of the keys contained

in this mapsize() Returns the number of key-value mappings

in this mapvalues() Returns a Collection view of the values

contained in this map

Examples

Create Struct for MATLAB Function Argument

Create a Struct and assign a key and value

import commathworksengineimport commathworksmatlabtypes

class StructProperties public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() int[] y = 12345 double[] color = 100507 Struct s = new Struct(ColorcolorLineWidth2) engfeval(plotys)

bull ldquoUsing MATLAB Structures in Javardquo

commathworksmatlabtypesStruct class

1-197

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject

TopicsldquoUsing MATLAB Structures in Javardquo

Introduced in R2016b

1 API Reference

1-198

commathworksmatlabtypesCellStr classPackage commathworksmatlabtypes

Java class to represent MATLAB cell array of char vectors

DescriptionThe CellStr class provides support for passing data from Java to MATLAB as aMATLAB cell array of char vectors (called a cellstr in MATLAB see cellstr) Thereare MATLAB functions that require cell arrays of char vectors as inputs To passarguments from Java to a MATLAB function requiring cellst inputs use the JavaCellStr class to create a compatible type

A MATLAB cellstr is mapped to a Java String array

Constructor SummaryCellStr(Object stringArray) creates a CellStr using a String or String arrayThe String array can have multiple dimensions

Method SummaryObject getStringArray() Get the String or String array used to

create the CellStrboolean equals(CellStr1CellStr2) Compare one CellStr instance with

another Two CellStr instances are equalif the String or String array they containare the same

commathworksmatlabtypesCellStr class

1-199

Examples

Construct CellStrThis example constructs a CellStr named keySet and puts the variable in theMATLAB base workspaceimport commathworksengineimport commathworksmatlabtypes

class javaCellstr public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() CellStr keySet = new CellStr(new String[]JanFebMarApr) engputVariable(mapKeyskeySet) engclose()

Construct CellStr Array

This example creates a CellStr array and passes it to the MATLAB plot function tochange the appearance of the graph produced by MATLAB The call to the MATLABprint function exports the figure as a jpeg file named myPlotjpg

import commathworksengineimport commathworksmatlabtypes

class CellStrArray public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() String[][] strArray = new String[2][2] strArray[0][0] = MarkerFaceColor strArray[0][1] = MarkerEdgeColor strArray[1][0] = green strArray[1][1] = red CellStr markerCellStr = new CellStr(strArray) engputVariable(MmarkerCellStr) engeval(plot(110--bsM)) engeval(print(myPlot-djpeg)) engclose()

1 API Reference

1-200

See AlsocommathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoPass Java CellStr to MATLABrdquo

Introduced in R2016b

commathworksmatlabtypesCellStr class

1-201

engClose (C and Fortran)Quit MATLAB engine session

C Syntaxinclude enginehint engClose(Engine ep)

Fortran Syntaxinclude enginehinteger4 engClose(ep)mwPointer ep

Argumentsep

Engine pointer

Returns0 on success and 1 otherwise Possible failure includes attempting to terminate analready-terminated MATLAB engine session

DescriptionThis routine sends a quit command to the MATLAB engine session and closes theconnection

1 API Reference

1-202

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIXreg operating systemsbull engwindemoc for a C example on Microsoftreg Windowsreg operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen

Introduced before R2006a

engClose (C and Fortran)

1-203

engEvalString (C and Fortran)Evaluate expression in string

C Syntaxinclude enginehint engEvalString(Engine ep const char string)

Fortran Syntaxinclude enginehinteger4 engEvalString(ep string)mwPointer epcharacter() string

Argumentsep

Engine pointerstring

String to execute

Returns1 if the engine session is no longer running or the engine pointer is invalid or NULLOtherwise returns 0 even if the MATLAB engine session cannot evaluate the command

DescriptionengEvalString evaluates the expression contained in string for the MATLAB enginesession ep previously started by engOpen

1 API Reference

1-204

UNIX Operating Systems

On UNIX systems engEvalString sends commands to the MATLAB workspace bywriting down a pipe connected to the MATLAB stdin process MATLAB reads back fromstdout any output resulting from the command that ordinarily appears on the screeninto the buffer defined by engOutputBuffer

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Microsoft Windows Operating Systems

On a Windows system engEvalString communicates with MATLAB software using aComponent Object Model (COM) interface

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engOutputBuffer

Introduced before R2006a

engEvalString (C and Fortran)

1-205

engGetVariable (C and Fortran)Copy variable from MATLAB engine workspace

C Syntaxinclude enginehmxArray engGetVariable(Engine ep const char name)

Fortran Syntaxinclude enginehmwPointer engGetVariable(ep name)mwPointer epcharacter() name

Argumentsep

Engine pointername

Name of mxArray to get from MATLAB workspace

ReturnsPointer to a newly allocated mxArray structure or NULL if the attempt failsengGetVariable fails if the named variable does not exist

DescriptionengGetVariable reads the named mxArray from the MATLAB engine sessionassociated with ep

1 API Reference

1-206

The limit for the size of data transferred is 2 GB

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengPutVariable mxDestroyArray

Introduced before R2006a

engGetVariable (C and Fortran)

1-207

engGetVisible (C)Determine visibility of MATLAB engine session

C Syntaxinclude enginehint engGetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Pointer to value returned from engGetVisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengGetVisible returns the current visibility setting for MATLAB engine session ep Avisible engine session runs in a window on the Windows desktop thus making the engineavailable for user interaction MATLAB removes an invisible session from the desktop

ExamplesThe following code opens engine session ep and disables its visibility

1 API Reference

1-208

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengSetVisible

engGetVisible (C)

1-209

Engine (C)Type for MATLAB engine

DescriptionA handle to a MATLAB engine object

Engine is a C language opaque type

You can call MATLAB software as a computational engine by writing C and Fortranprograms that use the MATLAB engine library Engine is the link between yourprogram and the separate MATLAB engine process

The header file containing this type is

include engineh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc shows how to call the MATLAB engine functions from a C programbull engwindemoc show how to call the MATLAB engine functions from a C program for

Windows systemsbull fengdemoF shows how to call the MATLAB engine functions from a Fortran

program

See AlsoengOpen

1 API Reference

1-210

engOpen (C and Fortran)Start MATLAB engine session

C Syntaxinclude enginehEngine engOpen(const char startcmd)

Fortran Syntaxinclude enginehmwPointer engOpen(startcmd)character() startcmd

Argumentsstartcmd

String to start the MATLAB process On Windows systems the startcmd stringmust be NULL

ReturnsPointer to an engine handle or NULL if the open fails

DescriptionThis routine allows you to start a MATLAB process for using MATLAB as acomputational engine

engOpen starts a MATLAB process using the command specified in the stringstartcmd establishes a connection and returns an engine pointer

engOpen (C and Fortran)

1-211

On UNIX systems if startcmd is NULL or the empty string engOpen starts a MATLABprocess on the current host using the command matlab If startcmd is a hostnameengOpen starts a MATLAB process on the designated host by embedding the specifiedhostname string into the larger string

rsh hostname bincsh -c setenv DISPLAY hostname0 matlab

If startcmd is any other string (has white space in it or nonalphanumeric characters)MATLAB executes the string literally

On UNIX systems engOpen performs the following steps

1 Creates two pipes2 Forks a new process Sets up the pipes to pass stdin and stdout from MATLAB

(parent) software to two file descriptors in the engine program (child)3 Executes a command to run MATLAB software (rsh for remote execution)

On Windows systems engOpen opens a COM channel to MATLAB The MATLABsoftware you registered during installation starts If you did not register duringinstallation enter the following command at the MATLAB prompt

matlab -regserver

See ldquoMATLAB COM Integrationrdquo for additional details

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

Introduced before R2006a

1 API Reference

1-212

engOpenSingleUse (C)Start MATLAB engine session for single nonshared use

C Syntaxinclude enginehEngine engOpenSingleUse(const char startcmd void dcom int retstatus)

Argumentsstartcmd

String to start MATLAB process On Microsoft Windows systems the startcmdstring must be NULL

dcomReserved for future use must be NULL

retstatusReturn status possible cause of failure

Returns

Microsoft Windows Operating Systems Only

Pointer to an engine handle or NULL if the open fails

UNIX Operating Systems

Not supported on UNIX systems

engOpenSingleUse (C)

1-213

DescriptionThis routine allows you to start multiple MATLAB processes using MATLAB as acomputational engine

engOpenSingleUse starts a MATLAB process establishes a connection and returns aunique engine identifier or NULL if the open fails Each call to engOpenSingleUsestarts a new MATLAB process

engOpenSingleUse opens a COM channel to MATLAB This starts the MATLABsoftware you registered during installation If you did not register during installationenter the following command at the MATLAB prompt

matlab -regserver

engOpenSingleUse allows single-use instances of an engine serverengOpenSingleUse differs from engOpen which allows multiple applications to use thesame engine server

See ldquoMATLAB COM Integrationrdquo for additional details

1 API Reference

1-214

engOutputBuffer (C and Fortran)Specify buffer for MATLAB output

C Syntaxinclude enginehint engOutputBuffer(Engine ep char p int n)

Fortran Syntaxinclude enginehinteger4 engOutputBuffer(ep p)mwPointer epcharactern p

Argumentsep

Engine pointerp

Pointer to character buffern

Length of buffer p

Returns1 if you pass it a NULL engine pointer Otherwise returns 0

engOutputBuffer (C and Fortran)

1-215

DescriptionengOutputBuffer defines a character buffer for engEvalString to return any outputthat ordinarily appears on the screen

The default behavior of engEvalString is to discard any standard output caused by thecommand it is executing A call to engOutputBuffer with a buffer of nonzero lengthtells any subsequent calls to engEvalString to save output in the character bufferpointed to by p

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Note The buffer returned by engEvalString is not NULL terminated

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engEvalString

Introduced before R2006a

1 API Reference

1-216

engPutVariable (C and Fortran)Put variable into MATLAB engine workspace

C Syntaxinclude enginehint engPutVariable(Engine ep const char name const mxArray pm)

Fortran Syntaxinclude enginehinteger4 engPutVariable(ep name pm)mwPointer ep pmcharacter() name

Argumentsep

Engine pointername

Name of mxArray in the engine workspacepm

mxArray pointer

Returns0 if successful and 1 if an error occurs

DescriptionengPutVariable writes mxArray pm to the engine ep giving it the variable name name

engPutVariable (C and Fortran)

1-217

If the mxArray does not exist in the workspace the function creates it If an mxArraywith the same name exists in the workspace the function replaces the existing mxArraywith the new mxArray

The limit for the size of data transferred is 2 GB

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The engine application owns the original mxArray and is responsible for freeing itsmemory Although the engPutVariable function sends a copy of the mxArray to theMATLAB workspace the engine application does not need to account for or free memoryfor the copy

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengGetVariable

Introduced before R2006a

1 API Reference

1-218

engSetVisible (C)Show or hide MATLAB engine session

C Syntaxinclude enginehint engSetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Value to set the Visible property to Set value to 1 to make the engine windowvisible or to 0 to make it invisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengSetVisible makes the window for the MATLAB engine session ep either visible orinvisible on the Windows desktop You can use this function to enable or disable userinteraction with the MATLAB engine session

engSetVisible (C)

1-219

ExamplesThe following code opens engine session ep and disables its visibility

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengGetVisible

1 API Reference

1-220

matClose (C and Fortran)Close MAT-file

C Syntaxinclude mathint matClose(MATFile mfp)

Fortran Syntaxinclude mathinteger4 matClose(mfp)mwPointer mfp

Argumentsmfp

Pointer to MAT-file information

ReturnsEOF in C (-1 in Fortran) for a write error and 0 if successful

DescriptionmatClose closes the MAT-file associated with mfp

ExamplesSee the following examples in matlabrootexternexampleseng_mat

matClose (C and Fortran)

1-221

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen

Introduced before R2006a

1 API Reference

1-222

matDeleteVariable (C and Fortran)Delete array from MAT-file

C Syntaxinclude mathint matDeleteVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathinteger4 matDeleteVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to delete

Returns0 if successful and nonzero otherwise

DescriptionmatDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp

matDeleteVariable (C and Fortran)

1-223

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

Introduced before R2006a

1 API Reference

1-224

MATFile (C and Fortran)Type for MAT-file

DescriptionA handle to a MAT-file object A MAT-file is the data file format MATLAB software usesfor saving data to your disk

MATFile is a C language opaque type

The MAT-file interface library contains routines for reading and writing MAT-files Callthese routines from your own CC++ and Fortran programs using MATFile to accessyour data file

The header file containing this type is

include math

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen matClose matPutVariable matGetVariable mxDestroyArray

MATFile (C and Fortran)

1-225

matGetDir (C and Fortran)List of variables in MAT-file

C Syntaxinclude mathchar matGetDir(MATFile mfp int num)

Fortran Syntaxinclude mathmwPointer matGetDir(mfp num)mwPointer mfpinteger4 num

Argumentsmfp

Pointer to MAT-file informationnum

Pointer to the variable containing the number of mxArrays in the MAT-file

ReturnsPointer to an internal array containing pointers to the names of the mxArrays in theMAT-file pointed to by mfp In C each name is a NULL-terminated string The numoutput argument is the length of the internal array (number of mxArrays in the MAT-file) If num is zero mfp contains no arrays

matGetDir returns NULL in C (0 in Fortran) If matGetDir fails sets num to a negativenumber

1 API Reference

1-226

DescriptionThis routine provides you with a list of the names of the mxArrays contained within aMAT-file

matGetDir allocates memory for the internal array of strings using a mxCalloc Freethe memory using mxFree when you are finished with the array

MATLAB variable names can be up to length mxMAXNAM defined in the C header filematrixh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo2F

Introduced before R2006a

matGetDir (C and Fortran)

1-227

matGetFp (C)File pointer to MAT-file

C Syntaxinclude mathFILE matGetFp(MATFile mfp)

Argumentsmfp

Pointer to MAT-file information

ReturnsC file handle to the MAT-file with handle mfp Returns NULL if mfp is a handle to aMAT-file in HDF5-based format

DescriptionUse matGetFp to obtain a C file handle to a MAT-file Standard C library routines likeferror and feof use file handle to investigate errors

Introduced before R2006a

1 API Reference

1-228

matGetNextVariable (C and Fortran)Next array in MAT-file

C Syntaxinclude mathmxArray matGetNextVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing the next mxArray from theMAT-file pointed to by mfp The function returns the name of the mxArray in name

matGetNextVariable returns NULL in C (0 in Fortran) for end of file or if there is anerror condition In C use feof and ferror from the Standard C Library to determinestatus

matGetNextVariable (C and Fortran)

1-229

DescriptionmatGetNextVariable allows you to step sequentially through a MAT-file and readevery mxArray in a single pass The function reads and returns the next mxArray fromthe MAT-file pointed to by mfp

Use matGetNextVariable immediately after opening the MAT-file with matOpen andnot with other MAT-file routines Otherwise the concept of the next mxArray isundefined

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariable is notguaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariableInfo matGetVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-230

matGetNextVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetNextVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing header information for thenext mxArray from the MAT-file pointed to by mfp The function returns the name of themxArray in name

matGetNextVariableInfo returns NULL in C (0 in Fortran) when the end of file isreached or if there is an error condition In C use feof and ferror from the Standard CLibrary to determine status

matGetNextVariableInfo (C and Fortran)

1-231

DescriptionmatGetNextVariableInfo loads only the array header information includingeverything except pr pi ir and jc from the current file offset

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetNextVariableInfo sets them to -1 instead These headers are forinformational use only Never pass this data back to the MATLAB workspace or save it toMAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariableInfo isnot guaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariable matGetVariableInfo

Introduced before R2006a

1 API Reference

1-232

matGetVariable (C and Fortran)Array from MAT-file

C Syntaxinclude mathmxArray matGetVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing the mxArray named byname from the MAT-file pointed to by mfp

matGetVariable returns NULL in C (0 in Fortran) if the attempt to return the mxArraynamed by name fails

matGetVariable (C and Fortran)

1-233

DescriptionThis routine allows you to copy an mxArray out of a MAT-file

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-234

matGetVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing header information for themxArray named by name from the MAT-file pointed to by mfp

matGetVariableInfo returns NULL in C (0 in Fortran) if the attempt to return headerinformation for the mxArray named by name fails

matGetVariableInfo (C and Fortran)

1-235

DescriptionmatGetVariableInfo loads only the array header information including everythingexcept pr pi ir and jc It recursively creates the cells and structures through theirleaf elements but does not include pr pi ir and jc

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetVariableInfo sets them to -1 instead These headers are for informational useonly Never pass this data back to the MATLAB workspace or save it to MAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomatGetVariable

Introduced before R2006a

1 API Reference

1-236

matlabengineconnect_matlabConnect shared MATLAB session to MATLAB Engine for Python

Syntaxeng = matlabengineconnect_matlab(name=None)eng = matlabengineconnect_matlab( ___ async)

Descriptioneng = matlabengineconnect_matlab(name=None) connects to the sharedMATLAB session name and returns a MatlabEngine object as eng The inputargument name specifies the name of a MATLAB session that is already running on yourlocal machine

bull If you specify name and the engine cannot find a shared MATLAB session of the samename then you receive an EngineError exception

bull If you do not specify name and the engine cannot find any shared MATLAB sessionsthen it starts a new shared MATLAB session If there are shared MATLAB sessionsrunning the engine connects to the first available session

bull If you do not specify name and the engine finds multiple shared MATLAB sessionsrunning then it connects to the first available session

eng = matlabengineconnect_matlab( ___ async) connects asynchronously ifasync is True

Examples

Connect to MATLAB Session

Connect to a shared MATLAB session that is already running on your local machine

matlabengineconnect_matlab

1-237

import matlabengineeng = matlabengineconnect_matlab()engsqrt(40)

20

matlabengineconnect_matlab connects to the first available shared MATLABsession If no MATLAB sessions are shared matlabengineconnect_matlab starts anew session

Connect to MATLAB Sessions by Name

When there are multiple shared MATLAB sessions on your local machine connect to twodifferent sessions one at a time by specifying their names

Connect to the first shared MATLAB session

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

Connect to the second shared MATLAB session

eng = matlabengineconnect_matlab(MATLAB_7090)engsqrt(40)

20

bull ldquoConnect Python to Running MATLAB Sessionrdquo

Input Argumentsname mdash Name of shared MATLAB sessioncharacter array

Name of the shared MATLAB session specified as a character array

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

1 API Reference

1-238

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

Output Argumentseng mdash Pythonreg variable for communicating with MATLABMatlabEngine object

Python variable for communicating with MATLAB returned as a MatlabEngine objecteng communicates with a shared MATLAB session that is already running on your localmachine

Limitationsbull Do not connect the engine multiple times to the same shared MATLAB session

See AlsomatlabengineMatlabEngine | matlabenginefind_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabengineconnect_matlab

1-239

matlabenginefind_matlabFind shared MATLAB sessions to connect to MATLAB Engine for Python

Syntaxnames = matlabenginefind_matlab()

Descriptionnames = matlabenginefind_matlab() finds all shared MATLAB sessions on yourlocal machine and returns their names in a tuple Any name in names can be the inputargument to matlabengineconnect_matlab If there are no shared sessionsrunning on your local machine matlabenginefind_matlab returns an emptytuple

Examples

Find Shared MATLAB Sessions

Identify the shared MATLAB sessions running on your local machine and connect to oneof them

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

There are two shared MATLAB sessions running so matlabenginefind_matlabreturns two names in a tuple

Connect to the first shared MATLAB session

1 API Reference

1-240

eng = matlabengineconnect_matlab(MATLAB_6830)

bull ldquoConnect Python to Running MATLAB Sessionrdquo

See Alsomatlabengineconnect_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabenginefind_matlab

1-241

matlabengineFutureResult classPackage matlabengine

Results of asynchronous call to MATLAB function stored in Python object

DescriptionThe FutureResult class stores results of an asynchronous call to a MATLAB function ina Python object

ConstructionThe MATLAB Engine for Python creates a FutureResult object when a MATLABfunction is called asynchronously There is no need to callmatlabengineFutureResult() to create FutureResult objects of your own

Methods

cancel Cancel asynchronous call to MATLAB function from Pythoncancelled Cancellation status of asynchronous call to MATLAB function from Pythondone Completion status of asynchronous call to MATLAB function from Pythonresult Result of asynchronous call to MATLAB function from Python

ExceptionsSyntaxError Python exception syntax error in function

callTypeError Python exception data type of output

argument not supported

1 API Reference

1-242

matlabengineCancelledError MATLAB engine cannot cancel functioncall

matlabengineInterruptedError Function call interruptedmatlabengineMatlabExecutionError

Function call fails to execute

matlabengineRejectedExecutionError

Engine terminated

matlabengineTimeoutError Result cannot be returned within thetimeout period

Examples

Get Result of Asynchronous MATLAB Call from Python

Call the MATLAB sqrt function from Python Set async to True to make the functioncall asynchronously

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquo

See AlsomatlabengineMatlabEngine

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from Pythonrdquo

matlabengineFutureResult class

1-243

Introduced in R2014b

1 API Reference

1-244

cancelClass matlabengineFutureResultPackage matlabengine

Cancel asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancel()

Descriptiontf = FutureResultcancel() cancels a call to a MATLAB function calledasynchronously from Python FutureResultcancel returns True if it successfullycancels the function and False if it cannot cancel the function

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status returned as either True or False The status tf is True ifFutureResultcancel successfully cancels the asynchronous function call and isFalse otherwise

Examples

Cancel an Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval function Thencancel it

cancel

1-245

import matlabengineeng = matlabenginestart_matlab()ret = engeval(while 1 endnargout=0async=True)tf = retcancel()print(tf)

True

See Also

1 API Reference

1-246

cancelledClass matlabengineFutureResultPackage matlabengine

Cancellation status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancelled()

Descriptiontf = FutureResultcancelled() returns the cancellation status of a call to aMATLAB function called asynchronously from Python FutureResultcancelledreturns True if a previous call to FutureResultcancel succeeded and Falseotherwise

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status of an asynchronous function call returned as either True or False

Examples

Check Cancellation Status of Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval functionCancel it and check that the engine stopped the loopimport matlabengineeng = matlabenginestart_matlab()

cancelled

1-247

ret = engeval(while 1 endnargout=0async=True)eval_stop = retcancel()tf = retcancelled()print(tf)

True

See Also

1 API Reference

1-248

doneClass matlabengineFutureResultPackage matlabengine

Completion status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultdone()

Descriptiontf = FutureResultdone() returns the completion status of a MATLAB functioncalled asynchronously from Python FutureResultdone returns True if the functionhas finished and False if it has not finished

Output Argumentstf mdash Completion status of asynchronous function callTrue | False

Completion status of an asynchronous function call returned as either True or False

Examples

Check If Asynchronous Call Finished

Call the MATLAB sqrt function with async = True Check the status of ret to learn ifsqrt is finished

import matlabengineeng = matlabenginestart_matlab()

done

1-249

ret = engsqrt(40async=True)tf = retdone()print(tf)

True

When retdone() returns True then you can call retresult() to return the squareroot

See Also

1 API Reference

1-250

resultClass matlabengineFutureResultPackage matlabengine

Result of asynchronous call to MATLAB function from Python

Syntaxret = FutureResultresult(timeout=None)

Descriptionret = FutureResultresult(timeout=None) returns the actual result of a call to aMATLAB function called asynchronously from Python

Input Argumentstimeout mdash Timeout value in secondsNone (default) | Python float

Timeout value in seconds specified as Python data type float to wait for result of thefunction call If timeout = None the FutureResultresult function waits until thefunction call finishes and then returns the result

Output Argumentsret mdash Result of asynchronous function callPython object

Result of an asynchronous function call returned as a Python object that is the actualoutput argument of a call to a MATLAB function

result

1-251

Examples

Get MATLAB Output Argument from Asynchronous Call

Call the MATLAB sqrt function from Python Set async to True and get the squareroot from the FutureResult object

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

See Also

1 API Reference

1-252

matlabengineMatlabEngine classPackage matlabengine

Python object using MATLAB as computational engine within Python session

DescriptionThe MatlabEngine class uses a MATLAB process as a computational engine for PythonYou can call MATLAB functions as methods of a MatlabEngine object because thefunctions are dynamically invoked when you call them You also can call functions andscripts that you define You can send data to and retrieve data from the MATLABworkspace associated with a MatlabEngine object

ConstructionThe matlabenginestart_matlab function creates a MatlabEngine object each timeit is called There is no need to call matlabengineMatlabEngine() to createMatlabEngine objects of your own

MethodsYou can call any MATLAB function as a method of a MatlabEngine object The enginedynamically invokes a MATLAB function when you call it The syntax shows positionalkeyword and output arguments of a function call

ret =MatlabEnginematlabfunc(argsnargout=1async=Falsestdout=sysstsdoutstderr=sysstderr)

Replace matlabfunc with the name of any MATLAB function (such as isprime orsqrt) Replace args with input arguments for the MATLAB function you call Thekeyword arguments specify

matlabengineMatlabEngine class

1-253

bull The number of output arguments the function returnsbull Whether the engine calls the function asynchronouslybull Where the engine sends standard output and standard error coming from the function

Specify keyword arguments only when specifying values that are not the default valuesshown in the syntax

Input Arguments to MATLAB FunctionArgument Description Python Typeargs Input arguments to

MATLAB function specifiedas positional arguments

Any Python types that theengine can convert toMATLAB types

Keyword Arguments to EngineArgument Description Python Typenargout Number of output

arguments from MATLABfunction

intDefault 1

async Flag to call MATLABfunction asynchronously

boolDefault False

stdout Standard output StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstdout

stderr Standard error StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstderr

1 API Reference

1-254

Output ArgumentsOutput Type Description Required Keyword

ArgumentsPython variable One output argument from

MATLAB functionDefault values

tuple Multiple output argumentsfrom MATLAB function

nargout=n (where n gt 1)

None No output argument fromMATLAB function

nargout=0

FutureResult object A placeholder for outputarguments fromasynchronous call toMATLAB function

async=True

ExceptionsMatlabExecutionError Function call fails to executeRejectedExecutionError MATLAB engine terminatedSyntaxError Syntax error in a function callTypeError Data type of an input or output argument

not supported

Attributesworkspace Python dictionary containing references to

MATLAB variables You can assign data toand get data from a MATLAB variablethrough the workspace The name of eachMATLAB variable you create becomes akey in the workspace dictionary The keysin workspace must be valid MATLABidentifiers (for example you cannot usenumbers as keys)

matlabengineMatlabEngine class

1-255

Examples

Call MATLAB Functions from Python

Call the MATLAB sqrt function from Python using the engine

import matlabengineeng = matlabenginestart_matlab()ret = engsqrt(40)print(ret)

20

Put Array Into MATLAB Workspace

Create an array in Python and put it into the MATLAB workspace

import matlabengineeng = matlabenginestart_matlab()px = englinspace(006281000)

px is a MATLAB array but englinspace returned it to Python To use it in MATLABput the array into the MATLAB workspace

engworkspace[mx] = px

When you add an entry to the engine workspace dictionary you create a MATLABvariable as well The engine converts the data to a MATLAB data type

Get Data from MATLAB Workspace

Get pi from the MATLAB workspace and copy it to a Python variable

import matlabengineeng = matlabenginestart_matlab()engeval(a = pinargout=0)mpi = engworkspace[a]print(mpi)

1 API Reference

1-256

314159265359

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquobull ldquoRedirect Standard Output and Error to Pythonrdquo

See AlsomatlabengineFutureResult | matlabenginestart_matlab

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from PythonrdquoldquoRedirect Standard Output and Error to Pythonrdquo

Introduced in R2014b

matlabengineMatlabEngine class

1-257

matlabenginestart_matlabStart MATLAB Engine for Python

Syntaxeng = matlabenginestart_matlab()

eng = matlabenginestart_matlab(option)eng = matlabenginestart_matlab(async)eng = matlabenginestart_matlab(background)eng = matlabenginestart_matlab( ___ )

Descriptioneng = matlabenginestart_matlab() starts a new MATLAB process and returnsPython variable eng which is a MatlabEngine object for communicating with theMATLAB process

If MATLAB cannot be started the engine raises an EngineError exception

eng = matlabenginestart_matlab(option) uses startup options specified byoption

For example call matlabenginestart_matlab(-desktop) to start the MATLABdesktop from Python

eng = matlabenginestart_matlab(async) starts MATLAB asynchronously ifasync is True

eng = matlabenginestart_matlab(background) starts MATLABasynchronously if background is True

eng = matlabenginestart_matlab( ___ ) can include any of the input argumentsin previous syntaxes

1 API Reference

1-258

Examples

Start MATLAB Engine from Python

Start an engine and a new MATLAB process from the Python command line

import matlabengineeng = matlabenginestart_matlab()

Start Multiple Engines

Start a different MATLAB process from each engine

import matlabengineeng1 = matlabenginestart_matlab()eng2 = matlabenginestart_matlab()

Start MATLAB Desktop with Engine

Start an engine with the MATLAB desktop

import matlabengineeng = matlabenginestart_matlab(-desktop)

You also can start the desktop after you start the engineimport matlabengineeng = matlabenginestart_matlab()engdesktop(nargout=0)

Note You can call MATLAB functions from both the desktop and Python

Start Engine Asynchronously

Start the engine with async=True While MATLAB starts you can enter commands atthe Python command line

matlabenginestart_matlab

1-259

import matlabenginefuture = matlabenginestart_matlab(async=True)eng = futureresult()engsqrt(4)

20

bull ldquoStart and Stop MATLAB Engine for Pythonrdquo

Input Argumentsoption mdash Startup options for MATLAB process-nodesktop (default) | string

Startup options for the MATLAB process specified as a string You can specify multiplestartup options with option

The engine supports -desktop to start MATLAB with the desktop In addition theengine supports all MATLAB startup options except for the options listed inldquoLimitationsrdquo on page 1-261Example matlabenginestart_matlab(-desktop -r format short) startsthe desktop from Python The engine passes -r format short to MATLAB

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

background mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargument background is an alias for async and will be removed in a future releaseExample matlabenginestart_matlab(background=True)

1 API Reference

1-260

Output Argumentseng mdash Python variable for communicating with MATLABMatlabEngine object | FutureResult object

Python variable for communicating with MATLAB returned as a MatlabEngine objectif async or background is set to False or a FutureResult object if async orbackground is set to True

Each time you call matlabenginestart_matlab it starts a new MATLAB process

LimitationsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

See AlsomatlabengineMatlabEngine

TopicsldquoStart and Stop MATLAB Engine for PythonrdquoldquoSpecify Startup OptionsrdquoldquoCommonly Used Startup Optionsrdquo

Introduced in R2014b

matlabenginestart_matlab

1-261

matOpen (C and Fortran)Open MAT-file

C Syntaxinclude mathMATFile matOpen(const char filename const char mode)

Fortran Syntaxinclude mathmwPointer matOpen(filename mode)character() filename mode

Argumentsfilename

Name of file to openmode

File opening mode The following table lists valid values for moder Opens file for reading only determines the current version of the MAT-

file by inspecting the files and preserves the current versionu Opens file for update both reading and writing If the file does not exist

does not create a file (equivalent to the r+ mode of fopen) Determinesthe current version of the MAT-file by inspecting the files and preservesthe current version

w Opens file for writing only deletes previous contents if anyw4 Creates a MAT-file compatible with MATLAB Versions 4 software and

earlierw6 Creates a MAT-file compatible with MATLAB Version 5 (R8) software or

earlier Equivalent to wL mode

1 API Reference

1-262

wL Opens file for writing character data using the default character set foryour system Use MATLAB Version 6 or 65 software to read theresulting MAT-file

If you do not use the wL mode switch MATLAB writes character data tothe MAT-file using Unicodereg character encoding by default

Equivalent to w6 modew7 Creates a MAT-file compatible with MATLAB Version 70 (R14) software

or earlier Equivalent to wz modewz Opens file for writing compressed data By default the MATLAB save

function compresses workspace variables as they are saved to a MAT-fileTo use the same compression ratio when creating a MAT-file with thematOpen function use the wz option

Equivalent to w7 modew73 Creates a MAT-file in an HDF5-based format that can store objects that

occupy more than 2 GB

ReturnsFile handle or NULL in C (0 in Fortran) if the open fails

DescriptionThis routine opens a MAT-file for reading and writing

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1F

matOpen (C and Fortran)

1-263

bull matdemo2F

See AlsomatClose save

Introduced before R2006a

1 API Reference

1-264

matPutVariable (C and Fortran)Array to MAT-file

C Syntaxinclude mathint matPutVariable(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariable(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library along with matGetFp to determine status

matPutVariable (C and Fortran)

1-265

DescriptionThis routine puts an mxArray into a MAT-file

matPutVariable writes mxArray pm to the MAT-file mfp If the mxArray does notexist in the MAT-file the function appends it to the end If an mxArray with the samename exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatGetVariable matGetFp

Introduced before R2006a

1 API Reference

1-266

matPutVariableAsGlobal (C and Fortran)Array to MAT-file as originating from global workspace

C Syntaxinclude mathint matPutVariableAsGlobal(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariableAsGlobal(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library with matGetFp to determine status

matPutVariableAsGlobal (C and Fortran)

1-267

DescriptionThis routine puts an mxArray into a MAT-file matPutVariableAsGlobal is likematPutVariable except that MATLAB software loads the array into the globalworkspace and sets a reference to it in the local workspace If you write to a MATLAB 4format file matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable

matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp If the mxArraydoes not exist in the MAT-file the function appends it to the end If an mxArray with thesame name exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable matGetFp

Introduced before R2006a

1 API Reference

1-268

mexAtExit (C and Fortran)Register function to call when MEX function clears or MATLAB terminates

C Syntaxinclude mexhint mexAtExit(void (ExitFcn)(void))

Fortran Syntaxinclude fintrfhinteger4 mexAtExit(ExitFcn)subroutine ExitFcn()

ArgumentsExitFcn

Pointer to function you want to run on exit

ReturnsAlways returns 0

DescriptionUse mexAtExit to register a function to call just before clearing the MEX function orterminating MATLAB mexAtExit gives your MEX function a chance to perform taskssuch as freeing persistent memory and closing files Other typical tasks include closingstreams or sockets

mexAtExit (C and Fortran)

1-269

Each MEX function can register only one active exit function at a time If you callmexAtExit more than once MATLAB uses the ExitFcn from the more recentmexAtExit call as the exit function

If a MEX function is locked you cannot clear the MEX file Therefore if you attempt toclear a locked MEX file MATLAB does not call the ExitFcn

In Fortran declare the ExitFcn as external in the Fortran routine that callsmexAtExit if it is not within the scope of the file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See AlsomexLock mexUnlock

Introduced before R2006a

1 API Reference

1-270

mexCallMATLAB (C and Fortran)Call MATLAB function user-defined function or MEX file

C Syntaxinclude mexhint mexCallMATLAB(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhinteger4 mexCallMATLAB(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

Argumentsnlhs

Number of output arguments Must be less than or equal to 50plhs

Array of pointers to output argumentsnrhs

Number of input arguments Must be less than or equal to 50prhs

Array of pointers to input argumentsfunctionName

Character string containing name of the MATLAB built-in function operator user-defined function or MEX file you are calling

mexCallMATLAB (C and Fortran)

1-271

If functionName is an operator place the operator inside a pair of single quotes forexample +

Returns0 if successful and a nonzero value if unsuccessful

DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions MATLABoperators user-defined functions or other MEX files Both mexCallMATLAB andmexEvalString execute MATLAB commands Use mexCallMATLAB for returningresults (left side arguments) back to the MEX file The mexEvalString function cannotreturn values to the MEX file

For a complete description of the input and output arguments passed to functionNamesee mexFunction

Error HandlingIf functionName detects an error MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt To trap errors use the mexCallMATLABWithTrapfunction

Limitationsbull Avoid using the mexCallMATLAB function in Simulinkreg S-functions If you do do not

store the resulting plhs mxArray pointers in any S-function block state that persistsafter the MEX function finishes Outputs of mexCallMATLAB have temporary scopeand are automatically destroyed at the end of the MEX function call

bull It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLABFor example this function returns two variables but only assigns one of them a value

function [ab] = foo(c)a = 2c

1 API Reference

1-272

If you then call foo using mexCallMATLAB the unassigned output variable is nowtype mxUNKNOWN_CLASS

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexevalstringcbull mexcallmatlabwithtrapc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxisclassc

See AlsomexFunction mexCallMATLABWithTrap mexEvalString mxDestroyArray

Tipsbull MATLAB allocates dynamic memory to store the arrays in plhs for mexCallMATLAB

MATLAB automatically deallocates the dynamic memory when you exit the MEX fileHowever if heap space is at a premium call mxDestroyArray when you are finishedwith the arrays in plhs

Note The plhs argument for mexCallMATLAB is not the same as the plhs formexFunction Do not destroy an mxArray returned in plhs for mexFunction

mexCallMATLAB (C and Fortran)

1-273

Introduced before R2006a

1 API Reference

1-274

mexCallMATLABWithTrap (C and Fortran)Call MATLAB function user-defined function or MEX-file and capture error information

C Syntaxinclude mexhmxArray mexCallMATLABWithTrap(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhmwPointer mexCallMATLABWithTrap(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

ArgumentsFor more information about arguments see mexCallMATLAB

nlhsNumber of desired output arguments

plhsArray of pointers to output arguments

nrhsNumber of input arguments

prhsArray of pointers to input arguments

functionNameCharacter string containing the name of the MATLAB built-in function operatorfunction or MEX-file that you are calling

mexCallMATLABWithTrap (C and Fortran)

1-275

ReturnsNULL if no error occurred otherwise a pointer to an mxArray of class MException

DescriptionThe mexCallMATLABWithTrap function performs the same function as mexCallMATLABHowever if MATLAB detects an error when executing functionName MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexCallMATLABWithTrap For information about MException see ldquoRespond to anExceptionrdquo

See AlsomexCallMATLAB MException

Introduced in R2008b

1 API Reference

1-276

mexErrMsgIdAndTxt (C and Fortran)Display error message with identifier and return to MATLAB prompt

C Syntaxinclude mexhvoid mexErrMsgIdAndTxt(const char errorid const char errormsg )

Fortran Syntaxinclude fintrfhsubroutine mexErrMsgIdAndTxt(errorid errormsg)character() errorid errormsg

Argumentserrorid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

errormsgString to display In C the string can include conversion specifications used by theANSIreg C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexErrMsgIdAndTxt function writes an error message to the MATLAB windowFor more information see the error function syntax statement using a message

mexErrMsgIdAndTxt (C and Fortran)

1-277

identifier After the error message prints MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt

Calling mexErrMsgIdAndTxt does not clear the MEX file from memory SomexErrMsgIdAndTxt does not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgIdAndTxt automatically frees the allocated memory

Note If you get warnings when using mexErrMsgIdAndTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errorid and errormsg the mexErrMsgIdAndTxt functiondetermines where the error occurred and displays the following information Forexample in the function foo mexErrMsgIdAndTxt displays

Error using foo

If you compile your MEX file with the MinGW-w64 compiler see the limitations withexception handling topic in ldquoTroubleshooting and Limitations Compiling CC++ MEXFiles with MinGW-w64rdquo

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrcbull matrixDividecbull timestwoFbull xtimesyF

1 API Reference

1-278

Validate char Input

The following code snippet checks if input argument prhs[0] is a string If not thecode displays a warning If there is an error reading the input string the code displaysan error message and terminates the MEX file

char bufint buflen

if (mxIsChar(prhs[0])) if (mxGetString(prhs[0] buf buflen) == 0) mexPrintf(The input string is sn buf) else mexErrMsgIdAndTxt(MyProgConvertString Could not convert string data) exit MEX file else mexWarnMsgIdAndTxt(MyProgInputString Input should be a string to print properly)

continue with processing

See Alsoerror | mexWarnMsgIdAndTxt

TopicsldquoMemory Considerations for Class DestructorsrdquoldquoTroubleshooting and Limitations Compiling CC++ MEX Files with MinGW-w64rdquo

Introduced before R2006a

mexErrMsgIdAndTxt (C and Fortran)

1-279

mexErrMsgTxt (C and Fortran)Display error message and return to MATLAB prompt

Note mexErrMsgTxt is not recommended Use mexErrMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexErrMsgTxt(const char errormsg)

Fortran Syntaxsubroutine mexErrMsgTxt(errormsg)character() errormsg

Argumentserrormsg

String containing the error message to display

DescriptionmexErrMsgTxt writes an error message to the MATLAB window After the errormessage prints MATLAB terminates the MEX-file and returns control to the MATLABprompt

Calling mexErrMsgTxt does not clear the MEX-file from memory So mexErrMsgTxtdoes not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgTxt automatically frees the allocated memory

1 API Reference

1-280

Note If you get warnings when using mexErrMsgTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errormsg the mexerrmsgtxt function determines where the erroroccurred and displays the following information If an error labeled Print my errormessage occurs in the function foo mexerrmsgtxt displays

Error using fooPrint my error message

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexErrMsgTxt (C and Fortran)

1-281

mexEvalString (C and Fortran)Execute MATLAB command in caller workspace

C Syntaxinclude mexhint mexEvalString(const char command)

Fortran Syntaxinclude fintrfhinteger4 mexEvalString(command)character() command

Argumentscommand

String containing MATLAB command to execute

Returns0 if successful and 1 if an error occurs

DescriptionCall mexEvalString to invoke a MATLAB command in the workspace of the caller

mexEvalString and mexCallMATLAB both execute MATLAB commands UsemexCallMATLAB for returning results (left side arguments) back to the MEX file ThemexEvalString function cannot return values to the MEX file

1 API Reference

1-282

All arguments that appear to the right of an equal sign in the command string must becurrent variables of the caller workspace

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction For more information see ldquoVariable Namesrdquo

Error HandlingIf command detects an error MATLAB returns control to the MEX-file andmexEvalString returns 1 If you want to trap errors use themexEvalStringWithTrap function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexevalstringc

See AlsomexCallMATLAB mexEvalStringWithTrap

Introduced before R2006a

mexEvalString (C and Fortran)

1-283

mexEvalStringWithTrap (C and Fortran)Execute MATLAB command in caller workspace and capture error information

C Syntaxinclude mexhmxArray mexEvalStringWithTrap(const char command)

Fortran Syntaxinclude fintrfhmwPointer mexEvalStringWithTrap(command)character() command

Argumentscommand

String containing the MATLAB command to execute

ReturnsObject ME of class MException

DescriptionThe mexEvalStringWithTrap function performs the same function as mexEvalStringHowever if MATLAB detects an error when executing command MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexEvalStringWithTrap

1 API Reference

1-284

See AlsomexEvalString MException mexCallMATLAB

Introduced before R2006a

mexEvalStringWithTrap (C and Fortran)

1-285

mexFunction (C and Fortran)Entry point to CC++ or Fortran MEX file

C Syntaxinclude mexhvoid mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

Fortran Syntaxinclude fintrfhsubroutine mexFunction(nlhs plhs nrhs prhs)integer nlhs nrhsmwPointer plhs() prhs()

Argumentsnlhs

Number of expected output mxArraysplhs

Array of pointers to the expected output mxArraysnrhs

Number of input mxArraysprhs

Array of pointers to the input mxArrays Do not modify any prhs values in yourMEX file Changing the data in these read-only mxArrays can produce undesiredside effects

1 API Reference

1-286

DescriptionmexFunction is not a routine you call Rather mexFunction is the name of the gatewayfunction in C (subroutine in Fortran) which every MEX file requires When you invoke aMEX function MATLAB software finds and loads the corresponding MEX file of thesame name MATLAB then searches for a symbol named mexFunction within the MEXfile If it finds one it calls the MEX function using the address of the mexFunctionsymbol MATLAB displays an error message if it cannot find a routine namedmexFunction inside the MEX file

When you invoke a MEX file MATLAB automatically seeds nlhs plhs nrhs and prhswith the calling arguments In the syntax of the MATLAB language functions have thegeneral form

[abc] = fun(def)

where the denotes more items of the same format The abc are left-sideoutput arguments and the def are right-side input arguments The argumentsnlhs and nrhs contain the number of left side and right side arguments respectivelyprhs is an array of mxArray pointers whose length is nrhs plhs is an array whoselength is nlhs where your function must set pointers for the output mxArrays

Note It is possible to return an output value even if nlhs = 0 which corresponds toreturning the result in the ans variable

To experiment with passing input arguments build the mexfunctionc examplefollowing the instructions in ldquoTable of MEX File Source Code Filesrdquo

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctioncbull mexlockfF

mexFunction (C and Fortran)

1-287

See Also

TopicsldquoIntroducing MEX Filesrdquo

Introduced before R2006a

1 API Reference

1-288

mexFunctionName (C and Fortran)Name of current MEX function

C Syntaxinclude mexhconst char mexFunctionName(void)

Fortran Syntaxinclude fintrfhcharacter() mexFunctionName()

ReturnsName of the current MEX function

DescriptionmexFunctionName returns the name of the current MEX function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

Introduced before R2006a

mexFunctionName (C and Fortran)

1-289

mexGet (C)Value of specified graphics property

Note Do not use mexGet Use mxGetProperty instead

C Syntaxinclude mexhconst mxArray mexGet(double handle const char property)

Argumentshandle

Handle to a particular graphics objectproperty

Graphics property

ReturnsValue of the specified property in the specified graphics object on success Returns NULLon failure Do not modify the return argument from mexGet Changing the data in aconst (read-only) mxArray can produce undesired side effects

DescriptionCall mexGet to get the value of the property of a certain graphics object mexGet is theAPI equivalent of the MATLAB get function To set a graphics property value callmexSet

1 API Reference

1-290

See AlsomxGetProperty mxSetProperty

mexGet (C)

1-291

mexGetVariable (C and Fortran)Copy of variable from specified workspace

C Syntaxinclude mexhmxArray mexGetVariable(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariable(workspace varname)character() workspace varname

Argumentsworkspace

Specifies where mexGetVariable searches for array varname The possible valuesarebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of the variable to copy

ReturnsCopy of the variable on success Returns NULL in C (0 on Fortran) on failure A commoncause of failure is specifying a variable that is not currently in the workspace Perhapsthe variable was in the workspace at one time but has since been cleared

1 API Reference

1-292

DescriptionCall mexGetVariable to get a copy of the specified variable The returned mxArraycontains a copy of all the data and characteristics that the variable had in the otherworkspace Modifications to the returned mxArray do not affect the variable in theworkspace unless you write the copy back to the workspace with mexPutVariable

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

See AlsomexGetVariablePtr mexPutVariable mxDestroyArray

mexGetVariable (C and Fortran)

1-293

mexGetVariablePtr (C and Fortran)Read-only pointer to variable from another workspace

C Syntaxinclude mexhconst mxArray mexGetVariablePtr(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariablePtr(workspace varname)character() workspace varname

Argumentsworkspace

Specifies which workspace you want mexGetVariablePtr to search The possiblevalues arebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of a variable in another workspace This is a variable name not an mxArraypointer

ReturnsRead-only pointer to the mxArray on success Returns NULL in C (0 in Fortran) onfailure

1 API Reference

1-294

DescriptionCall mexGetVariablePtr to get a read-only pointer to the specified variable varnameinto your MEX-file workspace This command is useful for examining an mxArrays dataand characteristics If you want to change data or characteristics use mexGetVariable(along with mexPutVariable) instead of mexGetVariablePtr

If you simply want to examine data or characteristics mexGetVariablePtr offerssuperior performance because the caller wants to pass only a pointer to the array

See AlsomexGetVariable

Introduced before R2006a

mexGetVariablePtr (C and Fortran)

1-295

mexIsLocked (C and Fortran)Determine if MEX-file is locked

C Syntaxinclude mexhbool mexIsLocked(void)

Fortran Syntaxinclude fintrfhinteger4 mexIsLocked()

ReturnsLogical 1 (true) if the MEX-file is locked logical 0 (false) if the file is unlocked

DescriptionCall mexIsLocked to determine if the MEX-file is locked By default MEX-files areunlocked meaning you can clear the MEX-file at any time

To unlock a MEX-file call mexUnlock

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-296

See AlsomexLock mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexIsLocked (C and Fortran)

1-297

mexLock (C and Fortran)Prevent clearing MEX-file from memory

C Syntaxinclude mexhvoid mexLock(void)

Fortran Syntaxinclude fintrfhsubroutine mexLock()

DescriptionBy default MEX files are unlocked meaning you can clear them at any time CallmexLock to prohibit clearing a MEX file

To unlock a MEX file call mexUnlock Do not use the munlock function

mexLock increments a lock count If you call mexLock n times call mexUnlock n timesto unlock your MEX file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-298

See AlsomexIsLocked mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexLock (C and Fortran)

1-299

mexMakeArrayPersistent (C and Fortran)Make array persist after MEX file completes

C Syntaxinclude mexhvoid mexMakeArrayPersistent(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mexMakeArrayPersistent(pm)mwPointer pm

Argumentspm

Pointer to an mxArray created by an mxCreate function

DescriptionBy default an mxArray allocated by an mxCreate function is not persistent TheMATLAB memory management facility automatically frees a nonpersistent mxArraywhen the MEX function finishes If you want the mxArray to persist through multipleinvocations of the MEX function call the mexMakeArrayPersistent function

Do not assign an array created with the mexMakeArrayPersistent function to theplhs output argument of a MEX file

Note If you create a persistent mxArray you are responsible for destroying it usingmxDestroyArray when the MEX file is cleared If you do not destroy a persistentmxArray MATLAB leaks memory See mexAtExit to see how to register a function that

1 API Reference

1-300

gets called when the MEX file is cleared See mexLock to see how to lock your MEX fileso that it is never cleared

See AlsomexAtExit mxDestroyArray mexLock mexMakeMemoryPersistent and themxCreate functions

Introduced before R2006a

mexMakeArrayPersistent (C and Fortran)

1-301

mexMakeMemoryPersistent (C and Fortran)Make memory allocated by MATLAB software persist after MEX-function completes

C Syntaxinclude mexhvoid mexMakeMemoryPersistent(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mexMakeMemoryPersistent(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of memory allocated by one of the MATLAB memoryallocation routines

DescriptionBy default memory allocated by MATLAB is nonpersistent so it is freed automaticallywhen the MEX function finishes If you want the memory to persist callmexMakeMemoryPersistent

Note If you create persistent memory you are responsible for freeing it when the MEXfunction is cleared If you do not free the memory MATLAB leaks memory To freememory use mxFree See mexAtExit to see how to register a function that gets calledwhen the MEX function is cleared See mexLock to see how to lock your MEX function sothat it is never cleared

1 API Reference

1-302

See AlsomexAtExit mexLock mexMakeArrayPersistent mxCalloc mxFree mxMallocmxRealloc

Introduced before R2006a

mexMakeMemoryPersistent (C and Fortran)

1-303

mexPrintf (C and Fortran)ANSI C PRINTF-style output routine

C Syntaxinclude mexhint mexPrintf(const char message )

Fortran Syntaxinclude fintrfhinteger4 mexPrintf(message)character() message

Argumentsmessage

String to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

ReturnsNumber of characters printed including characters specified with backslash codes suchas n and b

1 API Reference

1-304

DescriptionThis routine prints a string on the screen and in the diary (if the diary is in use) Itprovides a callback to the standard C printf routine already linked inside MATLABsoftware which avoids linking the entire stdio library into your MEX file

In a C MEX file call mexPrintf instead of printf to display a string

Note If you want the literal in your message use in the message string since hasspecial meaning to printf Failing to do so causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See Alsosprintf mexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexPrintf (C and Fortran)

1-305

mexPutVariable (C and Fortran)Array from MEX-function into specified workspace

C Syntaxinclude mexhint mexPutVariable(const char workspace const char varname const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mexPutVariable(workspace varname pm)character() workspace varnamemwPointer pm

Argumentsworkspace

Specifies scope of the array you are copying Values for workspace arebase Copy mxArray to the base workspacecaller Copy mxArray to the caller workspaceglobal Copy mxArray to the list of global variables

varnameName of mxArray in the workspace

pmPointer to the mxArray

1 API Reference

1-306

Returns0 on success 1 on failure A possible cause of failure is that pm is NULL in C (0 inFortran)

DescriptionCall mexPutVariable to copy the mxArray at pointer pm from your MEX-function intothe specified workspace MATLAB software gives the name varname to the copiedmxArray in the receiving workspace

mexPutVariable makes the array accessible to other entities such as MATLAB user-defined functions or other MEX-functions

If a variable of the same name exists in the specified workspace mexPutVariableoverwrites the previous contents of the variable with the contents of the new mxArrayFor example suppose the MATLAB workspace defines variable Peaches as

Peaches1 2 3 4

and you call mexPutVariable to copy Peaches into the same workspace

mexPutVariable(base Peaches pm)

The value passed by mexPutVariable replaces the old value of Peaches

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

mexPutVariable (C and Fortran)

1-307

See AlsomexGetVariable

1 API Reference

1-308

mexSet (C)Set value of specified graphics property

Note Do not use mexSet Use mxSetProperty instead

C Syntaxinclude mexhint mexSet(double handle const char property mxArray value)

Argumentshandle

Handle to a particular graphics objectproperty

String naming a graphics propertyvalue

Pointer to an mxArray holding the new value to assign to the property

Returns0 on success 1 on failure Possible causes of failure include

bull Specifying a nonexistent propertybull Specifying an illegal value for that property for example specifying a string value for

a numerical property

mexSet (C)

1-309

DescriptionCall mexSet to set the value of the property of a certain graphics object mexSet is theAPI equivalent of the MATLAB set function To get the value of a graphics property callmexGet

See AlsomxGetProperty mxSetProperty

1 API Reference

1-310

mexSetTrapFlag (C and Fortran)Control response of MEXCALLMATLAB to errors

C Syntaxinclude mexhvoid mexSetTrapFlag(int trapflag)

Note mexSetTrapFlag will be removed in a future version UsemexCallMATLABWithTrap instead

Fortran Syntaxsubroutine mexSetTrapFlag(trapflag)integer4 trapflag

Argumentstrapflag

Control flag Possible values are0 On error control returns to the MATLAB prompt1 On error control returns to your MEX-file

DescriptionCall mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB

If you do not call mexSetTrapFlag then whenever MATLAB detects an error in a call tomexCallMATLAB MATLAB automatically terminates the MEX-file and returns controlto the MATLAB prompt Calling mexSetTrapFlag with trapflag set to 0 is equivalentto not calling mexSetTrapFlag at all

mexSetTrapFlag (C and Fortran)

1-311

If you call mexSetTrapFlag and set the trapflag to 1 then whenever MATLABdetects an error in a call to mexCallMATLAB MATLAB does not automatically terminatethe MEX-file Rather MATLAB returns control to the line in the MEX-file immediatelyfollowing the call to mexCallMATLAB The MEX-file is then responsible for taking anappropriate response to the error

If you call mexSetTrapFlag the value of the trapflag you set remains in effect untilthe next call to mexSetTrapFlag within that MEX-file or if there are no more calls tomexSetTrapFlag until the MEX-file exits If a routine defined in a MEX-file callsanother MEX-file MATLAB

1 Saves the current value of the trapflag in the first MEX-file2 Calls the second MEX-file with the trapflag initialized to 0 within that file3 Restores the saved value of trapflag in the first MEX-file when the second MEX-

file exits

See AlsomexCallMATLAB mexCallMATLABWithTrap mexAtExit mexErrMsgTxt

Introduced in R2008b

1 API Reference

1-312

mexUnlock (C and Fortran)Allow clearing MEX-file from memory

C Syntaxinclude mexhvoid mexUnlock(void)

Fortran Syntaxinclude fintrfhsubroutine mexUnlock()

DescriptionBy default MEX-files are unlocked meaning you can clear them at any time CallingmexLock locks a MEX-file so that you cannot clear it from memory Call mexUnlock toremove the lock

mexLock increments a lock count If you called mexLock n times call mexUnlock ntimes to unlock your MEX-file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

mexUnlock (C and Fortran)

1-313

See AlsomexIsLocked mexLock mexMakeArrayPersistent mexMakeMemoryPersistentclear

1 API Reference

1-314

mexWarnMsgIdAndTxt (C and Fortran)Warning message with identifier

C Syntaxinclude mexhvoid mexWarnMsgIdAndTxt(const char warningid const char warningmsg )

Fortran Syntaxinclude fintrfhsubroutine mexWarnMsgIdAndTxt(warningid warningmsg)character() warningid warningmsg

Argumentswarningid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

warningmsgString to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexWarnMsgIdAndTxt function writes a warning message to the MATLABcommand prompt The warnings displayed are the same as warnings issued by the

mexWarnMsgIdAndTxt (C and Fortran)

1-315

MATLAB warning function To control the information displayed or suppressed call thewarning function with the desired settings before calling your MEX-file

Unlike mexErrMsgIdAndTxt calling mexWarnMsgIdAndTxt does not terminate theMEX-file

See AlsomexErrMsgIdAndTxt warning

Introduced before R2006a

1 API Reference

1-316

mexWarnMsgTxt (C and Fortran)Warning message

Note mexWarnMsgTxt is not recommended Use mexWarnMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexWarnMsgTxt(const char warningmsg)

Fortran Syntaxsubroutine mexWarnMsgTxt(warningmsg)character() warningmsg

Argumentswarningmsg

String containing the warning message to display

DescriptionmexWarnMsgTxt causes MATLAB software to display the contents of warningmsgmexWarnMsgTxt does not terminate the MEX-file

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexWarnMsgTxt (C and Fortran)

1-317

mwIndex (C and Fortran)Type for index values

DescriptionmwIndex is a type that represents index values such as indices into arrays Use thisfunction for cross-platform flexibility By default mwIndex is equivalent to int in CWhen using the mex -largeArrayDims switch mwIndex is equivalent to size_t in CIn Fortran mwIndex is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwIndex is a preprocessor macro The Fortran header file containing thistype is

include fintrfh

See Alsomex mwSize mwSignedIndex

Introduced before R2006a

1 API Reference

1-318

mwPointer (Fortran)Platform-independent pointer type

DescriptionmwPointer is a preprocessor macro that declares the appropriate Fortran typerepresenting a pointer to an mxArray or to other data that is not of a native Fortrantype such as memory allocated by mxMalloc On 32-bit platforms the Fortran type thatrepresents a pointer is INTEGER4 on 64-bit platforms it is INTEGER8 The Fortranpreprocessor translates mwPointer to the Fortran declaration that is appropriate for theplatform on which you compile your file

If your Fortran compiler supports preprocessing you can use mwPointer to declarefunctions arguments and variables that represent pointers If you cannot usemwPointer ensure that your declarations have the correct size for the platform on whichyou are compiling Fortran code

The Fortran header file containing this type is

include fintrfh

ExamplesThis example declares the arguments for mexFunction in a Fortran MEX file

subroutine mexFunction(nlhs plhs nrhs prhs)mwPointer plhs() prhs()integer nlhs nrhs

For additional examples see the Fortran files with names ending in F in thematlabrootexternexamples folder

Introduced in R2006a

mwPointer (Fortran)

1-319

mwSignedIndex (C and Fortran)Signed integer type for size values

DescriptionmwSignedIndex is a signed integer type that represents size values such as arraydimensions Use this function for cross-platform flexibility By default mwSignedIndexis equivalent to ptrdiff_t in C++ In Fortran mwSignedIndex is similarly equivalentto INTEGER4 or INTEGER8 based on platform and compilation flags

The C header file containing this type is

include matrixh

The Fortran header file containing this type is

include fintrfh

See AlsomwSize mwIndex

Introduced in R2009a

1 API Reference

1-320

mwSize (C and Fortran)Type for size values

DescriptionmwSize is a type that represents size values such as array dimensions Use this functionfor cross-platform flexibility By default mwSize is equivalent to size_t in C mwSize isan unsigned type meaning a nonnegative integer

When using the mex -compatibleArrayDims switch mwSize is equivalent to int in CIn Fortran mwSize is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwSize is a preprocessor macro The Fortran header file containing this typeis

include fintrfh

See Alsomex mwIndex mwSignedIndex

Introduced before R2006a

mwSize (C and Fortran)

1-321

mxAddField (C and Fortran)Add field to structure array

C Syntaxinclude matrixhextern int mxAddField(mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxAddField(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of the field you want to add

ReturnsField number on success or -1 if inputs are invalid or an out-of-memory conditionoccurs

1 API Reference

1-322

DescriptionCall mxAddField to add a field to a structure array Create the values with themxCreate functions and use mxSetFieldByNumber to set the individual values for thefield

See AlsomxRemoveField mxSetFieldByNumber

Introduced before R2006a

mxAddField (C and Fortran)

1-323

mxArray (C)Type for MATLAB array

DescriptionThe fundamental type underlying MATLAB data For information on how the MATLABarray works with MATLAB-supported variables see ldquoMATLAB Datardquo

mxArray is a C language opaque type

All C MEX-files start with a gateway routine called mexFunction which requiresmxArray for both input and output parameters For information about the C MEX-filegateway routine see ldquoComponents of MEX Filerdquo

Once you have MATLAB data in your MEX-file use functions in the Matrix Library tomanipulate the data and functions in the MEX Library to perform operations in theMATLAB environment You use mxArray to pass data to and from these functions

Use any of the mxCreate functions to create data and the correspondingmxDestroyArray function to free memory

The header file containing this type is

include matrixh

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomexFunction mxClassID mxCreateDoubleMatrix mxCreateNumericArraymxCreateString mxDestroyArray mxGetData mxSetData

1 API Reference

1-324

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquobull For troubleshooting mxArray errors in other MathWorks products search the

documentation for that product or see MATLAB Answerstrade topic Subscripting intoan mxArray is not supported

Introduced before R2006a

mxArray (C)

1-325

mxArrayToString (C)Array to string

C Syntaxinclude matrixhchar mxArrayToString(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string Returns NULL on failure Possible reasons for failure include out ofmemory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToString to copy the character data of an mxCHAR array into a C-stylestring The C-style string is always terminated with a NULL character and stored incolumn-major order

If the array contains multiple rows the rows are copied column-wise into a single array

This function is similar to mxGetString except that

bull It does not require the length of the string as an inputbull It supports both multi-byte and single-byte encoded characters On Windows and

Linuxreg platforms the default encoding is specified by the user locale setting

1 API Reference

1-326

mxArrayToString does not free the dynamic memory that the char pointer points toTherefore you typically free the C-style string (using mxFree) immediately after youhave finished using it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxArrayToUTF8String mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetString

Introduced before R2006a

mxArrayToString (C)

1-327

mxArrayToUTF8String (C)Array to string in UTF-8 encoding

C Syntaxinclude matrixhchar mxArrayToUTF8String(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string in UTF-8 encoding Returns NULL on failure Possible reasons for failureinclude out of memory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToUTF8String to copy the character data of an mxCHAR array into a C-style string The data is stored in column-major order If the array contains multiplerows the rows are copied column-wise into a single array

mxArrayToUTF8String does not free the dynamic memory that the char pointer pointsto Use mxFree to free memory

See AlsomxArrayToString mxFree mxCreateCharArray mxCreateString mxGetString

1 API Reference

1-328

Introduced in R2015a

mxArrayToUTF8String (C)

1-329

mxAssert (C)Check assertion value for debugging purposes

C Syntaxinclude matrixhvoid mxAssert(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionLike the ANSI C assert macro mxAssert checks the value of an assertion andcontinues execution only if the assertion holds If expr evaluates to logical 1 (true)mxAssert does nothing If expr evaluates to logical 0 (false) mxAssert terminates theMEX file and prints an error to the MATLAB command window The error contains theexpression of the failed assertion the file name and line number where the failedassertion occurred and the error_message text The error_message allows you tospecify a better description of why the assertion failed Use an empty string if you do notwant a description to follow the failed assertion message

The mex script turns off these assertions when building optimized MEX functions so useassertions for debugging purposes only To use mxAssert build the MEX file using themex -g filename syntax

Assertions are a way of maintaining internal consistency of logic Use them to keepyourself from misusing your own code and to prevent logical errors from propagating

1 API Reference

1-330

before they are caught Do not use assertions to prevent users of your code from misusingit

Assertions can be taken out of your code by the C preprocessor You can use these checksduring development and then remove them when the code works properly letting youuse them for troubleshooting during development without slowing down the finalproduct

See AlsomxAssertS mexErrMsgIdAndTxt

Introduced before R2006a

mxAssert (C)

1-331

mxAssertS (C)Check assertion value without printing assertion text

C Syntaxinclude matrixhvoid mxAssertS(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionmxAssertS is like mxAssert except mxAssertS does not print the text of the failedassertion

See AlsomxAssert

Introduced before R2006a

1 API Reference

1-332

mxCalcSingleSubscript (C and Fortran)Offset from first element to desired element

C Syntaxinclude matrixhmwIndex mxCalcSingleSubscript(const mxArray pm mwSize nsubs mwIndex subs)

Fortran Syntaxinclude fintrfhmwIndex mxCalcSingleSubscript(pm nsubs subs)mwPointer pmmwSize nsubsmwIndex subs

Argumentspm

Pointer to an mxArraynsubs

Number of elements in the subs array Typically you set nsubs equal to the numberof dimensions in the mxArray that pm points to

subsAn array of integers Each value in the array specifies that dimensions subscript InC syntax the value in subs[0] specifies the row subscript and the value insubs[1] specifies the column subscript Use zero-based indexing for subscripts Forexample to express the starting element of a two-dimensional mxArray in subs setsubs[0] to 0 and subs[1] to 0

In Fortran syntax the value in subs(1) specifies the row subscript and the value insubs(2) specifies the column subscript Use 1-based indexing for subscripts For

mxCalcSingleSubscript (C and Fortran)

1-333

example to express the starting element of a two-dimensional mxArray in subs setsubs(1) to 1 and subs(2) to 1

ReturnsThe number of elements or index between the start of the mxArray and the specifiedsubscript This number is the linear index equivalent of the subscripts Many MatrixLibrary routines (for example mxGetField) require an index as an argument

If subs describes the starting element of an mxArray mxCalcSingleSubscriptreturns 0 If subs describes the final element of an mxArray mxCalcSingleSubscriptreturns N-1 (where N is the total number of elements)

DescriptionCall mxCalcSingleSubscript to determine how many elements there are between thebeginning of the mxArray and a given element of that mxArray The function convertssubscripts to linear indices

For example given a subscript like (57) mxCalcSingleSubscript returns thedistance from the first element of the array to the (57) element Remember that themxArray data type internally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have For examplesshowing the internal representation see ldquoData Storagerdquo

Avoid using mxCalcSingleSubscript to traverse the elements of an array In C it ismore efficient to find the starting address of the array and then use pointerautoincrementing to access successive elements For example to find the startingaddress of a numerical array call mxGetPr or mxGetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

1 API Reference

1-334

See AlsomxGetCell mxSetCell

Introduced before R2006a

mxCalcSingleSubscript (C and Fortran)

1-335

mxCalloc (C and Fortran)Allocate dynamic memory for array initialized to 0 using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxCalloc(mwSize n mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxCalloc(n size)mwSize n size

Argumentsn

Number of elements to allocate This must be a nonnegative numbersize

Number of bytes per element (The C sizeof operator calculates the number of bytesper element)

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxCalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxCalloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-336

DescriptionmxCalloc allocates contiguous heap space sufficient to hold n elements of size byteseach and initializes this newly allocated memory to 0 Use mxCalloc instead of theANSI C calloc function to allocate memory in MATLAB applications

In MEX files but not MAT or engine applications mxCalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatacbull phonebookcbull revordc

mxCalloc (C and Fortran)

1-337

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxsetdimensionsc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistentmxDestroyArray mxFree mxMalloc mxRealloc

Introduced before R2006a

1 API Reference

1-338

mxChar (C)Type for string array

DescriptionMATLAB stores an mxArray string as type mxChar to represent the C-style char typeMATLAB uses 16-bit unsigned integer character encoding for Unicode characters

The header file containing this type is

include matrixh

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxcreatecharmatrixfromstrc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCharArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

mxChar (C)

1-339

Introduced before R2006a

1 API Reference

1-340

mxClassID (C)Enumerated value identifying class of array

C Syntaxtypedef enum mxUNKNOWN_CLASS mxCELL_CLASS mxSTRUCT_CLASS mxLOGICAL_CLASS mxCHAR_CLASS mxVOID_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_CLASS

Undetermined class You cannot specify this category for an mxArray however ifmxGetClassID cannot identify the class it returns this value

mxCELL_CLASSIdentifies a cell mxArray

mxSTRUCT_CLASSIdentifies a structure mxArray

mxClassID (C)

1-341

mxLOGICAL_CLASSIdentifies a logical mxArray an mxArray of mxLogical data

mxCHAR_CLASSIdentifies a string mxArray an mxArray whose data is represented as mxChar

mxVOID_CLASSReserved

mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

1 API Reference

1-342

mxINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxFUNCTION_CLASSIdentifies a function handle mxArray

DescriptionVarious Matrix Library functions require or return an mxClassID argumentmxClassID identifies how the mxArray represents its data elements

The following table shows MATLAB types with their equivalent C types Use the typefrom the right-most column for reading mxArrays with the mxClassID value shown inthe left columnMATLAB Primitive Types

mxClassID Value MATLAB Type MEX Type C Primitive TypemxINT8_CLASS int8 int8_T char bytemxUINT8_CLASS uint8 uint8_T unsigned char bytemxINT16_CLASS int16 int16_T shortmxUINT16_CLASS uint16 uint16_T unsigned shortmxINT32_CLASS int32 int32_T intmxUINT32_CLASS uint32 uint32_T unsigned intmxINT64_CLASS int64 int64_T long longmxUINT64_CLASS uint64 uint64_T unsigned long longmxSINGLE_CLASS single float floatmxDOUBLE_CLASS double double double

mxClassID (C)

1-343

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetClassID mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-344

mxClassIDFromClassName (Fortran)Identifier corresponding to class

Fortran Syntaxinclude fintrfhinteger4 mxClassIDFromClassName(classname)character() classname

Argumentsclassname

character array specifying a MATLAB class name For a list of valid classnamechoices see the mxIsClass reference page

ReturnsNumeric identifier used internally by MATLAB software to represent the MATLAB classclassname Returns unknown if classname is not a recognized MATLAB class

DescriptionUse mxClassIDFromClassName to obtain an identifier for any MATLAB class Thisfunction is most commonly used to provide a classid argument tomxCreateNumericArray and mxCreateNumericMatrix

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matsqint8F

mxClassIDFromClassName (Fortran)

1-345

See AlsomxGetClassName mxCreateNumericArray mxCreateNumericMatrix mxIsClass

Introduced before R2006a

1 API Reference

1-346

mxComplexity (C)Flag specifying whether array has imaginary components

C Syntaxtypedef enum mxComplexity mxREAL=0 mxCOMPLEX

ConstantsmxREAL

Identifies an mxArray with no imaginary componentsmxCOMPLEX

Identifies an mxArray with imaginary components

DescriptionVarious Matrix Library functions require an mxComplexity argument You can set anmxComplex argument to either mxREAL or mxCOMPLEX

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

See AlsomxCreateNumericArray mxCreateDoubleMatrix mxCreateSparse

mxComplexity (C)

1-347

Introduced before R2006a

1 API Reference

1-348

mxCopyCharacterToPtr (Fortran)CHARACTER values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyCharacterToPtr(y px n)character() ymwPointer pxmwSize n

Argumentsy

character Fortran arraypx

Pointer to character or name arrayn

Number of elements to copy

DescriptionmxCopyCharacterToPtr copies n character values from the Fortran characterarray y into the MATLAB character vector pointed to by px This subroutine is essentialfor copying character data between MATLAB pointer arrays and ordinary Fortrancharacter arrays

See AlsomxCopyPtrToCharacter mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

mxCopyCharacterToPtr (Fortran)

1-349

Introduced before R2006a

1 API Reference

1-350

mxCopyComplex16ToPtr (Fortran)COMPLEX16 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex16ToPtr(y pr pi n)complex16 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX16 Fortran arraypr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex16ToPtr copies n COMPLEX16 values from the Fortran COMPLEX16array y into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex16ToPtr (Fortran)

1-351

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyPtrToComplex16 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-352

mxCopyComplex8ToPtr (Fortran)COMPLEX8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex8ToPtr(y pr pi n)complex8 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX8 Fortran arraypr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex8ToPtr copies n COMPLEX8 values from the Fortran COMPLEX8 arrayy into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex8ToPtr (Fortran)

1-353

See AlsomxCopyPtrToComplex8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-354

mxCopyInteger1ToPtr (Fortran)INTEGER1 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger1ToPtr(y px n)integer1 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER1 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger1ToPtr copies n INTEGER1 values from the Fortran INTEGER1 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyInteger1ToPtr (Fortran)

1-355

bull matsqint8F

See AlsomxCopyPtrToInteger1 mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-356

mxCopyInteger2ToPtr (Fortran)INTEGER2 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger2ToPtr(y px n)integer2 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER2 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger2ToPtr copies n INTEGER2 values from the Fortran INTEGER2 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger2 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger2ToPtr (Fortran)

1-357

Introduced before R2006a

1 API Reference

1-358

mxCopyInteger4ToPtr (Fortran)INTEGER4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger4ToPtr(y px n)integer4 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER4 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger4ToPtr copies n INTEGER4 values from the Fortran INTEGER4 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger4 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger4ToPtr (Fortran)

1-359

Introduced before R2006a

1 API Reference

1-360

mxCopyPtrToCharacter (Fortran)CHARACTER values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToCharacter(px y n)mwPointer pxcharacter() ymwSize n

Argumentspx

Pointer to character or name arrayy

character Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToCharacter copies n character values from the MATLAB array pointedto by px into the Fortran character array y This subroutine is essential for copyingcharacter data from MATLAB pointer arrays into ordinary Fortran character arrays

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxCopyPtrToCharacter (Fortran)

1-361

See AlsomxCopyCharacterToPtr mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

Introduced before R2006a

1 API Reference

1-362

mxCopyPtrToComplex16 (Fortran)COMPLEX16 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex16(pr pi y n)mwPointer pr picomplex16 y(n)mwSize n

Argumentspr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayy

COMPLEX16 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex16 copies n COMPLEX16 values from the MATLAB arrayspointed to by pr and pi into the Fortran COMPLEX16 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex16 (Fortran)

1-363

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyComplex16ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-364

mxCopyPtrToComplex8 (Fortran)COMPLEX8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex8(pr pi y n)mwPointer pr picomplex8 y(n)mwSize n

Argumentspr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayy

COMPLEX8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex8 copies n COMPLEX8 values from the MATLAB arrays pointedto by pr and pi into the Fortran COMPLEX8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex8 (Fortran)

1-365

See AlsomxCopyComplex8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-366

mxCopyPtrToInteger1 (Fortran)INTEGER1 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger1(px y n)mwPointer pxinteger1 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER1 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger1 copies n INTEGER1 values from the MATLAB array pointed toby px either a real or imaginary array into the Fortran INTEGER1 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyPtrToInteger1 (Fortran)

1-367

bull matsqint8F

See AlsomxCopyInteger1ToPtr mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-368

mxCopyPtrToInteger2 (Fortran)INTEGER2 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger2(px y n)mwPointer pxinteger2 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER2 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger2 copies n INTEGER2 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER2 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger2ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger2 (Fortran)

1-369

Introduced before R2006a

1 API Reference

1-370

mxCopyPtrToInteger4 (Fortran)INTEGER4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger4(px y n)mwPointer pxinteger4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger4 copies n INTEGER4 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger4ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger4 (Fortran)

1-371

Introduced before R2006a

1 API Reference

1-372

mxCopyPtrToPtrArray (Fortran)Pointer values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToPtrArray(px y n)mwPointer pxmwPointer y(n)mwSize n

Argumentspx

Pointer to pointer arrayy

Fortran array of mwPointer valuesn

Number of pointers to copy

DescriptionmxCopyPtrToPtrArray copies n pointers from the MATLAB array pointed to by px intothe Fortran array y This subroutine is essential for copying the output of matGetDirinto an array of pointers After calling this function each element of y contains a pointerto a string You can convert these strings to Fortran character arrays by passing eachelement of y as the first argument to mxCopyPtrToCharacter

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToPtrArray (Fortran)

1-373

bull matdemo2F

See AlsomatGetDir mxCopyPtrToCharacter

Introduced before R2006a

1 API Reference

1-374

mxCopyPtrToReal4 (Fortran)REAL4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal4(px y n)mwPointer pxreal4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a single-precision MATLAB arrayy

REAL4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal4 copies n REAL4 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToReal4 (Fortran)

1-375

See AlsomxCopyReal4ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-376

mxCopyPtrToReal8 (Fortran)REAL8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal8(px y n)mwPointer pxreal8 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a double-precision MATLAB arrayy

REAL8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal8 copies n REAL8 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToReal8 (Fortran)

1-377

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyReal8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-378

mxCopyReal4ToPtr (Fortran)REAL4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal4ToPtr(y px n)real4 y(n)mwPointer pxmwSize n

Argumentsy

REAL4 Fortran arraypx

Pointer to the real or imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal4ToPtr copies n REAL4 values from the Fortran REAL4 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyReal4ToPtr (Fortran)

1-379

See AlsomxCopyPtrToReal4 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-380

mxCopyReal8ToPtr (Fortran)REAL8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal8ToPtr(y px n)real8 y(n)mwPointer pxmwSize n

Argumentsy

REAL8 Fortran arraypx

Pointer to the real or imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal8ToPtr copies n REAL8 values from the Fortran REAL8 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyReal8ToPtr (Fortran)

1-381

bull matdemo1F

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyPtrToReal8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-382

mxCreateCellArray (C and Fortran)N-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the created cell For example to create a three-dimensionalcell mxArray set ndim to 3

dimsDimensions array Each element in the dimensions array contains the size of themxArray in that dimension For example in C setting dims[0] to 5 and dims[1] to7 establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellArray (C and Fortran)

1-383

DescriptionUse mxCreateCellArray to create a cell mxArray with size defined by ndim and dimsFor example in C to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims[0] = 4 dims[1] = 8 dims[2] = 7

In Fortran to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims(1) = 4 dims(2) = 8 dims(3) = 7

The created cell mxArray is unpopulated mxCreateCellArray initializes each cell toNULL To put data into a cell call mxSetCell

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateCellMatrix mxGetCell mxSetCell mxIsCell

Introduced before R2006a

1 API Reference

1-384

mxCreateCellMatrix (C and Fortran)2-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellMatrix(mwSize m mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellMatrix(m n)mwSize m n

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellMatrix (C and Fortran)

1-385

DescriptionUse mxCreateCellMatrix to create an m-by-n two-dimensional cell mxArray Thecreated cell mxArray is unpopulated mxCreateCellMatrix initializes each cell to NULLin C (0 in Fortran) To put data into cells call mxSetCell

mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only butmxCreateCellArray can create mxArrays having any number of dimensions greaterthan 1

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray

Introduced before R2006a

1 API Reference

1-386

mxCreateCharArray (C and Fortran)N-D mxChar array

C Syntaxinclude matrixhmxArray mxCreateCharArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the mxArray specified as a positive number If you specify0 1 or 2 mxCreateCharArray creates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray The dims array must have at least ndimelements

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateCharArray (C and Fortran)

1-387

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateCharArray to create an N-dimensional mxChar array The createdmxArray is unpopulated that is mxCreateCharArray initializes each cell to NULL in C(0 in Fortran)

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateCharMatrixFromStrings mxCreateString

1 API Reference

1-388

mxCreateCharMatrixFromStrings (C and Fortran)2-D mxChar array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateCharMatrixFromStrings(mwSize m const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharMatrixFromStrings(m str)mwSize mcharacter() str(m)

Argumentsm

Number of rows in the mxArray The value you specify for m is the number of stringsin str

strIn C an array of strings containing at least m strings In Fortran a characternarray of size m where each element of the array is n bytes

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray Another possible reasonfor failure is that str contains fewer than m strings

mxCreateCharMatrixFromStrings (C and Fortran)

1-389

DescriptionUse mxCreateCharMatrixFromStrings to create a two-dimensional mxArray whereeach row is initialized to a string from str In C the created mxArray has dimensions m-by-max where max is the length of the longest string in str In Fortran the createdmxArray has dimensions m-by-n where n is the number of characters in str(i)

The mxArray represents its data elements as mxChar rather than as C char

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxCreateCharArray mxCreateString mxGetString

Introduced before R2006a

1 API Reference

1-390

mxCreateDoubleMatrix (C and Fortran)2-D double-precision floating-point array

C Syntaxinclude matrixhmxArray mxCreateDoubleMatrix(mwSize m mwSize n mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleMatrix(m n ComplexFlag)mwSize m ninteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsComplexFlag

If the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateDoubleMatrix (C and Fortran)

1-391

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateDoubleMatrix to create an m-by-n mxArray mxCreateDoubleMatrixinitializes each element in the pr array to 0 If you set ComplexFlag to mxCOMPLEX in C(1 in Fortran) mxCreateDoubleMatrix also initializes each element in the pi array to0

If you set ComplexFlag to mxREAL in C (0 in Fortran) mxCreateDoubleMatrixallocates enough memory to hold m-by-n real elements If you set ComplexFlag tomxCOMPLEX in C (1 in Fortran) mxCreateDoubleMatrix allocates enough memory tohold m-by-n real elements and m-by-n imaginary elements

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its associated real and complex elements

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull matrixDividecbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull matsqF

1 API Reference

1-392

bull timestwoFbull xtimesyF

See AlsomxCreateNumericArray

Introduced before R2006a

mxCreateDoubleMatrix (C and Fortran)

1-393

mxCreateDoubleScalar (C and Fortran)Scalar double-precision array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateDoubleScalar(double value)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleScalar(value)real8 value

Argumentsvalue

Value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateDoubleScalar to create a scalar double mxArray When you finish usingthe mxArray call mxDestroyArray to destroy it

1 API Reference

1-394

See AlsomxGetPr mxCreateDoubleMatrix

Alternatives

C Language

In C you can replace the statements

pa = mxCreateDoubleMatrix(1 1 mxREAL)mxGetPr(pa) = value

with a call to mxCreateDoubleScalar

pa = mxCreateDoubleScalar(value)

Fortran Language

In Fortran you can replace the statements

pm = mxCreateDoubleMatrix(1 1 0)mxCopyReal8ToPtr(value mxGetPr(pm) 1)

with a call to mxCreateDoubleScalar

pm = mxCreateDoubleScalar(value)

Introduced before R2006a

mxCreateDoubleScalar (C and Fortran)

1-395

mxCreateLogicalArray (C)N-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalArray(mwSize ndim const mwSize dims)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateLogicalArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray There are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalArray to create an N-dimensional mxArray of mxLogicalelements After creating the mxArray mxCreateLogicalArray initializes all itselements to logical 0 mxCreateLogicalArray differs from mxCreateLogicalMatrixin that the latter can create two-dimensional arrays only

1 API Reference

1-396

mxCreateLogicalArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateLogicalMatrix mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalArray (C)

1-397

mxCreateLogicalMatrix (C)2-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalMatrix(mwSize m mwSize n)

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateLogicalMatrix to create an m-by-n mxArray of mxLogical elementsmxCreateLogicalMatrix initializes each element in the array to logical 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray

1 API Reference

1-398

See AlsomxCreateLogicalArray mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalMatrix (C)

1-399

mxCreateLogicalScalar (C)Scalar logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalScalar(mxLogical value)

Argumentsvalue

Logical value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalScalar to create a scalar logical mxArraymxCreateLogicalScalar is a convenience function that replaces the following code

pa = mxCreateLogicalMatrix(1 1)mxGetLogicals(pa) = value

When you finish using the mxArray call mxDestroyArray to destroy it

1 API Reference

1-400

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxIsLogicalScalarmxIsLogicalScalarTrue mxGetLogicals mxDestroyArray

Introduced before R2006a

mxCreateLogicalScalar (C)

1-401

mxCreateNumericArray (C and Fortran)N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateNumericArray(mwSize ndim const mwSize dims mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericArray(ndim dims classid ComplexFlag)mwSize ndimmwSize dims(ndim)integer4 classid ComplexFlag

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classid

1 API Reference

1-402

value from a MATLAB class name See the Description on page 1-403 section formore information

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericArray to create an N-dimensional mxArray in which all dataelements have the numeric data type specified by classid After creating the mxArraymxCreateNumericArray initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericArray also initializes all itsimaginary data elements to 0 mxCreateNumericArray differs frommxCreateDoubleMatrix as follows

bull All data elements in mxCreateDoubleMatrix are double-precision floating-pointnumbers The data elements in mxCreateNumericArray can be any numerical typeincluding different integer precisions

bull mxCreateDoubleMatrix can create two-dimensional arrays onlymxCreateNumericArray can create arrays of two or more dimensions

mxCreateNumericArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

mxCreateNumericArray (C and Fortran)

1-403

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull doubleelementcbull matrixDividecbull matsqint8F

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-404

Introduced before R2006a

mxCreateNumericArray (C and Fortran)

1-405

mxCreateNumericMatrix (C and Fortran)2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateNumericMatrix(mwSize m mwSize n mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericMatrix(m n classid ComplexFlag)mwSize m ninteger4 classid ComplexFlag

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classidvalue from a MATLAB class name

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

1 API Reference

1-406

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which all data elements havethe numeric data type specified by classid After creating the mxArraymxCreateNumericMatrix initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericMatrix also initializes all itsimaginary data elements to 0 mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray When you finish using the mxArray call mxDestroyArrayto destroy it

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

mxCreateNumericMatrix (C and Fortran)

1-407

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrc

The following Fortran statements create a 4-by-3 matrix of REAL4 elements having noimaginary components

C Create 4x3 mxArray of REAL4 mxCreateNumericMatrix(4 3 + mxClassIDFromClassName(single) 0)

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericMatrix mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-408

mxCreateSparse (C and Fortran)2-D sparse array

C Syntaxinclude matrixhmxArray mxCreateSparse(mwSize m mwSize n mwSize nzmax mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateSparse(m n nzmax ComplexFlag)mwSize m n nzmaxinteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparse should allocate to hold the pr ir and ifComplexFlag is mxCOMPLEX in C (1 in Fortran) pi arrays Set the value of nzmax tobe greater than or equal to the number of nonzero elements you plan to put into themxArray but make sure that nzmax is less than or equal to mn nzmax is greaterthan or equal to 1

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

mxCreateSparse (C and Fortran)

1-409

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray In that case tryreducing nzmax m or n

DescriptionCall mxCreateSparse to create an unpopulated sparse double mxArray The returnedsparse mxArray contains no sparse information and cannot be passed as an argument toany MATLAB sparse functions To make the returned sparse mxArray useful initializethe pr ir jc and (if it exists) pi arrays

mxCreateSparse allocates space for

bull A pr array of length nzmaxbull A pi array of length nzmax but only if ComplexFlag is mxCOMPLEX in C (1 in

Fortran)bull An ir array of length nzmaxbull A jc array of length n+1

When you finish using the sparse mxArray call mxDestroyArray to reclaim all its heapspace

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

1 API Reference

1-410

See AlsomxDestroyArray mxSetNzmax mxSetPr mxSetPi mxSetIr mxSetJcmxComplexity

Introduced before R2006a

mxCreateSparse (C and Fortran)

1-411

mxCreateSparseLogicalMatrix (C)2-D sparse logical array

C Syntaxinclude matrixhmxArray mxCreateSparseLogicalMatrix(mwSize m mwSize n mwSize nzmax)

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparseLogicalMatrix should allocate to holdthe data Set the value of nzmax to be greater than or equal to the number of nonzeroelements you plan to put into the mxArray but make sure that nzmax is less than orequal to mn nzmax is greater than or equal to 1

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

1 API Reference

1-412

DescriptionUse mxCreateSparseLogicalMatrix to create an m-by-n mxArray of mxLogicalelements mxCreateSparseLogicalMatrix initializes each element in the array tological 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its elements

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxCreateSparse mxIsLogical

Introduced before R2006a

mxCreateSparseLogicalMatrix (C)

1-413

mxCreateString (C and Fortran)1-N array initialized to specified string

C Syntaxinclude matrixhmxArray mxCreateString(const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateString(str)character() str

Argumentsstr

String used to initialize mxArray data Only ASCII characters are supported

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateString to create an mxArray initialized to str Many MATLAB functions(for example strcmp and upper) require string array inputs

1 API Reference

1-414

mxCreateString supports both multi-byte and single-byte encoded characters OnWindows and Linux platforms the default encoding is specified by the user localesetting

Free the mxArray when you are finished using it by calling mxDestroyArray

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull revordcbull revordF

See the following examples in matlabrootexternexamplesmx

bull mxcreatestructarraycbull mxisclassc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxCreateCharMatrixFromStrings mxCreateCharArray

Introduced before R2006a

mxCreateString (C and Fortran)

1-415

mxCreateStructArray (C and Fortran)N-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructArray(mwSize ndim const mwSize dims int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructArray(ndim dims nfields fieldnames)mwSize ndimmwSize dims(ndim)integer4 nfieldscharacter() fieldnames(nfields)

Argumentsndim

Number of dimensions If you set ndim to be less than 2 mxCreateStructArraycreates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Typically the dims array should have ndim elements

nfieldsNumber of fields in each element Positive integer

fieldnamesList of field names Field names must be valid MATLAB identifiers which meansthey cannot be NULL or empty

1 API Reference

1-416

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateStructArray to create an unpopulated structure mxArray Each elementof a structure mxArray contains the same number of fields (specified in nfields) Eachfield has a name the list of names is specified in fieldnames A MATLAB structuremxArray is conceptually identical to an array of structs in the C language

Each field holds one mxArray pointer mxCreateStructArray initializes each field toNULL in C (0 in Fortran) Call mxSetField or mxSetFieldByNumber to place a non-NULL mxArray pointer in a field

When you finish using the returned structure mxArray call mxDestroyArray to reclaimits space

Any trailing singleton dimensions specified in the dims argument are automaticallyremoved from the resulting array For example if ndim equals 5 and dims equals [4 17 1 1] the resulting array is given the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

mxCreateStructArray (C and Fortran)

1-417

See AlsomxDestroyArray mxAddField mxRemoveField mxSetFieldmxSetFieldByNumber namelengthmax

Introduced before R2006a

1 API Reference

1-418

mxCreateStructMatrix (C and Fortran)2-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructMatrix(mwSize m mwSize n int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructMatrix(m n nfields fieldnames)mwSize m ninteger4 nfieldscharacter() fieldnames(nfields)

Argumentsm

Number of rows must be a positive integern

Number of columns must be a positive integernfields

Number of fields in each elementfieldnames

List of field names

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

mxCreateStructMatrix (C and Fortran)

1-419

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxCreateStructMatrix and mxCreateStructArray are almost identical The onlydifference is that mxCreateStructMatrix can create only two-dimensional mxArrayswhile mxCreateStructArray can create an mxArray having two or more dimensions

C ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray namelengthmax

Introduced before R2006a

1 API Reference

1-420

mxCreateUninitNumericArray (C)Uninitialized N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateUninitNumericArray(size_t ndim size_t dims mxClassID classid mxComplexity ComplexFlag)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateUninitNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericArray (C)

1-421

DescriptionCall mxCreateUninitNumericArray to create an N-dimensional mxArray in which alldata elements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericArray allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericMatrix mxCreateNumericArray

Introduced in R2015a

1 API Reference

1-422

mxCreateUninitNumericMatrix (C)Uninitialized 2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateUninitNumericMatrix(size_t m size_t n mxClassID classid mxComplexity ComplexFlag)

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericMatrix (C)

1-423

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreateuninitnumericmatrixc

DescriptionCall mxCreateUninitNumericMatrix to create a 2-D mxArray in which all dataelements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericMatrix allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-424

Introduced in R2015a

mxCreateUninitNumericMatrix (C)

1-425

mxDestroyArray (C and Fortran)Free dynamic memory allocated by MXCREATE functions

C Syntaxinclude matrixhvoid mxDestroyArray(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mxDestroyArray(pm)mwPointer pm

Argumentspm

Pointer to the mxArray to free If pm is a NULL pointer the function does nothing

DescriptionmxDestroyArray deallocates the memory occupied by the specified mxArray including

bull Characteristics fields of the mxArray such as size (m and n) and typebull Associated data arrays such as pr and pi for complex arrays and ir and jc for

sparse arraysbull Fields of structure arraysbull Cells of cell arrays

Do not call mxDestroyArray on an mxArray

bull returned in a left-side argument of a MEX file

1 API Reference

1-426

bull returned by the mxGetField or mxGetFieldByNumber functionsbull returned by the mxGetCell function

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexgetarrayc

See the following examples in matlabrootexternexamplesmx

bull mxisclasscbull mxcreatecellmatrixfF

See AlsomxCalloc mxMalloc mxFree mexMakeArrayPersistentmexMakeMemoryPersistent

Introduced before R2006a

mxDestroyArray (C and Fortran)

1-427

mxDuplicateArray (C and Fortran)Make deep copy of array

C Syntaxinclude matrixhmxArray mxDuplicateArray(const mxArray in)

Fortran Syntaxinclude fintrfhmwPointer mxDuplicateArray(in)mwPointer in

Argumentsin

Pointer to the mxArray you want to copy

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxDuplicateArray makes a deep copy of an array and returns a pointer to the copy Adeep copy refers to a copy in which all levels of data are copied For example a deep copyof a cell array copies each cell and the contents of each cell (if any)

1 API Reference

1-428

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxgetinfcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

Introduced before R2006a

mxDuplicateArray (C and Fortran)

1-429

mxFree (C and Fortran)Free dynamic memory allocated by mxCalloc mxMalloc mxRealloc mxArrayToString ormxArrayToUTF8String functions

C Syntaxinclude matrixhvoid mxFree(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mxFree(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of any memory parcel allocated by mxCalloc mxMalloc ormxRealloc If ptr is a NULL pointer the function does nothing

DescriptionmxFree deallocates heap space using the MATLAB memory management facility Thisfunction ensures correct memory management in error and abort (Ctrl+C) conditions

To deallocate heap space MATLAB applications in C should always call mxFree ratherthan the ANSI C free function

In MEX files but excluding MAT or engine standalone applications the MATLABmemory management facility maintains a list of all memory allocated by the followingfunctions

1 API Reference

1-430

bull mxCallocbull mxMallocbull mxReallocbull mxArrayToStringbull mxArrayToUTF8String

The memory management facility automatically deallocates all parcels managed by aMEX file when the MEX file completes and control returns to the MATLAB promptmxFree also removes the memory parcel from the memory management list of parcels

When mxFree appears in a MAT or engine standalone MATLAB application it simplydeallocates the contiguous heap space that begins at address ptr

In MEX files your use of mxFree depends on whether the specified memory parcel ispersistent or nonpersistent By default memory parcels created by mxCallocmxMalloc mxRealloc mxArrayToString and mxArrayToUTF8String arenonpersistent The memory management facility automatically frees all nonpersistentmemory whenever a MEX file completes Thus even if you do not call mxFree MATLABtakes care of freeing the memory for you Nevertheless it is good programming practiceto deallocate memory when you are through using it Doing so generally makes the entiresystem run more efficiently

If an application calls mexMakeMemoryPersistent the specified memory parcelbecomes persistent When a MEX file completes the memory management facility doesnot free persistent memory parcels Therefore the only way to free a persistent memoryparcel is to call mxFree Typically MEX files call mexAtExit to register a cleanuphandler The cleanup handler calls mxFree

Do not use mxFree for an mxArray created by any other functions in the Matrix LibraryAPI Use mxDestroyArray instead

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxcreatecharmatrixfromstrc

mxFree (C and Fortran)

1-431

bull mxisfinitecbull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxMalloc mxRealloc mxArrayToString mxArrayToUTF8String

Introduced before R2006a

1 API Reference

1-432

mxGetCell (C and Fortran)Pointer to element in cell array

C Syntaxinclude matrixhmxArray mxGetCell(const mxArray pm mwIndex index)

Fortran Syntaxinclude fintrfhmwPointer mxGetCell(pm index)mwPointer pmmwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Number of elements in the cell mxArray between the first element and the desiredone See mxCalcSingleSubscript for details on calculating an index in amultidimensional cell array

ReturnsPointer to the ith cell mxArray if successful Otherwise returns NULL in C (0 inFortran) Causes of failure include

bull Specifying the index of a cell array element that has not been populatedbull Specifying a pm that does not point to a cell mxArray

mxGetCell (C and Fortran)

1-433

bull Specifying an index to an element outside the bounds of the mxArraybull Insufficient heap space

Do not call mxDestroyArray on an mxArray returned by the mxGetCell function

DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexed element of the cellmxArray

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCellArray mxIsCell mxSetCell

Introduced before R2006a

1 API Reference

1-434

mxGetChars (C)Pointer to character array data

C Syntaxinclude matrixhmxChar mxGetChars(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first character in the mxArray Returns NULL if the specified array is not acharacter array

DescriptionCall mxGetChars to access the first character in the mxArray that array_ptr points toOnce you have the starting address you can access any other element in the mxArray

See AlsomxGetString

Introduced before R2006a

mxGetChars (C)

1-435

mxGetClassID (C and Fortran)Class of array

C Syntaxinclude matrixhmxClassID mxGetClassID(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetClassID(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumeric identifier of the class (category) of the mxArray that pm points to For a list ofC-language class identifiers see the mxClassID reference page For user-defined typesmxGetClassId returns a unique value identifying the class of the array contents UsemxIsClass to determine whether an array is of a specific user-defined type

DescriptionUse mxGetClassId to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray then mxGetClassId returns mxLOGICAL_CLASS (in C)

1 API Reference

1-436

mxGetClassId is like mxGetClassName except that the former returns the class as aninteger identifier and the latter returns the class as a string

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxClassID mxGetClassName mxIsClass

Introduced before R2006a

mxGetClassID (C and Fortran)

1-437

mxGetClassName (C and Fortran)Class of array as string

Note Use mxGetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhconst char mxGetClassName(const mxArray pm)

Fortran Syntaxinclude fintrfhcharacter() mxGetClassName(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsClass (as a string) of the mxArray pointed to by pm

DescriptionCall mxGetClassName to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray mxGetClassName returns logical

1 API Reference

1-438

mxGetClassID is like mxGetClassName except that the former returns the class as aninteger identifier as listed in the mxClassID reference page and the latter returns theclass as a string as listed in the mxIsClass reference page

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxGetClassID mxIsClass

Introduced before R2006a

mxGetClassName (C and Fortran)

1-439

mxGetData (C and Fortran)Pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxGetData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionIn C mxGetData returns a void pointer (void ) Since void pointers point to a valuethat has no type cast the return value to the pointer type that matches the type specifiedby pm To see how MATLAB types map to their equivalent C types see the table on themxClassID reference page

1 API Reference

1-440

In Fortran to copy values from the returned pointer use one of the mxCopyPtrTofunctions in the following manner

C Get the data in mxArray pm mxCopyPtrToReal8(mxGetData(pm)data + mxGetNumberOfElements(pm))

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxisfinitec

See AlsomxGetImagData mxGetPr mxClassID

Introduced before R2006a

mxGetData (C and Fortran)

1-441

mxGetDimensions (C and Fortran)Pointer to dimensions array

C Syntaxinclude matrixhconst mwSize mxGetDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element in the dimensions array Each integer in the dimensionsarray represents the number of elements in a particular dimension The array is notNULL terminated

DescriptionUse mxGetDimensions to determine how many elements are in each dimension of themxArray that pm points to Call mxGetNumberOfDimensions to get the number ofdimensions in the mxArray

To copy the values to Fortran use mxCopyPtrToInteger4 in the following manner

1 API Reference

1-442

C Get dimensions of mxArray pm mxCopyPtrToInteger4(mxGetDimensions(pm) dims + mxGetNumberOfDimensions(pm))

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetNumberOfDimensions

Introduced before R2006a

mxGetDimensions (C and Fortran)

1-443

mxGetElementSize (C and Fortran)Number of bytes required to store each data element

C Syntaxinclude matrixhsize_t mxGetElementSize(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetElementSize(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of bytes required to store one element of the specified mxArray if successfulReturns 0 on failure The primary reason for failure is that pm points to an mxArrayhaving an unrecognized class If pm points to a cell mxArray or a structure mxArraymxGetElementSize returns the size of a pointer (not the size of all the elements in eachcell or structure field)

DescriptionCall mxGetElementSize to determine the number of bytes in each data element of themxArray For example if the MATLAB class of an mxArray is int16 the mxArray

1 API Reference

1-444

stores each data element as a 16-bit (2-byte) signed integer Thus mxGetElementSizereturns 2

mxGetElementSize is helpful when using a non-MATLAB routine to manipulate dataelements For example the C function memcpy requires (for its third argument) the sizeof the elements you intend to copy

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull doubleelementcbull phonebookc

See AlsomxGetM mxGetN

Introduced before R2006a

mxGetElementSize (C and Fortran)

1-445

mxGetEps (C and Fortran)Value of EPS

C Syntaxinclude matrixhdouble mxGetEps(void)

Fortran Syntaxreal8 mxGetEps

ReturnsValue of the MATLAB eps variable

DescriptionCall mxGetEps to return the value of the MATLAB eps variable This variable holds thedistance from 10 to the next largest floating-point number As such it is a measure offloating-point accuracy The MATLAB pinv and rank functions use eps as a defaulttolerance

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

1 API Reference

1-446

See AlsomxGetInf mxGetNan

Introduced before R2006a

mxGetEps (C and Fortran)

1-447

mxGetField (C and Fortran)Pointer to field value from structure array given index and field name

C Syntaxinclude matrixhmxArray mxGetField(const mxArray pm mwIndex index const char fieldname)

Fortran Syntaxinclude fintrfhmwPointer mxGetField(pm index fieldname)mwPointer pmmwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

fieldnameName of the field whose value you want to extract

1 API Reference

1-448

ReturnsPointer to the mxArray in the specified field at the specified fieldname on successReturns NULL in C (0 in Fortran) if passed an invalid argument or if there is no valueassigned to the specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray Todetermine whether pm points to a structure mxArray call mxIsStruct

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains 10 elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent fieldname Call mxGetFieldNameByNumber ormxGetFieldNumber to get existing field names

bull Insufficient heap space

DescriptionCall mxGetField to get the value held in the specified element of the specified field Inpseudo-C terminology mxGetField returns the value at

pm[index]fieldname

mxGetFieldByNumber is like mxGetField Both functions return the same value Theonly difference is in the way you specify the field mxGetFieldByNumber takes a fieldnumber as its third argument and mxGetField takes a field name as its thirdargument

Do not call mxDestroyArray on an mxArray returned by the mxGetField function

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

mxGetField(pa index field_name)

mxGetField (C and Fortran)

1-449

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where if you have a 1-by-1 structure index is 0

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where if you have a 1-by-1 structure index is 1

ExamplesSee the following example in matlabrootexternexampleseng_mat

bull matreadstructarrayc

See AlsomxGetFieldByNumber mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-450

mxGetFieldByNumber (C and Fortran)Pointer to field value from structure array given index and field number

C Syntaxinclude matrixhmxArray mxGetFieldByNumber(const mxArray pm mwIndex index int fieldnumber)

Fortran Syntaxinclude fintrfhmwPointer mxGetFieldByNumber(pm index fieldnumber)mwPointer pmmwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for more details on calculating an indexfieldnumber

Position of the field whose value you want to extract

mxGetFieldByNumber (C and Fortran)

1-451

In C the first field within each element has a field number of 0 the second field hasa field number of 1 and so on The last field has a field number of N-1 where N is thenumber of fields

In Fortran the first 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 field number of N whereN is the number of fields

ReturnsPointer to the mxArray in the specified field for the desired element on success ReturnsNULL in C (0 in Fortran) if passed an invalid argument or if there is no value assigned tothe specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains ten elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent field number Call mxGetFieldNumber to determine thefield number that corresponds to a given field name

DescriptionCall mxGetFieldByNumber to get the value held in the specified fieldnumber at theindexed element

Do not call mxDestroyArray on an mxArray returned by the mxGetFieldByNumberfunction

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

1 API Reference

1-452

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldByNumber (C and Fortran)

1-453

mxGetFieldNameByNumber (C and Fortran)Pointer to field name from structure array given field number

C Syntaxinclude matrixhconst char mxGetFieldNameByNumber(const mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhcharacter() mxGetFieldNameByNumber(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Position of the desired field For instance in C to get the name of the first field setfieldnumber to 0 to get the name of the second field set fieldnumber to 1 and soon In Fortran to get the name of the first field set fieldnumber to 1 to get thename of the second field set fieldnumber to 2 and so on

ReturnsPointer to the nth field name on success Returns NULL in C (0 in Fortran) on failureCommon causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

1 API Reference

1-454

bull Specifying a value of fieldnumber outside the bounds of the number of fields in thestructure mxArray In C fieldnumber 0 represents the first field andfieldnumber N-1 represents the last field where N is the number of fields in thestructure mxArray In Fortran fieldnumber 1 represents the first field andfieldnumber N represents the last field

DescriptionCall mxGetFieldNameByNumber to get the name of a field in the given structuremxArray A typical use of mxGetFieldNameByNumber is to call it inside a loop to get thenames of all the fields in a given mxArray

Consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test A field number other than 0 1 or 2causes mxGetFieldNameByNumber to return NULL

In Fortran the field number 1 represents the field name field number 2 represents fieldbilling field number 3 represents field test A field number other than 1 2 or 3causes mxGetFieldNameByNumber to return 0

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

mxGetFieldNameByNumber (C and Fortran)

1-455

bull explorec

See AlsomxGetField mxGetFieldByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-456

mxGetFieldNumber (C and Fortran)Field number from structure array given field name

C Syntaxinclude matrixhint mxGetFieldNumber(const mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxGetFieldNumber(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of a field in the structure mxArray

ReturnsField number of the specified fieldname on success In C the first field has a fieldnumber of 0 the second field has a field number of 1 and so on In Fortran the first fieldhas a field number of 1 the second field has a field number of 2 and so on Returns -1 inC (0 in Fortran) on failure Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

mxGetFieldNumber (C and Fortran)

1-457

bull 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 do not know its fieldname call mxGetFieldNameByNumber

For example consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field name has a field number of 0 the field billing has a field number of 1and the field test has a field number of 2 If you call mxGetFieldNumber and specify afield name of anything other than name billing or test mxGetFieldNumber returns-1

Calling

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran the field name has a field number of 1 the field billing has a field numberof 2 and the field test has a field number of 3 If you call mxGetFieldNumber andspecify a field name of anything other than name billing or testmxGetFieldNumber returns 0

Calling

mxGetField(pm index fieldname)

is equivalent to calling

1 API Reference

1-458

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxGetField mxGetFieldByNumber mxGetFieldNameByNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldNumber (C and Fortran)

1-459

mxGetImagData (C and Fortran)Pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxGetImagData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetImagData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the imaginary data Returns NULL in C (0 in Fortran) ifthere is no imaginary data or if there is an error

DescriptionThis function is like mxGetPi except that in C it returns a void For moreinformation see the description for the mxGetData function

1 API Reference

1-460

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxGetData mxGetPi

Introduced before R2006a

mxGetImagData (C and Fortran)

1-461

mxGetInf (C and Fortran)Value of infinity

C Syntaxinclude matrixhdouble mxGetInf(void)

Fortran Syntaxreal8 mxGetInf

ReturnsValue of infinity on your system

DescriptionCall mxGetInf to return the value of the MATLAB internal inf variable inf is apermanent variable representing IEEEreg arithmetic positive infinity Your systemspecifies the value of inf you cannot modify it

Operations that return infinity include

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-462

bull mxgetinfc

See AlsomxGetEps mxGetNaN

Introduced before R2006a

mxGetInf (C and Fortran)

1-463

mxGetIr (C and Fortran)Sparse matrix IR array

C Syntaxinclude matrixhmwIndex mxGetIr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetIr(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the ir array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetIr to obtain the starting address of the ir array The ir array is an array ofintegers The length of ir is nzmax the storage allocated for the sparse array or nnz

1 API Reference

1-464

the number of nonzero matrix elements For example if nzmax equals 100 the ir arraycontains 100 integers

Each value in an ir array indicates a row (offset by 1) at which a nonzero element can befound (The jc array is an index that indirectly specifies a column where nonzeroelements can be found)

For details on the ir and jc arrays see mxSetIr and mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetJc mxGetNzmax mxSetIr mxSetJc mxSetNzmax nzmax nnz

Introduced before R2006a

mxGetIr (C and Fortran)

1-465

mxGetJc (C and Fortran)Sparse matrix JC array

C Syntaxinclude matrixhmwIndex mxGetJc(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetJc(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the jc array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetJc to obtain the starting address of the jc array The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

1 API Reference

1-466

The values in the jc array indirectly indicate columns containing nonzero elements Fora detailed explanation of the jc array see mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetIr mxGetNzmax mxSetIr mxSetJc mxSetNzmax

Introduced before R2006a

mxGetJc (C and Fortran)

1-467

mxGetLogicals (C)Pointer to logical array data

C Syntaxinclude matrixhmxLogical mxGetLogicals(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first logical element in the mxArray The result is unspecified if themxArray is not a logical array

DescriptionCall mxGetLogicals to access the first logical element in the mxArray that array_ptrpoints to Once you have the starting address you can access any other element in themxArray

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxIsLogical mxIsLogicalScalar mxIsLogicalScalarTrue

Introduced before R2006a

1 API Reference

1-468

mxGetM (C and Fortran)Number of rows in array

C Syntaxinclude matrixhsize_t mxGetM(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetM(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of rows in the mxArray to which pm points

DescriptionmxGetM returns the number of rows in the specified array The term rows always meansthe first dimension of the array no matter how many dimensions the array has Forexample if pm points to a four-dimensional array having dimensions 8-by-9-by-5-by-3mxGetM returns 8

mxGetM (C and Fortran)

1-469

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull matrixDividecbull matrixDivideComplexcbull revordcbull timestwocbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull timestwoFbull xtimesyF

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-470

bull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomxGetN mxSetM mxSetN

Introduced before R2006a

mxGetM (C and Fortran)

1-471

mxGetN (C and Fortran)Number of columns in array

C Syntaxinclude matrixhsize_t mxGetN(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetN(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of columns in the mxArray

DescriptionCall mxGetN to determine the number of columns in the specified mxArray

If pm is an N-dimensional mxArray mxGetN is the product of dimensions 2 through NFor example if pm points to a four-dimensional mxArray having dimensions 13-by-5-by-4-by-6 mxGetN returns the value 120 (5 times 4 times 6) If the specified mxArray has morethan two dimensions and you need to know exactly how many elements are in eachdimension call mxGetDimensions

1 API Reference

1-472

If pm points to a sparse mxArray mxGetN still returns the number of columns not thenumber of occupied columns

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull revordcbull timestwocbull xtimesyc

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxGetN (C and Fortran)

1-473

See AlsomxGetM mxGetDimensions mxSetM mxSetN

Introduced before R2006a

1 API Reference

1-474

mxGetNaN (C and Fortran)Value of NaN (Not-a-Number)

C Syntaxinclude matrixhdouble mxGetNaN(void)

Fortran Syntaxreal8 mxGetNaN

ReturnsValue of NaN (Not-a-Number) on your system

DescriptionCall mxGetNaN to return the value of NaN for your system NaN is the IEEE arithmeticrepresentation for Not-a-Number Certain mathematical operations return NaN as aresult for example

bull 0000bull Inf-Inf

Your system specifies the value of Not-a-Number You cannot modify it

C ExamplesSee the following examples in matlabrootexternexamplesmx

mxGetNaN (C and Fortran)

1-475

bull mxgetinfc

See AlsomxGetEps mxGetInf

Introduced before R2006a

1 API Reference

1-476

mxGetNumberOfDimensions (C and Fortran)Number of dimensions in array

C Syntaxinclude matrixhmwSize mxGetNumberOfDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNumberOfDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of dimensions in the specified mxArray The returned value is always 2 orgreater

DescriptionUse mxGetNumberOfDimensions to determine how many dimensions are in thespecified array To determine how many elements are in each dimension callmxGetDimensions

mxGetNumberOfDimensions (C and Fortran)

1-477

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsecbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See AlsomxSetM mxSetN mxGetDimensions

Introduced before R2006a

1 API Reference

1-478

mxGetNumberOfElements (C and Fortran)Number of elements in array

C Syntaxinclude matrixhsize_t mxGetNumberOfElements(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetNumberOfElements(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of elements in the specified mxArray

DescriptionmxGetNumberOfElements tells you how many elements an array has For example ifthe dimensions of an array are 3-by-5-by-10 mxGetNumberOfElements returns thenumber 150

mxGetNumberOfElements (C and Fortran)

1-479

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxgetepsfFbull mxgetinfcbull mxisfinitecbull mxsetdimensionscbull mxsetdimensionsfF

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetDimensions mxGetM mxGetN mxGetClassID mxGetClassName

Introduced before R2006a

1 API Reference

1-480

mxGetNumberOfFields (C and Fortran)Number of fields in structure array

C Syntaxinclude matrixhint mxGetNumberOfFields(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetNumberOfFields(pm)mwPointer pm

Argumentspm

Pointer to a structure mxArray

ReturnsNumber of fields on success Returns 0 on failure The most common cause of failure isthat pm is not a structure mxArray Call mxIsStruct to determine whether pm is astructure

DescriptionCall mxGetNumberOfFields to determine how many fields are in the specified structuremxArray

Once you know the number of fields in a structure you can loop through every field to setor to get field values

mxGetNumberOfFields (C and Fortran)

1-481

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxIsStruct mxSetField

Introduced before R2006a

1 API Reference

1-482

mxGetNzmax (C and Fortran)Number of elements in IR PR and PI arrays

C Syntaxinclude matrixhmwSize mxGetNzmax(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNzmax(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsNumber of elements allocated to hold nonzero entries in the specified sparse mxArray onsuccess Returns an indeterminate value on error The most likely cause of failure is thatpm points to a full (nonsparse) mxArray

DescriptionUse mxGetNzmax to get the value of the nzmax field The nzmax field holds an integervalue that signifies the number of elements in the ir pr and if it exists the pi arraysThe value of nzmax is always greater than or equal to the number of nonzero elements ina sparse mxArray In addition the value of nzmax is always less than or equal to thenumber of rows times the number of columns

mxGetNzmax (C and Fortran)

1-483

As you adjust the number of nonzero elements in a sparse mxArray MATLAB softwareoften adjusts the value of the nzmax field MATLAB adjusts nzmax to reduce the numberof costly reallocations and to optimize its use of heap space

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetnzmaxc

See AlsomxSetNzmax

Introduced before R2006a

1 API Reference

1-484

mxGetPi (C and Fortran)Imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPi(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPi(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the imaginary data elements of the specified mxArray on success ReturnsNULL in C (0 in Fortran) if there is no imaginary data or if there is an error

DescriptionUse mxGetPi on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetImagData

The pi field points to an array containing the imaginary data of the mxArray CallmxGetPi to get the contents of the pi field that is to get the starting address of thisimaginary data

mxGetPi (C and Fortran)

1-485

The best way to determine whether an mxArray is purely real is to call mxIsComplex

If any of the input matrices to a function are complex MATLAB allocates the imaginaryparts of all input matrices

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull fulltosparsec

For Fortran examples see

bull convecF

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetinfcbull mxisfinitecbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexcallmatlabc

See AlsomxGetPr mxSetPi mxSetPr mxGetImagData mxIsDouble

Introduced before R2006a

1 API Reference

1-486

mxGetPr (C and Fortran)Real data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPr(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionUse mxGetPr on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetData

Call mxGetPr to access the real data in the mxArray that pm points to Once you havethe starting address you can access any other element in the mxArray

mxGetPr (C and Fortran)

1-487

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull arrayFillGetPrcbull conveccbull doubleelementcbull findnzcbull fulltosparsecbull matrixDividecbull matrixMultiplycbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull sincallFbull timestwoFbull xtimesyF

See AlsomxGetPi mxSetPi mxSetPr mxGetData mxIsDouble

Introduced before R2006a

1 API Reference

1-488

mxGetProperty (C and Fortran)Value of public property of MATLAB object

C Syntaxinclude matrixhmxArray mxGetProperty(const mxArray pa mwIndex index const char propname)

Fortran Syntaxinclude fintrfhmwPointer mxGetProperty(pa index propname)mwPointer pamwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you want to extract

mxGetProperty (C and Fortran)

1-489

ReturnsPointer to the mxArray of the specified propname on success Returns NULL in C (0 inFortran) if unsuccessful Common causes of failure include

bull Specifying a nonexistent propnamebull Specifying a nonpublic propnamebull Specifying an index to an element outside the bounds of the mxArray To test the

index value use mxGetNumberOfElements or mxGetM and mxGetNbull Insufficient heap space

DescriptionCall mxGetProperty to get the value held in the specified element In pseudo-Cterminology mxGetProperty returns the value at

pa[index]propname

mxGetProperty makes a copy of the value If the property uses a large amount ofmemory creating a copy might be a concern There must be sufficient memory (in theheap) to hold the copy of the value

Examples

Display Name Property of timeseries Object

Create a MEX file disppropertyc in a folder on your MATLAB path================================================================= disppropertyc - Display timeseries Name property This is a MEX file for MATLAB Copyright 2013 The MathWorks Inc All rights reserved ================================================================= include mexh

void mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

1 API Reference

1-490

Check for proper number of arguments if(nrhs=1) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidNumInputs One input required) else if(nlhsgt1) mexErrMsgIdAndTxt( MATLABdisppropertymaxlhs Too many output arguments) Check for timeseries object if (mxIsClass(prhs[0] timeseries)) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidClass Input must be timeseries object) plhs[0] = mxGetProperty(prhs[0]0Name)

Build the MEX file

mex(-vdisppropertyc)

Create a timeseries object

ts = timeseries(rand(5 4)NameLaunchData)

Display name

tsname = dispproperty(ts)

tsname =LaunchData

Change Object Color

Open and build the mexgetpropertyc MEX file in the matlabrootexternexamplesmex folder

Limitationsbull mxGetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

mxGetProperty (C and Fortran)

1-491

See AlsomxSetProperty mxGetNumberOfElements mxGetM mxGetN

Introduced in R2008a

1 API Reference

1-492

mxGetScalar (C and Fortran)Real component of first data element in array

C Syntaxinclude matrixhdouble mxGetScalar(const mxArray pm)

Fortran Syntaxinclude fintrfhreal8 mxGetScalar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray cannot be a cell mxArray a structure mxArray or an emptymxArray

ReturnsThe value of the first real (nonimaginary) element of the mxArray

In C mxGetScalar returns a double If real elements in the mxArray are of a typeother than double then mxGetScalar automatically converts the scalar value into adouble To preserve the original data representation of the scalar cast the return valueto the desired data type

If pm points to a sparse mxArray then mxGetScalar returns the value of the firstnonzero real element in the mxArray If there are no nonzero elements then the functionreturns 0

mxGetScalar (C and Fortran)

1-493

DescriptionCall mxGetScalar to get the value of the first real (nonimaginary) element of themxArray

Usually you call mxGetScalar when pm points to an mxArray containing only oneelement (a scalar) However pm can point to an mxArray containing many elements Ifpm points to an mxArray containing multiple elements then the function returns thevalue of the first real element For example if pm points to a two-dimensional mxArraythen mxGetScalar returns the value of the (11) element If pm points to a three-dimensional mxArray then the function returns the value of the (111) element andso on

Use mxGetScalar on a nonempty mxArray of type numeric logical or char only To testfor these conditions use Matrix Library functions such as mxIsEmpty mxIsLogicalmxIsNumeric or mxIsChar

If the input value to mxGetScalar is type int64 or uint64 then the value might loseprecision if it is greater than flintmax

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull timestwoaltcbull xtimesyc

See the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

1 API Reference

1-494

See AlsomxGetM mxGetN mxIsScalar

mxGetScalar (C and Fortran)

1-495

mxGetString (C and Fortran)mxChar array to C-style string or Fortran character array

C Syntaxinclude matrixhint mxGetString(const mxArray pm char str mwSize strlen)

Fortran Syntaxinclude fintrfhinteger4 mxGetString(pm str strlen)mwPointer pmcharacter() strmwSize strlen

Argumentspm

Pointer to an mxChar arraystr

Starting location mxGetString writes the character data into str and then in Cterminates the string with a NULL character (in the manner of C strings) str canpoint to either dynamic or static memory

strlenSize in bytes of destination buffer pointed to by str Typically in C you set strlento 1 plus the number of elements in the mxArray to which pm points To get thenumber of elements use mxGetM or mxGetN

Do not use with ldquoMultibyte Encoded Charactersrdquo on page 1-497

1 API Reference

1-496

Returns0 on success or if strlen == 0 and 1 on failure Possible reasons for failure include

bull mxArray is not an mxChar arraybull strlen is not large enough to store the entire mxArray If so the function returns 1

and truncates the string

DescriptionCall mxGetString to copy the character data of an mxArray into a C-style string in C ora character array in Fortran The copied data starts at str and contains no more thanstrlen-1 characters in C (no more than strlen characters in Fortran) In C the C-style string is always terminated with a NULL character

If the array contains multiple rows the function copies them into a single array onecolumn at a time

Multibyte Encoded Characters

Use this function only with characters represented in single-byte encoding schemes Forcharacters represented in multibyte encoding schemes use the C functionmxArrayToString Fortran users must allocate sufficient space for the return string toavoid possible truncation

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmallocc

See the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

mxGetString (C and Fortran)

1-497

bull revordF

See AlsomxArrayToString mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetChars

Introduced before R2006a

1 API Reference

1-498

mxIsCell (C and Fortran)Determine whether input is cell array

C Syntaxinclude matrixhbool mxIsCell(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsCell(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCELL_CLASS and logical 0(false) otherwise

DescriptionUse mxIsCell to determine whether the specified array is a cell array

In C calling mxIsCell is equivalent to calling

mxGetClassID(pm) == mxCELL_CLASS

mxIsCell (C and Fortran)

1-499

In Fortran calling mxIsCell is equivalent to calling

mxGetClassName(pm) eq cell

Note mxIsCell does not answer the question ldquoIs this mxArray a cell of a cell arrayrdquo Anindividual cell of a cell array can be of any type

See AlsomxIsClass

Introduced before R2006a

1 API Reference

1-500

mxIsChar (C and Fortran)Determine whether input is mxChar array

C Syntaxinclude matrixhbool mxIsChar(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsChar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCHAR_CLASS and logical 0(false) otherwise

DescriptionUse mxIsChar to determine whether pm points to an mxChar array

In C calling mxIsChar is equivalent to calling

mxGetClassID(pm) == mxCHAR_CLASS

mxIsChar (C and Fortran)

1-501

In Fortran calling mxIsChar is equivalent to calling

mxGetClassName(pm) eq char

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull revordc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxmallocc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxIsClass mxGetClassID

Introduced before R2006a

1 API Reference

1-502

mxIsClass (C and Fortran)Determine whether array is object of specified class

C Syntaxinclude matrixhbool mxIsClass(const mxArray pm const char classname)

Fortran Syntaxinclude fintrfhinteger4 mxIsClass(pm classname)mwPointer pmcharacter() classname

Argumentspm

Pointer to an mxArrayclassname

Array category to test Specify classname as a string (not as an integer identifier)You can specify any one of the following predefined constants

Value of classname Corresponding Classcell mxCELL_CLASSchar mxCHAR_CLASSdouble mxDOUBLE_CLASSfunction_handle mxFUNCTION_CLASSint8 mxINT8_CLASSint16 mxINT16_CLASS

mxIsClass (C and Fortran)

1-503

Value of classname Corresponding Classint32 mxINT32_CLASSint64 mxINT64_CLASSlogical mxLOGICAL_CLASSsingle mxSINGLE_CLASSstruct mxSTRUCT_CLASSuint8 mxUINT8_CLASSuint16 mxUINT16_CLASSuint32 mxUINT32_CLASSuint64 mxUINT64_CLASSltclass_namegt ltclass_idgt

unknown mxUNKNOWN_CLASS

In the table ltclass_namegt represents the name of a specific MATLAB custom objectYou can also specify one of your own class names

ReturnsLogical 1 (true) if pm points to an array having category classname and logical 0(false) otherwise

DescriptionEach mxArray is tagged as being a certain type Call mxIsClass to determine whetherthe specified mxArray has this type MATLAB does not check if the class is derived froma base class

In C

mxIsClass(pm double)

is equivalent to calling either of these forms

1 API Reference

1-504

mxIsDouble(pm)

strcmp(mxGetClassName(pm) double)

In Fortran

mxIsClass(pm double)

is equivalent to calling either one of the following

mxIsDouble(pm)

mxGetClassName(pm) eq double

It is most efficient to use the mxIsDouble form

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxClassID mxGetClassID mxIsEmpty mxGetClassName

Introduced before R2006a

mxIsClass (C and Fortran)

1-505

mxIsComplex (C and Fortran)Determine whether data is complex

C Syntaxinclude matrixhbool mxIsComplex(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsComplex(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm is a numeric array containing complex data and logical 0 (false)otherwise If pm points to a cell array or a structure array mxIsComplex returns false

DescriptionUse mxIsComplex to determine whether an imaginary part is allocated for an mxArrayIf an mxArray is purely real and does not have any imaginary data the imaginarypointer pi is NULL in C (0 in Fortran) If an mxArray is complex pi points to an array ofnumbers

1 API Reference

1-506

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxgetinfc

See the following examples in matlabrootexternexamplesrefbook

bull conveccbull convecFbull fulltosparseFbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorecbull yprimecbull mexlockc

See AlsomxIsNumeric

Introduced before R2006a

mxIsComplex (C and Fortran)

1-507

mxIsDouble (C and Fortran)Determine whether mxArray represents data as double-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsDouble(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsDouble(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as double-precision floating-pointnumbers and logical 0 (false) otherwise

DescriptionCall mxIsDouble to determine whether the specified mxArray represents its real andimaginary data as double-precision floating-point numbers

Older versions of MATLAB software store all mxArray data as double-precision floating-point numbers However starting with MATLAB Version 5 software MATLAB can storereal and imaginary data in various numerical formats

1 API Reference

1-508

In C calling mxIsDouble is equivalent to calling

mxGetClassID(pm) == mxDOUBLE_CLASS

In Fortran calling mxIsDouble is equivalent to calling

mxGetClassName(pm) eq double

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsDouble (C and Fortran)

1-509

mxIsEmpty (C and Fortran)Determine whether array is empty

C Syntaxinclude matrixhbool mxIsEmpty(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsEmpty(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is empty and logical 0 (false) otherwise

DescriptionUse mxIsEmpty to determine whether an mxArray contains no data An mxArray isempty if the size of any of its dimensions is 0

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-510

bull mxisfinitec

See AlsomxIsClass

Introduced before R2006a

mxIsEmpty (C and Fortran)

1-511

mxIsFinite (C and Fortran)Determine whether input is finite

C Syntaxinclude matrixhbool mxIsFinite(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsFinite(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is finite and logical 0 (false) otherwise

DescriptionCall mxIsFinite to determine whether value is finite A number is finite if it is greaterthan -Inf and less than Inf

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-512

bull mxisfinitec

See AlsomxIsInf mxIsNan

Introduced before R2006a

mxIsFinite (C and Fortran)

1-513

mxIsFromGlobalWS (C and Fortran)Determine whether array was copied from MATLAB global workspace

C Syntaxinclude matrixhbool mxIsFromGlobalWS(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsFromGlobalWS(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array was copied out of the global workspace and logical 0(false) otherwise

DescriptionmxIsFromGlobalWS is useful for standalone MAT-file programs

1 API Reference

1-514

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnsc

Introduced before R2006a

mxIsFromGlobalWS (C and Fortran)

1-515

mxIsInf (C and Fortran)Determine whether input is infinite

C Syntaxinclude matrixhbool mxIsInf(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsInf(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is infinite and logical 0 (false) otherwise

DescriptionCall mxIsInf to determine whether value is equal to infinity or minus infinityMATLAB software stores the value of infinity in a permanent variable named Inf whichrepresents IEEE arithmetic positive infinity The value of the variable Inf is built intothe system you cannot modify it

Operations that return infinity include

1 API Reference

1-516

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

If value equals NaN (Not-a-Number) mxIsInf returns false In other words NaN is notequal to infinity

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxIsFinite mxIsNaN

Introduced before R2006a

mxIsInf (C and Fortran)

1-517

mxIsInt16 (C and Fortran)Determine whether array represents data as signed 16-bit integers

C Syntaxinclude matrixhbool mxIsInt16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt16 to determine whether the specified array represents its real andimaginary data as 16-bit signed integers

In C calling mxIsInt16 is equivalent to calling

mxGetClassID(pm) == mxINT16_CLASS

1 API Reference

1-518

In Fortran calling mxIsInt16 is equivalent to calling

mxGetClassName(pm) == int16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt16 (C and Fortran)

1-519

mxIsInt32 (C and Fortran)Determine whether array represents data as signed 32-bit integers

C Syntaxinclude matrixhbool mxIsInt32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt32 to determine whether the specified array represents its real andimaginary data as 32-bit signed integers

In C calling mxIsInt32 is equivalent to calling

mxGetClassID(pm) == mxINT32_CLASS

1 API Reference

1-520

In Fortran calling mxIsInt32 is equivalent to calling

mxGetClassName(pm) == int32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt32 (C and Fortran)

1-521

mxIsInt64 (C and Fortran)Determine whether array represents data as signed 64-bit integers

C Syntaxinclude matrixhbool mxIsInt64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt64 to determine whether the specified array represents its real andimaginary data as 64-bit signed integers

In C calling mxIsInt64 is equivalent to calling

mxGetClassID(pm) == mxINT64_CLASS

1 API Reference

1-522

In Fortran calling mxIsInt64 is equivalent to calling

mxGetClassName(pm) == int64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt64 (C and Fortran)

1-523

mxIsInt8 (C and Fortran)Determine whether array represents data as signed 8-bit integers

C Syntaxinclude matrixhbool mxIsInt8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 8-bit integers and logical 0 (false)otherwise

DescriptionUse mxIsInt8 to determine whether the specified array represents its real andimaginary data as 8-bit signed integers

In C calling mxIsInt8 is equivalent to calling

mxGetClassID(pm) == mxINT8_CLASS

1 API Reference

1-524

In Fortran calling mxIsInt8 is equivalent to calling

mxGetClassName(pm) eq int8

See AlsomxIsClass mxGetClassID mxIsInt16 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt8 (C and Fortran)

1-525

mxIsLogical (C and Fortran)Determine whether array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogical(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsLogical(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a logical mxArray Otherwise it returns logical 0(false)

DescriptionUse mxIsLogical to determine whether MATLAB software treats the data in themxArray as Boolean (logical) If an mxArray is logical MATLAB treats all zeros asmeaning false and all nonzero values as meaning true

1 API Reference

1-526

See AlsomxIsClass

TopicsldquoLogical Operationsrdquo

Introduced before R2006a

mxIsLogical (C and Fortran)

1-527

mxIsLogicalScalar (C)Determine whether scalar array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogicalScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is of class mxLogical and has 1-by-1 dimensionsOtherwise it returns logical 0 (false)

DescriptionUse mxIsLogicalScalar to determine whether MATLAB treats the scalar data in themxArray as logical or numerical

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalarTrue

TopicsldquoLogical Operationsrdquo

1 API Reference

1-528

Introduced before R2006a

mxIsLogicalScalar (C)

1-529

mxIsLogicalScalarTrue (C)Determine whether scalar array of type mxLogical is true

C Syntaxinclude matrixhbool mxIsLogicalScalarTrue(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the value of the mxArray logical scalar element is true Otherwise itreturns logical 0 (false)

DescriptionUse mxIsLogicalScalarTrue to determine whether the value of a scalar mxArray istrue or false

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalar

TopicsldquoLogical Operationsrdquo

1 API Reference

1-530

Introduced before R2006a

mxIsLogicalScalarTrue (C)

1-531

mxIsNaN (C and Fortran)Determine whether input is NaN (Not-a-Number)

C Syntaxinclude matrixhbool mxIsNaN(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsNaN(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is NaN (Not-a-Number) and logical 0 (false) otherwise

DescriptionCall mxIsNaN to determine whether value is NaN NaN is the IEEE arithmeticrepresentation for Not-a-Number A NaN is obtained as a result of mathematicallyundefined operations such as

bull 0000bull Inf-Inf

1 API Reference

1-532

The system understands a family of bit patterns as representing NaN NaN is not a singlevalue it is a family of numbers that MATLAB software (and other IEEE-compliantapplications) uses to represent an error condition or missing data

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsec

See AlsomxIsFinite mxIsInf

Introduced before R2006a

mxIsNaN (C and Fortran)

1-533

mxIsNumeric (C and Fortran)Determine whether array is numeric

C Syntaxinclude matrixhbool mxIsNumeric(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsNumeric(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array can contain numeric data The following class IDs representstorage types for arrays that can contain numeric data

bull mxDOUBLE_CLASSbull mxSINGLE_CLASSbull mxINT8_CLASSbull mxUINT8_CLASSbull mxINT16_CLASSbull mxUINT16_CLASS

1 API Reference

1-534

bull mxINT32_CLASSbull mxUINT32_CLASSbull mxINT64_CLASSbull mxUINT64_CLASS

Logical 0 (false) if the array cannot contain numeric data

DescriptionCall mxIsNumeric to determine whether the specified array contains numeric data Ifthe specified array has a storage type that represents numeric data mxIsNumericreturns logical 1 (true) Otherwise mxIsNumeric returns logical 0 (false)

Call mxGetClassID to determine the exact storage type

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxGetClassID

Introduced before R2006a

mxIsNumeric (C and Fortran)

1-535

mxIsScalar (C)Determine whether array is scalar array

C Syntaxinclude matrixhbool mxIsScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray has 1-by-1 dimensions Otherwise it returns logical 0(false)

Note Only use mxIsScalar for mxArray classes with IDs documented by mxClassID

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxisscalarc

See AlsomxClassID | mxGetScalar

1 API Reference

1-536

Introduced in R2015a

mxIsScalar (C)

1-537

mxIsSingle (C and Fortran)Determine whether array represents data as single-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsSingle(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSingle(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as single-precision floating-point numbersand logical 0 (false) otherwise

DescriptionUse mxIsSingle to determine whether the specified array represents its real andimaginary data as single-precision floating-point numbers

In C calling mxIsSingle is equivalent to calling

mxGetClassID(pm) == mxSINGLE_CLASS

1 API Reference

1-538

In Fortran calling mxIsSingle is equivalent to calling

mxGetClassName(pm) eq single

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsSingle (C and Fortran)

1-539

mxIsSparse (C and Fortran)Determine whether input is sparse array

C Syntaxinclude matrixhbool mxIsSparse(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSparse(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a sparse mxArray and logical 0 (false) otherwise Afalse return value means that pm points to a full mxArray or that pm does not point to avalid mxArray

DescriptionUse mxIsSparse to determine whether pm points to a sparse mxArray Many routines(for example mxGetIr and mxGetJc) require a sparse mxArray as input

1 API Reference

1-540

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

See Alsosparse mxGetIr mxGetJc mxCreateSparse

Introduced before R2006a

mxIsSparse (C and Fortran)

1-541

mxIsStruct (C and Fortran)Determine whether input is structure array

C Syntaxinclude matrixhbool mxIsStruct(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsStruct(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a structure mxArray and logical 0 (false) otherwise

DescriptionUse mxIsStruct to determine whether pm points to a structure mxArray Many routines(for example mxGetFieldNameByNumber and mxSetField) require a structuremxArray as an argument

1 API Reference

1-542

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldNameByNumbermxGetField mxSetField

Introduced before R2006a

mxIsStruct (C and Fortran)

1-543

mxIsUint16 (C and Fortran)Determine whether array represents data as unsigned 16-bit integers

C Syntaxinclude matrixhbool mxIsUint16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint16 to determine whether the specified mxArray represents its real andimaginary data as 16-bit unsigned integers

In C calling mxIsUint16 is equivalent to calling

mxGetClassID(pm) == mxUINT16_CLASS

1 API Reference

1-544

In Fortran calling mxIsUint16 is equivalent to calling

mxGetClassName(pm) eq uint16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint16 (C and Fortran)

1-545

mxIsUint32 (C and Fortran)Determine whether array represents data as unsigned 32-bit integers

C Syntaxinclude matrixhbool mxIsUint32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint32 to determine whether the specified mxArray represents its real andimaginary data as 32-bit unsigned integers

In C calling mxIsUint32 is equivalent to calling

mxGetClassID(pm) == mxUINT32_CLASS

1 API Reference

1-546

In Fortran calling mxIsUint32 is equivalent to calling

mxGetClassName(pm) eq uint32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint64

Introduced before R2006a

mxIsUint32 (C and Fortran)

1-547

mxIsUint64 (C and Fortran)Determine whether array represents data as unsigned 64-bit integers

C Syntaxinclude matrixhbool mxIsUint64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint64 to determine whether the specified mxArray represents its real andimaginary data as 64-bit unsigned integers

In C calling mxIsUint64 is equivalent to calling

mxGetClassID(pm) == mxUINT64_CLASS

1 API Reference

1-548

In Fortran calling mxIsUint64 is equivalent to calling

mxGetClassName(pm) eq uint64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint32

Introduced before R2006a

mxIsUint64 (C and Fortran)

1-549

mxIsUint8 (C and Fortran)Determine whether array represents data as unsigned 8-bit integers

C Syntaxinclude matrixhbool mxIsUint8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 8-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint8 to determine whether the specified mxArray represents its real andimaginary data as 8-bit unsigned integers

In C calling mxIsUint8 is equivalent to calling

mxGetClassID(pm) == mxUINT8_CLASS

1 API Reference

1-550

In Fortran calling mxIsUint8 is equivalent to calling

mxGetClassName(pm) eq uint8

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint8 (C and Fortran)

1-551

mxLogical (C)Type for logical array

DescriptionAll logical mxArrays store their data elements as mxLogical rather than as bool

The header file containing this type is

include matrixh

See AlsomxCreateLogicalArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

Introduced before R2006a

1 API Reference

1-552

mxMalloc (C and Fortran)Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxMalloc(mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxMalloc(n)mwSize n

Argumentsn

Number of bytes to allocate for n greater than 0

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxMalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxMalloc is unsuccessful when there is insufficient free heap space

If you call mxMalloc in C with value n = 0 MATLAB returns either NULL or a validpointer

mxMalloc (C and Fortran)

1-553

DescriptionmxMalloc allocates contiguous heap space sufficient to hold n bytes To allocate memoryin MATLAB applications use mxMalloc instead of the ANSI C malloc function

In MEX files but not MAT or engine applications mxMalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

1 API Reference

1-554

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxRealloc

Introduced before R2006a

mxMalloc (C and Fortran)

1-555

mxRealloc (C and Fortran)Reallocate dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxRealloc(void ptr mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxRealloc(ptr size)mwPointer ptrmwSize size

Argumentsptr

Pointer to a block of memory allocated by mxCalloc mxMalloc or mxReallocsize

New size of allocated memory in bytes

ReturnsPointer to the start of the reallocated block of memory if successful If unsuccessful in aMAT or engine standalone application mxRealloc returns NULL in C (0 in Fortran) andleaves the original memory block unchanged (Use mxFree to free the original memoryblock) If unsuccessful in a MEX file the MEX file terminates and control returns to theMATLAB prompt

mxRealloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-556

DescriptionmxRealloc changes the size of a memory block that has been allocated with mxCallocmxMalloc or mxRealloc To allocate memory in MATLAB applications use mxReallocinstead of the ANSI C realloc function

mxRealloc changes the size of the memory block pointed to by ptr to size bytes Thecontents of the reallocated memory are unchanged up to the smaller of the new and oldsizes The reallocated memory might be in a different location from the original memoryso the returned pointer can be different from ptr If the memory location changesmxRealloc frees the original memory block pointed to by ptr

If size is greater than 0 and ptr is NULL in C (0 in Fortran) mxRealloc behaves likemxMalloc mxRealloc allocates a new block of memory of size bytes and returns apointer to the new block

If size is 0 and ptr is not NULL in C (0 in Fortran) mxRealloc frees the memorypointed to by ptr and returns NULL in C (0 in Fortran)

In MEX files but not MAT or engine applications mxRealloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

mxRealloc (C and Fortran)

1-557

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxMalloc

Introduced before R2006a

1 API Reference

1-558

mxRemoveField (C and Fortran)Remove field from structure array

C Syntaxinclude matrixhvoid mxRemoveField(mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhsubroutine mxRemoveField(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Number of the field you want to remove In C to remove the first field setfieldnumber to 0 to remove the second field set fieldnumber to 1 and so on InFortran to remove the first field set fieldnumber to 1 to remove the second fieldset fieldnumber to 2 and so on

DescriptionCall mxRemoveField to remove a field from a structure array If the field does not existnothing happens This function does not destroy the field values To destroy the actualfield values call mxRemoveField and then call mxDestroyArray

Consider a MATLAB structure initialized to

mxRemoveField (C and Fortran)

1-559

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test In Fortran the field number 1represents the field name field number 2 represents field billing field number 3represents field test

See AlsomxAddField mxDestroyArray mxGetFieldByNumber

Introduced before R2006a

1 API Reference

1-560

mxSetCell (C and Fortran)Set contents of cell array

C Syntaxinclude matrixhvoid mxSetCell(mxArray pm mwIndex index mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetCell(pm index value)mwPointer pm valuemwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Index from the beginning of the mxArray Specify the number of elements betweenthe first cell of the mxArray and the cell you want to set The easiest way to calculateindex in a multidimensional cell array is to call mxCalcSingleSubscript

valuePointer to new value for the cell You can put an mxArray of any type into a cell Youcan even put another cell mxArray into a cell

DescriptionCall mxSetCell to put the designated value into a particular cell of a cell mxArray

mxSetCell (C and Fortran)

1-561

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxDestroyArray on the pointer returned by mxGetCellbefore you call mxSetCell

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray mxCreateCellMatrix mxGetCell mxIsCellmxDestroyArray

Introduced before R2006a

1 API Reference

1-562

mxSetClassName (C)Structure array to MATLAB object array

Note Use mxSetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhint mxSetClassName(mxArray array_ptr const char classname)

Argumentsarray_ptr

Pointer to an mxArray of class mxSTRUCT_CLASSclassname

Object class to which to convert array_ptr

Returns0 if successful and nonzero otherwise One cause of failure is that array_ptr is not astructure mxArray Call mxIsStruct to determine whether array_ptr is a structure

DescriptionmxSetClassName converts a structure array to an object array to be saved later to aMAT-file MATLAB does not register or validate the object until it is loaded by the LOADcommand If the specified classname is an undefined class within MATLAB LOADconverts the object back to a simple structure array

mxSetClassName (C)

1-563

See AlsomxIsClass mxGetClassID mxIsStruct

Introduced before R2006a

1 API Reference

1-564

mxSetData (C and Fortran)Set pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxSetData(mxArray pm void pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetData(pm pr)mwPointer pm pr

Argumentspm

Pointer to an mxArraypr

Pointer to an array Each element in the array contains the real component of avalue The array must be in dynamic memory call mxCalloc to allocate thismemory Do not use the ANSI C calloc function which can cause memoryalignment issues leading to program termination

DescriptionmxSetData is like mxSetPr except that in C its second argument is a void Use thisfunction on numeric arrays with contents other than double

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetData before you callmxSetData

mxSetData (C and Fortran)

1-565

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatac

See AlsomxCalloc mxFree mxGetData mxSetPr

Introduced before R2006a

1 API Reference

1-566

mxSetDimensions (C and Fortran)Modify number of dimensions and size of each dimension

C Syntaxinclude matrixhint mxSetDimensions(mxArray pm const mwSize dims mwSize ndim)

Fortran Syntaxinclude fintrfhinteger4 mxSetDimensions(pm dims ndim)mwPointer pmmwSize ndimmwSize dims(ndim)

Argumentspm

Pointer to an mxArraydims

Dimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray In most cases there are ndim elements in the dimsarray

ndimNumber of dimensions

mxSetDimensions (C and Fortran)

1-567

Returns0 on success and 1 on failure mxSetDimensions allocates heap space to hold the inputsize array So it is possible (though unlikely) that increasing the number of dimensionscan cause the system to run out of heap space

DescriptionCall mxSetDimensions to reshape an existing mxArray mxSetDimensions is likemxSetM and mxSetN however mxSetDimensions provides greater control for reshapingan mxArray that has more than two dimensions

mxSetDimensions does not allocate or deallocate any space for the pr or pi arrays Soif your call to mxSetDimensions increases the number of elements in the mxArrayenlarge the pr (and pi if it exists) arrays accordingly

If your call to mxSetDimensions reduces the number of elements in the mxArray youcan optionally reduce the size of the pr and pi arrays using mxRealloc

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetdimensionsfF

See AlsomxGetNumberOfDimensions mxSetM mxSetN mxRealloc

Introduced before R2006a

1 API Reference

1-568

mxSetField (C and Fortran)Set field value in structure array given index and field name

C Syntaxinclude matrixhvoid mxSetField(mxArray pm mwIndex index const char fieldname mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetField(pm index fieldname pvalue)mwPointer pm pvaluemwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of an element in the array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an index

mxSetField (C and Fortran)

1-569

fieldnameName of a field in the structure The field must exist in the structure CallmxGetFieldNameByNumber or mxGetFieldNumber to determine existing fieldnames

pvaluePointer to an mxArray containing the data you want to assign to fieldname

DescriptionUse mxSetField to assign the contents of pvalue to the field fieldname of elementindex

If you want to replace the contents of fieldname first free the memory of the existingdata Use the mxGetField function to get a pointer to the field call mxDestroyArray onthe pointer then call mxSetField to assign the new value

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then call mxSetFieldon each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

1 API Reference

1-570

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldmxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetFieldByNumber mxDestroyArray mxCalcSingleSubscript

Alternatives

C Language

In C you can replace the statements

field_num = mxGetFieldNumber(pa fieldname)mxSetFieldByNumber(pa index field_num new_value_pa)

with a call to mxSetField

mxSetField(pa index fieldname new_value_pa)

Fortran Language

In Fortran you can replace the statements

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

with a call to mxSetField

mxSetField(pm index fieldname newvalue)

Introduced before R2006a

mxSetField (C and Fortran)

1-571

mxSetFieldByNumber (C and Fortran)Set field value in structure array given index and field number

C Syntaxinclude matrixhvoid mxSetFieldByNumber(mxArray pm mwIndex index int fieldnumber mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetFieldByNumber(pm index fieldnumber pvalue)mwPointer pm pvaluemwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an indexfieldnumber

Position of the field in the structure The field must exist in the structure

1 API Reference

1-572

In C the first field within each element has a fieldnumber of 0 The fieldnumberof the last is N-1 where N is the number of fields

In Fortran the first field within each element has a fieldnumber of 1 Thefieldnumber of the last is N where N is the number of fields

pvaluePointer to the mxArray containing the data you want to assign

DescriptionUse mxSetFieldByNumber to assign the contents of pvalue to the field specified byfieldnumber of element index mxSetFieldByNumber is like mxSetField howeverthe function identifies the field by position number not by name

If you want to replace the contents at fieldnumber first free the memory of the existingdata Use the mxGetFieldByNumber function to get a pointer to the field callmxDestroyArray on the pointer then call mxSetFieldByNumber to assign the newvalue

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then callmxSetFieldByNumber on each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

mxSetFieldByNumber (C and Fortran)

1-573

Alternatives

C Language

In C calling

mxSetField(pa index field_name new_value_pa)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxSetFieldByNumber(pa index field_num new_value_pa)

Fortran Language

In Fortran calling

mxSetField(pm index fieldname newvalue)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldByNumbermxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxDestroyArray mxCalcSingleSubscript

Introduced before R2006a

1 API Reference

1-574

mxSetImagData (C and Fortran)Set pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxSetImagData(mxArray pm void pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetImagData(pm pi)mwPointer pm pi

Argumentspm

Pointer to an mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory errors will result when the array is destroyed

DescriptionmxSetImagData is like mxSetPi except that in C its pi argument is a void Usethis function on numeric arrays with contents other than double

mxSetImagData (C and Fortran)

1-575

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetImagData beforeyou call mxSetImagData

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxCalloc mxFree mxGetImagData mxSetPi

Introduced before R2006a

1 API Reference

1-576

mxSetIr (C and Fortran)IR array of sparse array

C Syntaxinclude matrixhvoid mxSetIr(mxArray pm mwIndex ir)

Fortran Syntaxinclude fintrfhsubroutine mxSetIr(pm ir)mwPointer pm ir

Argumentspm

Pointer to a sparse mxArrayir

Pointer to the ir array The ir array must be sorted in column-major order

DescriptionUse mxSetIr to specify the ir array of a sparse mxArray The ir array is an array ofintegers the length of the ir array equals the value of nzmax the storage allocated forthe sparse array or nnz the number of nonzero matrix elements

Each element in the ir array indicates a row (offset by 1) at which a nonzero elementcan be found (The jc array is an index that indirectly specifies a column where nonzeroelements can be found See mxSetJc for more details on jc)

mxSetIr (C and Fortran)

1-577

For example suppose that you create a 7-by-3 sparse mxArray named Sparrowcontaining six nonzero elements by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The pr array holds the real data for the sparse matrix which in Sparrow is the five 1sand the one 2 If there is any nonzero imaginary data it is in a pi arraySubscript ir pr jc Comments(21) 1 1 0 Column 1 ir is 1 because row is 2(51) 4 1 2 Column 1 ir is 4 because row is 5(32) 2 1 3 Column 2 ir is 2 because row is 3(23) 1 2 6 Column 3 ir is 1 because row is 2(53) 4 1 Column 3 ir is 4 because row is 5(63) 5 1 Column 3 ir is 5 because row is 6

Notice how each element of the ir array is always 1 less than the row of thecorresponding nonzero element For instance the first nonzero element is in row 2therefore the first element in ir is 1 (that is 2 ndash 1) The second nonzero element is inrow 5 therefore the second element in ir is 4 (5 ndash 1)

The ir array must be in column-major order The ir array must define the row positionsin column 1 (if any) first then the row positions in column 2 (if any) second and so onthrough column N Within each column row position 1 must appear before row position2 and so on

mxSetIr does not sort the ir array for you you must specify an ir array that is alreadysorted

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetIr before you callmxSetIr

1 API Reference

1-578

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateSparse mxGetIr mxGetJc mxSetJc mxFree nzmax nnz

Introduced before R2006a

mxSetIr (C and Fortran)

1-579

mxSetJc (C and Fortran)JC array of sparse array

C Syntaxinclude matrixhvoid mxSetJc(mxArray pm mwIndex jc)

Fortran Syntaxinclude fintrfhsubroutine mxSetJc(pm jc)mwPointer pm jc

Argumentspm

Pointer to a sparse mxArrayjc

Pointer to the jc array

DescriptionUse mxSetJc to specify a new jc array for a sparse mxArray The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

If the jth column of the sparse mxArray has any nonzero elements

bull jc[j] is the index in ir pr and pi (if it exists) of the first nonzero element in thejth column

bull jc[j+1]-1 is the index of the last nonzero element in the jth column

1 API Reference

1-580

bull For the jth column of the sparse matrix jc[j] is the total number of nonzeroelements in all preceding columns

The number of nonzero elements in the jth column of the sparse mxArray is

jc[j+1] - jc[j]

For the jth column of the sparse mxArray jc[j] is the total number of nonzeroelements in all preceding columns The last element of the jc array jc[number ofcolumns] is equal to nnz which is the number of nonzero elements in the entire sparsemxArray

For example consider a 7-by-3 sparse mxArray named Sparrow containing six nonzeroelements created by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The following table lists the contents of the ir jc and pr arraysSubscript ir pr jc Comment(21) 1 1 0 Column 1 contains two nonzero

elements with rows designated byir[0] and ir[1]

(51) 4 1 2 Column 2 contains one nonzeroelement with row designated by ir[2]

(32) 2 1 3 Column 3 contains three nonzeroelements with rows designated byir[3]ir[4] and ir[5]

(23) 1 2 6 There are six nonzero elements in all(53) 4 1 (63) 5 1

mxSetJc (C and Fortran)

1-581

As an example of a much sparser mxArray consider a 1000-by-8 sparse mxArray namedSpacious containing only three nonzero elements The ir pr and jc arrays containthe values listed in this tableSubscript ir pr jc Comment(732) 72 1 0 Column 1 contains no nonzero

elements(503) 49 1 0 Column 2 contains one nonzero

element with row designated by ir[0](645) 63 1 1 Column 3 contains one nonzero

element with row designated by ir[1] 2 Column 4 contains no nonzero

elements 2 Column 5 contains one nonzero

element with row designated by ir[2] 3 Column 6 contains no nonzero

elements 3 Column 7 contains no nonzero

elements 3 Column 8 contains no nonzero

elements 3 There are three nonzero elements in all

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetJc before you callmxSetJc

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-582

See AlsomxCreateSparse mxGetIr mxGetJc mxSetIr mxFree

Introduced before R2006a

mxSetJc (C and Fortran)

1-583

mxSetM (C and Fortran)Set number of rows in array

C Syntaxinclude matrixhvoid mxSetM(mxArray pm mwSize m)

Fortran Syntaxinclude fintrfhsubroutine mxSetM(pm m)mwPointer pmmwSize m

Argumentspm

Pointer to an mxArraym

Number of rows

DescriptionCall mxSetM to set the number of rows in the specified mxArray The term rows meansthe first dimension of an mxArray regardless of the number of dimensions Call mxSetNto set the number of columns

You typically use mxSetM to change the shape of an existing mxArray The mxSetMfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So ifyour calls to mxSetM and mxSetN increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays Call mxRealloc to enlarge them

1 API Reference

1-584

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetN mxRealloc

Introduced before R2006a

mxSetM (C and Fortran)

1-585

mxSetN (C and Fortran)Set number of columns in array

C Syntaxinclude matrixhvoid mxSetN(mxArray pm mwSize n)

Fortran Syntaxinclude fintrfhsubroutine mxSetN(pm n)mwPointer pmmwSize n

Argumentspm

Pointer to an mxArrayn

Number of columns

DescriptionCall mxSetN to set the number of columns in the specified mxArray The term columnsalways means the second dimension of a matrix Calling mxSetN forces an mxArray tohave two dimensions For example if pm points to an mxArray having three dimensionscalling mxSetN reduces the mxArray to two dimensions

You typically use mxSetN to change the shape of an existing mxArray The mxSetNfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So if

1 API Reference

1-586

your calls to mxSetN and mxSetM increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetM

Introduced before R2006a

mxSetN (C and Fortran)

1-587

mxSetNzmax (C and Fortran)Set storage space for nonzero elements

C Syntaxinclude matrixhvoid mxSetNzmax(mxArray pm mwSize nzmax)

Fortran Syntaxinclude fintrfhsubroutine mxSetNzmax(pm nzmax)mwPointer pmmwSize nzmax

Argumentspm

Pointer to a sparse mxArraynzmax

Number of elements mxCreateSparse should allocate to hold the arrays pointed toby ir pr and pi (if it exists) Set nzmax greater than or equal to the number ofnonzero elements in the mxArray but set it to be less than or equal to the number ofrows times the number of columns If you specify an nzmax value of 0 mxSetNzmaxsets the value of nzmax to 1

DescriptionUse mxSetNzmax to assign a new value to the nzmax field of the specified sparsemxArray The nzmax field holds the maximum number of nonzero elements in the sparsemxArray

1 API Reference

1-588

The number of elements in the ir pr and pi (if it exists) arrays must be equal tonzmax Therefore after calling mxSetNzmax you must change the size of the ir pr andpi arrays To change the size of one of these arrays

1 Call mxRealloc with a pointer to the array setting the size to the new value ofnzmax

2 Call the appropriate mxSet routine (mxSetIr mxSetPr or mxSetPi) to establishthe new memory area as the current one

Ways to determine how large to make nzmax are

bull Set nzmax equal to or slightly greater than the number of nonzero elements in asparse mxArray This approach conserves precious heap space

bull Make nzmax equal to the total number of elements in an mxArray This approacheliminates (or at least reduces) expensive reallocations

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetNzmax mxRealloc

Introduced before R2006a

mxSetNzmax (C and Fortran)

1-589

mxSetPi (C and Fortran)Set new imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPi(mxArray pm double pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetPi(pm pi)mwPointer pm pi

Argumentspm

Pointer to a full (nonsparse) mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory leaks and other memory errors might result

DescriptionUse mxSetPi to set the imaginary data of the specified mxArray

Most mxCreate functions optionally allocate heap space to hold imaginary data If youtell an mxCreate function to allocate heap spacemdashfor example by setting theComplexFlag to mxCOMPLEX in C (1 in Fortran) or by setting pi to a non-NULL value in

1 API Reference

1-590

C (a nonzero value in Fortran)mdashyou do not ordinarily use mxSetPi to initialize thecreated mxArrays imaginary elements Rather you call mxSetPi to replace the initialimaginary values with new ones

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPi before you callmxSetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetImagData mxSetPr mxFree

Introduced before R2006a

mxSetPi (C and Fortran)

1-591

mxSetPr (C and Fortran)Set new real data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPr(mxArray pm double pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetPr(pm pr)mwPointer pm pr

Argumentspm

Pointer to a full (nonsparse) mxArraypr

Pointer to the first element of an array Each element in the array contains the realcomponent of a value The array must be in dynamic memory call mxCalloc toallocate this memory Do not use the ANSI C calloc function which can causememory alignment issues leading to program termination If pr points to staticmemory memory leaks and other memory errors can result

DescriptionUse mxSetPr to set the real data of the specified mxArray

All mxCreate calls allocate heap space to hold real data Therefore you do notordinarily use mxSetPr to initialize the real elements of a freshly created mxArrayRather you call mxSetPr to replace the initial real values with new ones

1 API Reference

1-592

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPr before you callmxSetPr

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

See the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetData mxSetPi mxFree

Introduced before R2006a

mxSetPr (C and Fortran)

1-593

mxSetProperty (C and Fortran)Set value of public property of MATLAB object

C Syntaxinclude matrixhvoid mxSetProperty(mxArray pa mwIndex index const char propname const mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetProperty(pa index propname value)mwPointer pa valuemwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you are assigning

valuePointer to the mxArray you are assigning

1 API Reference

1-594

DescriptionUse mxSetProperty to assign a value to the specified property In pseudo-Cterminology mxSetProperty performs the assignment

pa[index]propname = value

Property propname must be an existing public property and index must be within thebounds of the mxArray To test the index value use mxGetNumberOfElements ormxGetM and mxGetN functions

mxSetProperty makes a copy of the value before assigning it as the new property valueMaking a copy might be a concern if the property uses a large amount of memory Theremust be sufficient memory (in the heap) to hold the copy of the value

Limitationsbull mxSetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

See AlsomxGetProperty

Introduced in R2008a

mxSetProperty (C and Fortran)

1-595

Page 5: C and Fortran API Reference

API Reference

1

matlabdataArrayDimensionsType specifying array dimensions

DescriptionUse the ArrayDimensions type to specify the size of an array ArrayDimensions isspecified as

using ArrayDimensions = stdvectorltsize_tgt

Free Function

getNumElementsinline size_t getNumElements(const ArrayDimensionsamp dims)

Determine the number of elements based on the ArrayDimensions

const ArrayDimensionsampdims

Array dimensions

inline size_t Number of elements

None

See Also

TopicsldquoMATLAB Data API Typesrdquo

1 API Reference

1-2

Introduced in R2017b

matlabdataArrayDimensions

1-3

matlabdataArrayElementRefC++ class representing element of Array or ReferenceltArraygt object

DescriptionAn ArrayElementRef object is created when using operator[] into an Array or aReferenceltArraygt It is untyped since Array and ReferenceltArraygt do not havetype information It collects up the indexes specified by the user and can be cast to anelement if the array holds primitive data or can be used to create a ReferenceltTgtinstance

Indexing is zero-based

Class DetailsNamespace matlabdataInclude ArrayElementRefhpp

Template Parametersbool is_const_ref Indicates if this reference is const The non-const

version of this class supports assignment

Other Operatorsbull ldquooperator[]rdquo on page 1-4bull ldquooperator Trdquo on page 1-5bull ldquooperator=rdquo on page 1-6

operator[]ArrayElementRefltis_const_refgt operator[](size_t idx)

ArrayElementRefltis_const_refgt operator[](stdstring idx)

1 API Reference

1-4

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indices in anindexing operation

stdstring idx Index to add Array must support string indexing

TooManyIndicesProvidedException

Too many indices provided The number of size_tindices is more than the number of dimensions in thearray

StringIndexMustBeLastException

String index is not the last index A size_t index isprovided after a string index

StringIndexNotValidException

An stdstring index is not valid for this array

CanOnlyUseOneStringIndexException

More than one stdstring index provided

double val = arr[2][7][f1]

operator Ttemplate lttypename Tgtoperator T() const

Cast a value Throws an error if not arithmetic complex or stdstring

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain the type specifiedby T

Array dblArray_const = factorycreateArrayltdoublegt(22)double val = dblArray_const[1][2]

matlabdataArrayElementRef

1-5

operator=template lttypename TgtArrayElementRefltis_const_refgtamp operator= (T rhs)

Assign a primitive or complex type to an element of an Array The Array must be non-const

If the Array contains other Arrays then operator= can assign an Array into theelement

T rhs The value to assign to an element in the Array specifiedas a primitive or complex type or as an Array

ArrayElementRefltis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array does not contain a primitive orcomplex type or does not contain other Arrays

Assign numeric types to Array arr

Array arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55arr[1][2] = stdcomplexltdoublegt(54 31)

Assign an Array to cell_arr then create a ReferenceltArraygt ref to the element

Array cell_arr = factorycreateArrayltArraygt(13)cell_arr[2] = factorycreateScalar(true)ReferenceltArraygt ref = cell_arr[2]

See AlsoArray | ArrayElementTypedRef | Reference | TypedArrayRef

1 API Reference

1-6

Introduced in R2017b

matlabdataArrayElementRef

1-7

matlabdataArrayElementTypedRefC++ class representing element of TypedArray or TypedArrayRef object

DescriptionAn ArrayElementTypedRef object is created when using operator[] into aTypedArrayltTgt or a TypedArrayRefltTgt It collects up the indexes specified by theuser and can be cast to ltTgt without the added cost of type checking that exists whenusing ArrayElementRef Primitive types can be cast to Tamp which is not supported withArrayElementRef The non-const version of this class supports assignment

Class DetailsNamespace matlabdataInclude ArrayElementTypedRefhpp

Template ParametersT Element typesbool is_const_ref TBD

Other Operatorsbull ldquooperator[]rdquo on page 1-8bull ldquooperator referencerdquo on page 1-9bull ldquooperator=rdquo on page 1-10

operator[]ArrayElementTypedRefltT is_const_refgt operator[](size_t idx)

ArrayElementTypedRefltArray is_const_refgt operator[](stdstringidx)

1 API Reference

1-8

Add an index to an Array

size_t idx Index to add Call this syntax to use two or more indicesin an indexing operation

stdstring idx Index to add Array must support string indexing

ArrayElementTypedRefltArray is_const_refgt

New instance with the additional index

TooManyIndicesProvidedException

Too many indices provided

StringIndexMustBeLastException

String index is not the last index

double val = arr[2][7][3]

operator referenceoperator reference() const

operator stdstring() const

Cast to reference to its primitive value

T

stdstring

The value

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

double val = dblArray[1][2]

stdstring val = strArray[1][2]

matlabdataArrayElementTypedRef

1-9

operator=ArrayElementTypedRefltT is_const_refgtamp operator= (T rhs)

ArrayElementTypedRefltT is_const_refgtamp operator= (stdstring rhs)

Assign a value into an Array The Array must be non-const

T rhs

stdstring rhs

Value to assign to an element in the Array

ArrayElementTypedRefltTis_const_refgtamp

Reference to the Array element

InvalidArrayIndexException

The index provided is not valid for this Array or one of theindices is out of range

TypeMismatchException

The element of the Array cannot be cast to stdstring

arr[1][2] = stdcomplexltdoublegt(54 31)

arr[1][2] = MyString

ExamplesTBD

TypedArrayltdoublegt arr = factorycreateArrayltdoublegt(22)arr[0][0] = 55doubleamp val = arr[0][0]CellArray cell_arr = factorycreateArrayltArraygt(12)cell_arr[0] = factorycreateScalar(105)cell_arr[1] = factorycreateScalar(false)ArrayRef ref_to_element = cell_arr[0]TypedArrayRefltdoublegt typed_ref_to_element = cell_arr[0]

1 API Reference

1-10

Array const shared_copy_of_element = cell_arr[1]TypedArrayltboolgt const typed_shared_copy_of_element = cell_arr[1]

See AlsoArray | ArrayElementRef | ArrayElementTypedRef | Reference |TypedArrayRef | TypedIterator

Introduced in R2017b

matlabdataArrayElementTypedRef

1-11

matlabdataArrayFactoryC++ class to create arrays

DescriptionUse ArrayFactory to create matlabdataArray objects

Class DetailsNamespace matlabdataInclude ArrayFactoryhpp

Constructors

Default Constructor

ArrayFactory()

FailedToLoadLibMatlabDataArrayException

Concrete implementation has not been loaded

Destructor~ArrayFactory()

Member Functionsbull ldquocreateArrayrdquo on page 1-13bull ldquocreateScalarrdquo on page 1-14bull ldquocreateCellArrayrdquo on page 1-15

1 API Reference

1-12

bull ldquocreateCharArrayrdquo on page 1-16bull ldquocreateStructArrayrdquo on page 1-17bull ldquocreateEnumArrayrdquo on page 1-18bull ldquocreateSparseArrayrdquo on page 1-19bull ldquocreateEmptyArrayrdquo on page 1-20bull ldquocreateBufferrdquo on page 1-21bull ldquocreateArrayFromBufferrdquo on page 1-21

createArraytemplate lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims)

template lttypename ItType typename TgtTypedArrayltTgt createArray(ArrayDimensions dims ItType begin ItType end)

template lttypename TgtTypedArrayltTgt createArray(ArrayDimensions dims const T const begin const T const end)

template lttypename Tgt TypedArrayltTgt createArray(ArrayDimensions dims stdinitializer_listltTgt data)

Creates a TypedArrayltTgt with the given dimensions Fills the array with data ifspecified Data is copied and must be in column major order

bull ItType - Iterator types specified as stditeratorbull T - Element types specified as one of the following C++ data types

bool int8_t int16_t int32_t int64_t uint8_tuint16_t uint32_t uint64_t float double char16_t

matlabdataArrayFactory

1-13

matlabdataString

stdcomplexltdoublegt

stdcomplexltfloatgt

stdcomplexltint8_tgt

stdcomplexltuint8_tgt

stdcomplexltint16_tgt

stdcomplexltuint16_tgt

stdcomplexltint32_tgt

stdcomplexltuint32_tgt

stdcomplexltint64_tgt

stdcomplexltuint64_tgt

matlabdataMATLABString

ArrayDimensionsdims

Dimensions for the array

ItType begin

ItType end

Start and end of the user supplied data The data type isdetermined by the value_type of the iterator

const T constbegin

const T const end

Start and end of the user supplied data specified as C-stylepointer Supports all primitive types complex types andstring types

stdinitializer_listltTgt

Initializer list containing the data

matlabOutOfMemoryException

The array could not be allocated

createScalartemplate lttypename TgtTypedArrayltTgt createScalar(const T val)

TypedArrayltStringgt createScalar(const String val)

TypedArrayltStringgt createScalar(const stdstring val)

Creates a scalar TypedArrayltTgt with the given value This method supports arithmetictypes complex types and string types

const T val Value to be inserted into the scalar If valis 7-bit ASCII data then the methodconverts it to UTF16

const String valconst stdstring val

1 API Reference

1-14

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory

Create a vector containing 2 scalar values stdvectorltmatlabdataArraygt args( factorycreateScalarltint16_tgt(100) factorycreateScalarltint16_tgt(60)) return 0

ldquoCall Function with Single Returned Argumentrdquo

createCellArrayCellArrayltArraygt createCellArray(ArrayDimensions dims)

template lttypename TargsgtCellArrayltArraygt createCellArray(ArrayDimensions dims Targs data)

Creates a CellArray with the specified data Data is specified in column major order

Targs Variadic template of

bull arithmetic typebull complex typebull matlabdataStringbull stdstringbull matlabdataArray

matlabdataArrayFactory

1-15

ArrayDimensionsdims

Dimensions of the cell array

Targs data Elements to be inserted into the cell array specified as aprimitive complex type string or Array

matlabOutOfMemoryException

The array could not be allocated

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f CellArray myArray = fcreateCellArray( 12 fcreateCharArray(MATLAB Cell Array) fcreateArrayltdoublegt( 22 12 22 32 42 ))

return 0

createCharArrayCharArray createCharArray(String str)

CharArray createCharArray(stdstring str)

Creates a 1xn CharArray from the specified input where n is the string length

matlabdataString str

Data to be filled into the array

stdstring str

matlabOutOfMemoryException

The array could not be allocated

1 API Reference

1-16

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) return 0

createStructArrayStructArray createStructArray(ArrayDimensions dims stdvectorltstdstringgt fieldNames)

Creates a StructArray with the given dimensions and field names

ArrayDimensions dims Dimensions for the arraystdvectorltstdstringgtfieldNames

Vector of the field names for the structure

matlabOutOfMemoryException

The array could not be allocated

DuplicateFieldNameInStructArrayException

Duplicate field names specified

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f

Create StructArray equivalent to MATLAB structure s s = struct(loc east west data [1 2 3] [4 5 6 7 8]) StructArray S = fcreateStructArray( 12 loc data ) S[0][loc] = fcreateCharArray(east) S[0][data] = fcreateArrayltuint8_tgt( 1 3 1 2 3 )

matlabdataArrayFactory

1-17

S[1][loc] = fcreateCharArray(west) S[1][data] = fcreateArrayltdoublegt( 1 5 4 5 6 7 8 )

Access the value defined by the MATLAB statement s(1)data ReferenceltArraygt val = S[0][data] return 0

createEnumArrayEnumArray createEnumArray(ArrayDimensions dims stdstring className stdvectorltstdstringgt enums)

EnumArray createEnumArray(ArrayDimensions dims stdstring className)

Creates an EnumArray of type className If specified the array is initialized with thelist of enumeration names

ArrayDimensionsdims

Dimensions for the array

stdstringclassName

Class name of the enumeration array

stdvectorltstdstringgt enums

List of the enumeration names

matlabOutOfMemoryException

The array could not be allocated

MustSpecifyClassNameException

Class name not specified

WrongNumberOfEnumsSuppliedException

The wrong number of enumerations provided

include MatlabDataArrayhppinclude ltvectorgt

1 API Reference

1-18

int main() using namespace matlabdata ArrayFactory f auto blue = fcreateEnumArray( 11 TextColor Blue )

Create an argument vector stdvectorltArraygt args( fcreateCharArray(My text) stdmove(blue) )

return 0

createSparseArraytemplate lttypename TgtSparseArrayltTgt createSparseArray(ArrayDimensions dims size_t nnz buffer_ptr_tltTgt data buffer_ptr_tltsize_tgt rows buffer_ptr_tltsize_tgt cols)

Creates a SparseArrayltTgt with rows-by-cols dimensions Only two dimensions areallowed for sparse arrays The buffer is not copied and the array takes ownership

T Element types specified as double bool orstdcomplexltdoublegt

ArrayDimensionsdims

Dimensions for the array

size_t nnz Number of nonzero elementsbuffer_ptr_tltTgtdata

Buffer containing the nonzero elements

buffer_ptr_tltsize_tgt rows

Buffer containing the row value for each element

buffer_ptr_tltsize_tgt cols

Buffer containing the column value for each element

matlabdataArrayFactory

1-19

matlabOutOfMemoryException

The array could not be allocated

InvalidDimensionsInSparseArrayException

More than two dimensions are specified

include MatlabDataArrayhpp

int main() stdvectorltdoublegt data = 35 1298 2176 stdvectorltsize_tgt rows = 001 stdvectorltsize_tgt cols = 048 size_t nnz = 3

matlabdataArrayFactory factory auto data_p = factorycreateBufferltdoublegt(nnz) auto rows_p = factorycreateBufferltsize_tgt(nnz) auto cols_p = factorycreateBufferltsize_tgt(nnz)

double dataPtr = data_pget() size_t rowsPtr = rows_pget() size_t colsPtr = cols_pget() stdfor_each(databegin() dataend() [amp](const doubleamp e) (dataPtr++) = e ) stdfor_each(rowsbegin() rowsend() [amp](const size_tamp e) (rowsPtr++) = e ) stdfor_each(colsbegin() colsend() [amp](const size_tamp e) (colsPtr++) = e )

matlabdataSparseArrayltdoublegt arr = factorycreateSparseArrayltdoublegt( 29 nnz stdmove(data_p) stdmove(rows_p) stdmove(cols_p)) return 0

createEmptyArrayArray createEmptyArray()

Creates an empty Array containing no elements

Array Empty array

1 API Reference

1-20

matlabOutOfMemoryException

The array could not be allocated

createBuffertemplate lttypename Tgtbuffer_ptr_tltTgt createBuffer(size_t numberOfElements)

Creates a buffer which can be passed into createArrayFromBuffer No data copies aremade when creating an array from a buffer Data must be in column major order

T Primitive types

size_t numberOfElements Number of elements not the actualbuffer size

buffer_ptr_tltTgt Unique_ptr containing the buffer

matlabOutOfMemoryException

The array could not be allocated

createArrayFromBuffertemplate lttypename TgtTypedArrayltTgt createArrayFromBuffer(ArrayDimensions dims buffer_ptr_tltTgt buffer)

Creates a TypedArrayltTgt using the given buffer

T Primitive types

ArrayDimensions dims Dimensions for the arraybuffer_ptr_tltTgt buffer Buffer containing the data The buffer is not

copied The TypedArrayltTgt object takesownership of the buffer Data must be in columnmajor order

matlabdataArrayFactory

1-21

matlabOutOfMemoryException

The array could not be allocated

See Also

Introduced in R2017b

1 API Reference

1-22

matlabdataReferenceltArraygtC++ class to get reference to Array

DescriptionUse the ReferenceltArraygt class to get a reference to an Array element of a containerobject such as a MATLAB structure or cell array The class is a base class for allreference types that refer to arrays and provides basic array information ArrayRef isdefined as

using ArrayRef = ReferenceltArraygt

Class DetailsNamespace matlabdataInclude ArrayReferenceExthpp

Member Functionsbull ldquogetTyperdquo on page 1-23bull ldquogetDimensionsrdquo on page 1-24bull ldquogetNumberOfElementsrdquo on page 1-24bull ldquoisEmptyrdquo on page 1-24

getTypeArrayType getType() const

ArrayType Type of the array

NotEnoughIndicesProvidedException

Not enough indices provided

matlabdataReferenceltArraygt

1-23

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

InvalidArrayTypeException

Array type not recognized

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Array dimensions vector

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

getNumberOfElementssize_t getNumberOfElements() const

size_t Number of elements in array

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

isEmptybool isEmpty() const

bool Returns true if array is empty otherwise returns false

NotEnoughIndicesProvidedException

Not enough indices provided

1 API Reference

1-24

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-25bull ldquogetWritableElementsrdquo on page 1-25

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are const

const ReferenceltArraygtampref

ReferenceltArraygt

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(ReferenceltArraygtamp ref)

Get a range containing the elements of the Array or ReferenceltArraygt Iteratorscontained in the range are non-const

ReferenceltArraygtamp ref ReferenceltArraygt

matlabdataReferenceltArraygt

1-25

RangeltTypedIterator Tgt Range containing begin and end iterators for theelements of the input ReferenceltArraygt

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayType

Introduced in R2017b

1 API Reference

1-26

matlabdataArrayTypeC++ array type enumeration class

DescriptionUse ArrayType objects to identify the data type and other attributes of a MATLABarray

Class DetailsNamespace matlabdataInclude ArrayTypehpp

Enumerationenum class ArrayType UNKNOWN LOGICAL CHAR DOUBLE SINGLE INT8 UINT8 INT16 UINT16 INT32 UINT32 INT64 UINT64 COMPLEX_DOUBLE COMPLEX_SINGLE COMPLEX_INT8 COMPLEX_UINT8 COMPLEX_INT16 COMPLEX_UINT16 COMPLEX_INT32 COMPLEX_UINT32

matlabdataArrayType

1-27

COMPLEX_INT64 COMPLEX_UINT64 CELL STRUCT OBJECT VALUE_OBJECT HANDLE_OBJECT_REF ENUM SPARSE_LOGICAL SPARSE_DOUBLE SPARSE_COMPLEX_DOUBLE MATLAB_STRING

C++ Data Type ConversionMATLAB ArrayType Value C++ Type DescriptionDOUBLE double double-precision (64-bit)

floating-point numberSINGLE float single-precision (32-bit)

floating-point numberINT8 int8_t signed 8-bit integerUINT8 uint8_t unsigned 8-bit integerINT16 int16_t signed 16-bit integerUINT16 uint16_t unsigned 16-bit integerINT32 int32_t signed 32-bit integerUINT32 uint32_t unsigned 32-bit integerINT64 int64_t signed 64-bit integerUINT64 uint64_t unsigned 64-bit integerCHAR char16_t 16-bit characterLOGICAL bool logicalCOMPLEX_DOUBLE stdcomplexltdoublegt complex double-precision

(64-bit) floating-pointnumber

1 API Reference

1-28

MATLAB ArrayType Value C++ Type DescriptionCOMPLEX_SINGLE stdcomplexltfloatgt complex single precision

(32-bit) floating-pointnumber

COMPLEX_INT8 stdcomplexltint8_tgt complex signed 8-bitinteger

COMPLEX_UINT8 stdcomplexltuint8_tgt complex unsigned 8-bitinteger

COMPLEX_INT16 stdcomplexltint16_tgt complex signed 16-bitinteger

COMPLEX_UINT16 stdcomplexltuint16_tgt complex unsigned 16-bitinteger

COMPLEX_INT32 stdcomplexltint32_tgt complex signed 32-bitinteger

COMPLEX_UINT32 stdcomplexltuint32_tgt complex unsigned 32-bitinteger

COMPLEX_INT64 stdcomplexltint64_tgt complex signed 64-bitinteger

COMPLEX_UINT64 stdcomplexltuint64_tgt complex unsigned 64-bitinteger

CELL matlabdataArray Array containing otherArrays

STRUCT matlabdataStruct Array with named fieldsthat can contain data ofvarying types and sizes

OBJECT matlabdataObject MATLAB objectVALUE_OBJECT matlabdataObject MATLAB value objectHANDLE_OBJECT_REF matlabdataObject Reference to an existing

handle object in MATLABENUM matlabdataEnumerat

ionArray of enumerationvalues

SPARSE_LOGICAL bool Sparse array of logicalSPARSE_DOUBLE double Sparse array of double

matlabdataArrayType

1-29

MATLAB ArrayType Value C++ Type DescriptionSPARSE_COMPLEX_DOUBLE stdcomplexltdoublegt Sparse array of complex

doubleMATLAB_STRING matlabdataMATLABSt

ringMATLAB string

See AlsoArrayVisitors

Introduced in R2017b

1 API Reference

1-30

matlabdataArrayVisitorsFunctions for defining visitor pattern

DetailsNamespace matlabdataInclude ArrayVisitorshpp

Functionsbull ldquoapply_visitorrdquo on page 1-31bull ldquoapply_visitor_refrdquo on page 1-31

apply_visitorauto apply_visitor(Array a V visitor)

TBD

TBD

InvalidArrayTypeException

apply_visitor_refauto apply_visitor_ref(const ArrayRefamp a V visitor)

Apply functor V to Array a

Result of V

matlabdataArrayVisitors

1-31

InvalidArrayTypeException

See Also

Introduced in R2017b

1 API Reference

1-32

matlabdataCellArrayC++ class to access MATLAB cell arrays

DescriptionA CellArray is a TypedArray with Array as the element type Use CellArray objectsto access MATLAB cell arrays To create a CellArray call createCellArrayCellArray is defined as

using CellArray = TypedArrayltArraygt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

ExamplesCreate Cell Array

Create a cell array with two elements

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CellArray cellArray1 = factorycreateCellArray( 12 factorycreateCharArray(MATLAB Cell Array) factorycreateArrayltdoublegt( 22 12 22 32 42 ))

matlabdataCellArray

1-33

return 0

See AlsocreateCellArray

Introduced in R2017b

1 API Reference

1-34

matlabdataCharArrayC++ class to access MATLAB character arrays

DescriptionUse CharArray objects to work with MATLAB character arrays To create a CharArraycall createCharArray

Class DetailsNamespace matlabdataBase class TypedArrayltchar16_tgtInclude CharArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-35bull ldquoCopy Assignment Operatorsrdquo on page 1-36bull ldquoMove Constructorsrdquo on page 1-37bull ldquoMove Assignment Operatorsrdquo on page 1-37

Copy Constructors

CharArray(const CharArrayamp rhs)

CharArray(const Arrayamp rhs)

Creates a shared data copy of a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

matlabdataCharArray

1-35

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray B(A) return 0

createCharArray on page 1-16

Copy Assignment OperatorsCharArrayamp operator=(const CharArrayamp rhs)

CharArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a CharArray object

const CharArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array) CharArray C = factorycreateCharArray()

1 API Reference

1-36

Arrays A and C refer to the same data C = A

return 0

Move Constructors

CharArray(CharArrayampamp rhs)

CharArray(Arrayampamp rhs)

Moves contents of a CharArray object to a new instance

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move constructor - Creates B copies data from A A not valid CharArray B(stdmove(A))

return 0

Move Assignment Operators

CharArrayamp operator=(CharArrayampamp rhs)

CharArrayamp operator=(Arrayampamp rhs)

matlabdataCharArray

1-37

Assigns the input to this CharArray object

CharArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeCHAR object

CharArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeCHAR

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory CharArray A = factorycreateCharArray(This is a char array)

Move assignment - Data from A moved to C A no longer valid CharArray C = factorycreateCharArray() C = stdmove(A)

return 0

Member Functionsbull ldquotoUTF16rdquo on page 1-38bull ldquotoAsciirdquo on page 1-39

toUTF16String toUTF16() const

matlabdataString Contents of CharArray as matlabdataString

None

1 API Reference

1-38

toAsciistdstring toAscii() const

stdstring Contents of CharArray as ASCII string

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory f auto arr = fcreateCharArray(helloworld) stdstring s = arrtoAscii()

return 0

ldquoEvaluate Mathematical Function in MATLABrdquo

See AlsoldquocreateCharArrayrdquo on page 1-16 | TypedArray | matlabdataString

Introduced in R2017b

matlabdataCharArray

1-39

matlabdataReferenceltCharArraygtC++ class to get reference to CharArray

DescriptionThe CharArrayExt class extends the APIs available to a reference to a CharArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquotoUTF16rdquo on page 1-40bull ldquotoAsciirdquo on page 1-40

toUTF16String toUTF16() const

matlabdataString Contents of reference to CharArray as a utf16 string

None

toAsciistdstring toAscii() const

stdstring Contents of reference to CharArray asmatlabdataString

1 API Reference

1-40

NonAsciiCharInRequestedAsciiOutputException

Data contains non-ASCII characters

See AlsoCharArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltCharArraygt

1-41

matlabdataEnumArrayC++ class to access MATLAB enumeration arrays

DescriptionUse EnumArray objects to access enumeration arrays To create an EnumArray callcreateEnumArray

Class DetailsNamespace matlabdataBase class TypedArrayltEnumerationgtInclude EnumArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-42bull ldquoCopy Assignment Operatorsrdquo on page 1-43bull ldquoMove Constructorsrdquo on page 1-43bull ldquoMove Assignment Operatorsrdquo on page 1-43

Copy Constructors

EnumArray(const EnumArrayamp rhs)

EnumArray(const Arrayamp rhs)

Creates a shared data copy of an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as EnumArray object

1 API Reference

1-42

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Copy Assignment OperatorsEnumArrayamp operator=(const EnumArrayamp rhs)

EnumArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an EnumArray object

const EnumArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move ConstructorsEnumArray(EnumArrayampamp rhs)

EnumArray(Arrayampamp rhs)

Moves contents of an EnumArray object to a new instance

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Move Assignment OperatorsEnumArrayamp operator=(EnumArrayampamp rhs)

matlabdataEnumArray

1-43

EnumArrayamp operator=(Arrayampamp rhs)

Assigns the input to this EnumArray object

EnumArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeENUM object

EnumArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeENUM

Member Functions

getClassNamestdstring getClassName() const

Return class name for this EnumArray

stdstring The class name

None

See AlsoldquocreateEnumArrayrdquo on page 1-18 | TypedArray

Introduced in R2017b

1 API Reference

1-44

matlabdataReferenceltEnumArraygtC++ class to get reference to EnumArray

DescriptionThe EnumArrayExt class extends the APIs available to a reference to an EnumArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functions

getClassNamestdstring getClassName() const

Return class name for this reference to an EnumArray object

stdstring Class name

None

See AlsoEnumArray | ReferenceltTypedArrayltTgtgt

Introduced in R2017b

matlabdataReferenceltEnumArraygt

1-45

matlabdataEnumerationElement type for MATLAB enumeration arrays

DescriptionEnumeration is the element type for an EnumArray object

Class DetailsNamespace matlabdataInclude Enumerationhpp

See AlsoEnumArray

TopicsldquoMATLAB Data API Typesrdquo

Introduced in R2017b

1 API Reference

1-46

matlabExceptionC++ base class for exceptions

DescriptionAll MATLAB C++ exceptions can be caught as matlabException

Class DetailsNamespace matlabInclude Exceptionhpp

See Also

TopicsldquoMATLAB Data API Exceptionsrdquo

Introduced in R2017b

matlabException

1-47

matlabdataForwardIteratorltTgtTemplated C++ class to provide forward iterator support for StructArray field names

DescriptionUse ForwardIterator objects to access a range of field name elements in aStructArray

Class DetailsNamespace matlabdataInclude ForwardIteratorhpp

Template ParametersT matlabdataMATLABFieldIdentifier

Constructorsbull ldquoCopy Constructorsrdquo on page 1-48bull ldquoCopy Assignment Operatorsrdquo on page 1-49

Copy Constructors

ForwardIterator(const ForwardIteratorltTgtamp rhs)

Creates a shared data copy of a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to copy

ForwardIterator New instance

1 API Reference

1-48

None

Copy Assignment Operators

ForwardIteratorltTgtamp operator=(const ForwardIteratorltTgtamp rhs)

Assigns a shared data copy to a ForwardIteratorltTgt object

constForwardIteratorltTgtamp rhs

Object to assign

ForwardIteratorltTgt Updated instance

None

Other Operatorsbull ldquooperator++rdquo on page 1-49bull ldquooperator--rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperator=rdquo on page 1-50bull ldquooperatorrdquo on page 1-51bull ldquooperator-gtrdquo on page 1-51bull ldquooperator[]rdquo on page 1-51

operator++ForwardIteratorltTgtamp operator++()

Pre-increment operator

ForwardIteratorltTgtamp Reference to updated value

matlabdataForwardIteratorltTgt

1-49

None

operator--ForwardIteratorltTgt operator--(int)

Post-increment operator

ForwardIteratorltTgt New object

None

operator=bool operator==(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if the iterators point to the same elementOtherwise returns false

None

operator=bool operator=(const ForwardIteratorltTgtamp rhs) const

constForwardIteratorltTgtamp rhs

Iterator to compare

bool Returns true if this iterator points to a differentelement Otherwise returns false

None

1 API Reference

1-50

operatorreference operator() const

reference Shared copy of element that iterator points to specifiedas

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataForwardIteratorltTgt

1-51

See AlsoMATLABFieldIdentifier | StructArray

Introduced in R2017b

1 API Reference

1-52

matlabdataGetArrayTypeC++ struct TBD

DescriptionUse GetArrayType objects to TBD

Class DetailsNamespace matlabdataInclude GetArrayTypehpp

See Also

Introduced in R2017b

matlabdataGetArrayType

1-53

matlabdataGetReturnTypeC++ struct TBD

DescriptionUse GetReturnType to convert a template argument to the appropriate templateargument when creating a TypedArray

Class DetailsNamespace matlabdataInclude GetReturnTypehpp

See Also

Introduced in R2017b

1 API Reference

1-54

matlabdataMATLABFieldIdentifierC++ class used to identify field names in MATLAB struct array

Description

Class DetailsNamespace matlabdataInclude MATLABFieldIdentifierhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-55bull ldquoConstructorrdquo on page 1-55bull ldquoDestructorrdquo on page 1-56bull ldquoCopy Constructorsrdquo on page 1-56bull ldquoCopy Assignment Operatorsrdquo on page 1-56bull ldquoMove Constructorsrdquo on page 1-57bull ldquoMove Assignment Operatorsrdquo on page 1-57

Default ConstructorMATLABFieldIdentifier()

Construct an empty MATLABFieldIdentifier

None

ConstructorMATLABFieldIdentifier(stdstring str)

matlabdataMATLABFieldIdentifier

1-55

Construct a MATLABFieldIdentifier from stdstring

stdstring str String that contains the field name

Destructor

~MATLABFieldIdentifier()

Destroy a MATLABFieldIdentifier

None

Copy Constructors

MATLABFieldIdentifier(const MATLABFieldIdentifieramp rhs)

Creates a shared data copy of a MATLABFieldIdentifier object

constMATLABFieldIdentifieramprhs

Value to copy

None

Copy Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifier constamp rhs)

Assigns a shared data copy to a MATLABFieldIdentifier object

MATLABFieldIdentifierconstamp rhs

Value to move

1 API Reference

1-56

MATLABFieldIdentifieramp Updated instance

None

Move Constructors

MATLABFieldIdentifier(MATLABFieldIdentifierampamp rhs)

Moves contents a MATLABFieldIdentifier object to a new instance

MATLABFieldIdentifierampamprhs

Value to move

None

Move Assignment Operators

MATLABFieldIdentifieramp operator=(MATLABFieldIdentifierampamp rhs)

MATLABFieldIdentifierampamprhs

Value to move

MATLABFieldIdentifieramp Updated instance

None

Destructor~MATLABFieldIdentifier()

Description

Destroy a MATLABFieldIdentifier

matlabdataMATLABFieldIdentifier

1-57

Other Operators

operator stdstringoperator stdstring() const

stdstring Representation of the MATLABFieldIdentifier object

None

Free Functions

operator==bool operator==(const MATLABFieldIdentifieramp rhs) const

Check if two MATLABFieldIdentifier objects are identical

constMATLABFieldIdentifieramprhs

Value to be compared

bool Returns true if the objects are identical Otherwisereturns false

None

See AlsoForwardIterator | StructArray

Introduced in R2017b

1 API Reference

1-58

matlabdataMATLABStringElement type for MATLAB string arrays

DescriptionMATLABString is defined as

using MATLABString = OptionalltStringgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataString

Introduced in R2017b

matlabdataMATLABString

1-59

matlabdataReferenceltMATLABStringgtC++ class to get reference to element of StringArray

DescriptionA ReferenceltMATLABStringgt object is created when using operator[] into anStringArray or dereferenceing a String arrary iterator

Class DetailsNamespace matlabdataInclude MATLABStringReferenceExthpp

Cast

String()operator String() const

matlabdataString Element of a MATLABString array converted toString

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

stdruntime_error Array element does not have a value

1 API Reference

1-60

Member Functionsbull ldquoboolrdquo on page 1-61bull ldquohas_valuerdquo on page 1-61

booloperator bool() const

Check whether string contains a value

operator True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

has_valuebool has_value() const

Check whether string contains a value

bool True if string contains a value

NotEnoughIndicesProvidedException

Not enough indices provided

InvalidArrayIndexException

Index provided is not valid for this Array or one of theindices is out of range

TooManyIndicesProvidedException

Too many indices provided

matlabdataReferenceltMATLABStringgt

1-61

See Also

Introduced in R2017b

1 API Reference

1-62

matlabdataArrayC++ base class for all array types

DescriptionUse Array objects to represent single and multi-dimensional arrays The Array classprovides methods for users to be able to query generic information about all arrays suchas dimensions and type and has methods to create deep copies and shared data copiesUse ArrayFactory methods to construct Arrays Once an Array has been constructedit can be moved or cloned (deep-copied) or a shared-data copy can be created Arrayssupport copy-on-write semantics

Class DetailsNamespace matlabdataInclude MDArrayhpp

Constructorsbull ldquoDefault Constructorrdquo on page 1-63bull ldquoCopy Constructorsrdquo on page 1-64bull ldquoCopy Assignment Operatorsrdquo on page 1-64bull ldquoMove Constructorsrdquo on page 1-64bull ldquoMove Assignment Operatorsrdquo on page 1-65

Default Constructor

Array()

None

matlabdataArray

1-63

Copy Constructors

Array(const Arrayamp rhs)

Creates a shared data copy of an Array object

const Arrayamp rhs Value to copy

None

Copy Assignment Operators

Arrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to an Array object

const Arrayamp rhsrhs Value to copy

Arrayamp Updated instance

None

Move Constructors

Array(Arrayampamp rhs)

Moves contents of an Array object to a new instance

Arrayampamp rhs Value to move

None

1 API Reference

1-64

Move Assignment Operators

Arrayamp operator=(Arrayampamp rhs)

Assigns the input to this Array object

Arrayampamp rhs Value to move

Arrayamp Updated instance

None

Destructorvirtual ~Array()

Indexing Operators

operator[]ArrayElementRefltfalsegt operator[](size_t idx)

ArrayElementReflttruegt operator[](size_t idx) const

Enables [] indexing on const and non-const arrays Indexing is 0-based

size_t idx First array index

ArrayElementRefltfalsegt Temporary object containing the index specified Thereturn value allows the element of the array to bemodified or retrieved

matlabdataArray

1-65

ArrayElementReflttruegt Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Member Functionsbull ldquogetTyperdquo on page 1-66bull ldquogetDimensionsrdquo on page 1-66bull ldquogetNumberOfElementsrdquo on page 1-66bull ldquoisEmptyrdquo on page 1-67

getTypeArrayType getType() const

ArrayType Array type

None

getDimensionsArrayDimensions getDimensions() const

ArrayDimensions Vector of each dimension in the array

None

getNumberOfElementssize_t getNumberOfElements() const

size_t The number of elements in the array

1 API Reference

1-66

None

isEmptybool isEmpty() const

bool True if array is empty False if array is not empty

None

Free Functionsbull ldquogetReadOnlyElementsrdquo on page 1-67bull ldquogetWritableElementsrdquo on page 1-67

getReadOnlyElementstemplate lttypename TgtRangeltTypedIterator T constgt getReadOnlyElements(const Arrayamp arr)

Get a range containing the elements of the Array Iterators contained in the range areconst

const Arrayamp arr Array

RangeltTypedIterator Tconstgt

Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

getWritableElementstemplate lttypename TgtRangeltTypedIterator Tgt getWritableElements(Arrayamp arr)

matlabdataArray

1-67

Get a range containing the elements of the Array Iterators contained in the range arenon-const

Arrayamp arr Array

RangeltTypedIterator Tgt Range containing begin and end iterators for the inputArray

InvalidArrayTypeException

Array does not contain type T

See AlsoArrayFactory

Introduced in R2017b

1 API Reference

1-68

matlabdataObjectElement type for MATLAB object arrays

DescriptionObject is the element type for an ObjectArray

Class DetailsNamespace matlabdataInclude Objecthpp

See AlsoObjectArray

Introduced in R2017b

matlabdataObject

1-69

matlabdataObjectArrayC++ class to access MATLAB object arrays

DescriptionUse ObjectArray objects to access MATLAB object arrays You do not create anObjectArray only MATLAB functions create ObjectArrays You can pass anObjectArray to a MATLAB function

ObjectArray is defined as

using ObjectArray = TypedArrayltObjectgt

Class DetailsNamespace matlabdataInclude ObjectArrayhpp

See AlsoObject

Introduced in R2017b

1 API Reference

1-70

matlabdataOptionalltTgtTemplated C++ class representing optional values

DescriptionUse Optional objects to represent values that might or might not exist

Class DetailsNamespace matlabdataInclude Optionalhpp

Template ParametersT Array type specified as matlabdataString

Constructorsbull ldquoDefault Constructorsrdquo on page 1-71bull ldquoCopy Constructorsrdquo on page 1-71bull ldquoCopy Assignment Operatorsrdquo on page 1-72bull ldquoMove Constructorsrdquo on page 1-72bull ldquoMove Assignment Operatorsrdquo on page 1-72

Default Constructors

optional()

Copy Constructors

optional(const optionalamp other)

matlabdataOptionalltTgt

1-71

Creates a shared data copy

const optionalamp other Value to copy

None

Copy Assignment OperatorsoptionalltTgtamp operator=(const optionalltTgtamp other)

Assigns a shared data copy

const optionalltTgtamp other Value to copy

optionalltTgtamp Updated instance

None

Move Constructorsoptional(optionalampamp other)

optional(Tampamp value)

Moves contents of an Optional object to a new instance

optionalampamp other Value to moveTampamp value Value of type T to move

None

Move Assignment OperatorsoptionalltTgtamp operator=(optionalltTgtampamp other)

1 API Reference

1-72

optionalltTgtamp operator=(Tampamp value)

Assigns the input to this instance

optionalltTgtampamp other

Tampamp value

Value to move

optionalltTgtamp Updated instance

None

Other Operatorsbull ldquooperator=rdquo on page 1-73bull ldquooperator-gtrdquo on page 1-74bull ldquooperatorrdquo on page 1-74bull ldquooperator Trdquo on page 1-74

operator=optionalltTgtamp operator=(nullopt_t)

optionalltTgtamp operator=(const optionalltTgtamp other)

optionalltTgtamp operator=(optionalltTgtampamp other)

optionalltTgtamp operator=(Tampamp value)

optionalltTgtamp operator=(const Tamp value)

Assignment operators

optionalltTgtamp Updated instance

None

matlabdataOptionalltTgt

1-73

operator-gtconst T operator-gt() const

T operator-gt()

const T

T

Pointer to the element

stdruntime_error Optional object does not contain a value

operatorconst Tamp operator() const

Tamp operator()

const Tamp

Tamp

Reference to the element

stdruntime_error Optional object does not contain a value

operator Toperator T() const

Cast optionalltTgt value to T

operator Value contained in optionalltTgt if it exists

stdruntime_error There is no value

1 API Reference

1-74

Member Functionsbull ldquoboolrdquo on page 1-75bull ldquohas_valuerdquo on page 1-75bull ldquoswaprdquo on page 1-75bull ldquoresetrdquo on page 1-76

boolexplicit operator bool() const

Check whether object contains a value

operator True if object contains a value

None

has_valuebool has_value() const

Check whether object contains a value

bool True if object contains a value

None

swapvoid swap(optional ampother)

Swap value of this optional instance with value contained in the parameter

optional ampother Value to swap

matlabdataOptionalltTgt

1-75

None

resetvoid reset()

Reset optional value to missing

None

See Also

Introduced in R2017b

1 API Reference

1-76

matlabdataRangeltItTypeElemTypegtTemplated C++ class to provide range-based operation support

DescriptionRange objects wrap begin and end functions to enable range-based operations

Class DetailsNamespace matlabdataInclude Rangehpp

Template ParametersIteratorType Iterator typeElementType Element type

Constructorsbull ldquoConstructorrdquo on page 1-77bull ldquoMove Constructorsrdquo on page 1-78bull ldquoMove Assignment Operatorsrdquo on page 1-78

Constructor

Range(IteratorTypeltElementTypegt begin IteratorTypeltElementTypegtend)

Creates a Range object

matlabdataRangeltItTypeElemTypegt

1-77

IteratorTypeltElementTypegt begin

IteratorTypeltElementTypegt end

First and last elements of range

Range New instance

None

Move Constructors

Range(Rangeampamp rhs)

Moves contents of a Range object to a new instance

Rangeampamp rhs Range to move

Range New instance

None

Move Assignment Operators

Rangeamp operator=(Rangeampamp rhs)

Assigns the input to this Range object

Rangeampamp rhs Range to move

Rangeamp Updated instance

None

1 API Reference

1-78

beginIteratorTypeltElementTypegtamp begin()

ReturnsIteratorTypeltElementTypegtamp

First element in range

None

endIteratorTypeltElementTypegtamp end()

ReturnsIteratorTypeltElementTypegtamp

End of range

None

See Also

Introduced in R2017b

matlabdataRangeltItTypeElemTypegt

1-79

matlabdataReferenceltTgtTemplated C++ class to get references to Array elements

DescriptionA Reference object is a reference to an element of an Array without making a copy AReference is

bull Not a shared copybull Valid as long as the array that contains the reference is validbull Not thread-safe

Class DetailsNamespace matlabdataInclude Referencehpp

Template ParametersT Type of element referred to specified as

bull Arraybull Structbull Enumerationbull MATLABStringbull All stdcomplex types

Constructorsbull ldquoCopy Constructorrdquo on page 1-81bull ldquoCopy Assignment Operatorsrdquo on page 1-81bull ldquoMove Assignment Operatorsrdquo on page 1-81

1 API Reference

1-80

bull ldquoMove Constructorsrdquo on page 1-81

Copy ConstructorReference(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

Copy Assignment OperatorsReferenceltTgtamp operator=(const ReferenceltTgtamp rhs)

const ReferenceltTgtamp rhs Value to copy

ReferenceltTgtamp Updated instance

Move Assignment OperatorsReferenceltTgtamp operator=(ReferenceltTgtampamp rhs)

ReferenceltTgtampamp rhs Value to move

ReferenceltTgtamp Updated instance

None

Move ConstructorsReference(ReferenceltTgtampamp rhs)

Moves contents of a Reference object to a new instance

ReferenceltTgtampamp rhs Value to move

None

matlabdataReferenceltTgt

1-81

Other Operatorsbull ldquooperator=rdquo on page 1-82bull ldquooperatorltltrdquo on page 1-82bull ldquooperator T()rdquo on page 1-83bull ldquooperator stdstring()rdquo on page 1-83

operator=ReferenceltTgtamp operator=(T rhs)

ReferenceltTgtamp operator=(stdstring rhs)

ReferenceltTgtamp operator=(String rhs)

T rhs Value to assign The array being indexed must be non-const

stdstring rhs String to assign The array must be non-const andallow strings to be assigned

String rhs String to assign to StringArray The array beingindexed must be non-const

ReferenceltTgtamp Updated instance

None

operatorltlt

stdostreamamp operator ltlt(stdostreamamp os ReferenceltTgt constamp rhs)

stdostreamamp os ReferenceltTgt constamp rhs

stdostreamamp

1 API Reference

1-82

operator T()operator T() const

Cast to element from the array

T Shared copy of element from the array

None

operator stdstring()operator stdstring() const

Cast to stdstring from the array Makes a copy of the stdstring Only valid fortypes that can be cast to a stdstring

stdstring The string

NonAsciiCharInInputDataException

Input is stdstring and contains non-ASCIIcharacters

stdruntime_error MATLABString is missing

Free Functions

operator==inline bool operator ==(ReferenceltMATLABStringgt constamp lhsstdstring constamp rhs)

inline bool operator ==(stdstring constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhs Stringconstamp rhs)

matlabdataReferenceltTgt

1-83

inline bool operator ==(String constamp lhs ReferenceltMATLABStringgtconstamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsMATLABString constamp rhs)

inline bool operator ==(MATLABString constamp lhsReferenceltMATLABStringgt constamp rhs)

inline bool operator ==(ReferenceltMATLABStringgt constamp lhsReferenceltMATLABStringgt constamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhs Tconstamp rhs)

templatelttypename Tgt bool operator ==(T constamp lhs ReferenceltTgtconstamp rhs)

templatelttypename Tgt bool operator ==(ReferenceltTgt constamp lhsReferenceltTgt constamp rhs)

ReferenceltMATLABStringgtconstamp lhs

stdstring constamp rhs Values tocompare

stdstring constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

String constamp rhs

String constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

MATLABString constamp rhs

MATLABString constamp lhs ReferenceltMATLABStringgtconstamp rhs

ReferenceltMATLABStringgtconstamp lhs

ReferenceltMATLABStringgtconstamp rhs

ReferenceltTgt constamp lhs T constamp rhsT constamp lhs ReferenceltTgt constamp rhsReferenceltTgt constamp lhs ReferenceltTgt constamp rhs

1 API Reference

1-84

bool Returns true if values are equal

stdruntime_error Cannot compare argument to MATLABString

See Also

TopicsldquoAccess C++ Data Array Container Elementsrdquo

Introduced in R2017b

matlabdataReferenceltTgt

1-85

matlabdataSparseArrayltTgtTemplated C++ class to access data in MATLAB sparse arrays

DescriptionUse SparseArray objects to work with sparse MATLAB arrays To create aSparseArray call createSparseArray

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude SparseArrayhpp

Template ParametersT Type of element referred to specified as

bull boolbull doublebull stdcomplexltdoublegt

Constructorsbull ldquoCopy Constructorsrdquo on page 1-86bull ldquoCopy Assignment Operatorsrdquo on page 1-87bull ldquoMove Constructorsrdquo on page 1-87bull ldquoMove Assignment Operatorsrdquo on page 1-88

Copy Constructors

SparseArray(const SparseArrayltTgtamp rhs)

1 API Reference

1-86

SparseArray(const Arrayamp rhs)

Creates a shared data copy of a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array ofArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Copy Assignment OperatorsSparseArrayamp operator=(const SparseArrayltTgtamp rhs)

SparseArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a SparseArray object

const SparseArrayltTgtamprhs

Value to copy

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

Move ConstructorsSparseArray(SparseArrayampamp rhs)

matlabdataSparseArrayltTgt

1-87

SparseArray(Arrayampamp rhs)

Moves contents a SparseArray object to a new instance

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

InvalidArrayTypeException

Type of input Array is not sparse

Move Assignment Operators

SparseArrayamp operator=(SparseArrayltTgtampamp rhs)

SparseArrayamp operator=(Arrayampamp rhs)

Assigns the input to this SparseArray object

const SparseArrayltTgtamprhs

Value to move

const Arrayamp rhs Value specified as an Array of typeArrayTypeSPARSE_LOGICALArrayTypeSPARSE_DOUBLE orArrayTypeSPARSE_COMPLEX_DOUBLE

SparseArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not sparse

1 API Reference

1-88

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-89bull ldquoEnd Iteratorsrdquo on page 1-89

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functionsbull ldquogetNumberOfNonZeroElementsrdquo on page 1-90

matlabdataSparseArrayltTgt

1-89

bull ldquogetIndexrdquo on page 1-90

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array

size_t Number of nonzero elements in the array

None

getIndexSparseIndex getIndex(const TypedIteratorltTgtamp it)

SparseIndex getIndex(const TypedIteratorltT constgtamp it)

Returns the row-column coordinates of the nonzero entry that the iterator is pointing to

const TypedIteratorltTgtampit

Iterator pointing to the current entry in the sparsematrix

const TypedIteratorltTconstgtamp it

SparseIndex Row-column coordinates of the nonzero entry that theiterator is pointing to SparseIndex is defined asstdpairltsize_t size_tgt

None

See AlsoArray | createSparseArray

1 API Reference

1-90

Introduced in R2017b

matlabdataSparseArrayltTgt

1-91

matlabdataReferenceltSparseArrayltTgtgtTemplated C++ class to get reference to SparseArray

DescriptionUse the ReferenceltSparseArraygt class to get a reference to a SparseArray elementof a container object such as a MATLAB structure or cell array

Class DetailsNamespace matlabdataInclude SparseArrayRefhpp

Template ParametersT Type of elements in SparseArray specified as bool

double or stdcomplexltdoublegt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-92bull ldquoEnd Interatorsrdquo on page 1-93

Begin Interatorsiterator begin()

const_iterator begin() const

const_iterator cbegin() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to beginning of array Iterates over non-zeroelements of the SparseArray

1 API Reference

1-92

None

End Interators

iterator end()

const_iterator end() const

const_iterator cend() const

ldquoiteratorrdquo

ldquoconst_iteratorrdquo

Iterator to end of array

None

Member Functions

getNumberOfNonZeroElementssize_t getNumberOfNonZeroElements() const

Returns the number of nonzero elements in the array Since sparse arrays only storenonzero elements this method returns the actual array size It is different from arraydimensions that specify the full array size

size_t Number of nonzero elements in the array

None

See Also

Introduced in R2017b

matlabdataReferenceltSparseArrayltTgtgt

1-93

matlabdataStringType representing strings as stdbasic_stringltchar16_tgt

DescriptionThe String class defines the element type of a StringArray String is defined as

using String = stdbasic_stringltchar16_tgt

Class DetailsNamespace matlabdataInclude Stringhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

1 API Reference

1-94

matlabdataStringArrayC++ class to access MATLAB string arrays

DescriptionUse StringArray objects to access MATLAB string arrays StringArray is defined as

using StringArray = TypedArrayltMATLABStringgt

Class DetailsNamespace matlabdataInclude TypedArrayhpp

See AlsomatlabdataMATLABString

Introduced in R2017b

matlabdataStringArray

1-95

matlabdataStructArrayC++ class to access MATLAB struct arrays

DescriptionUse StructArray objects to work with MATLAB struct arrays To access a field for asingle element in the array use the field name To create a StructArray object callcreateStructArray

Class DetailsNamespace matlabdataBase class TypedArrayltStructgtInclude StructArrayhpp

Constructorsbull ldquoCopy Constructorsrdquo on page 1-96bull ldquoCopy Assignment Operatorsrdquo on page 1-97bull ldquoMove Constructorsrdquo on page 1-97bull ldquoMove Assignment Operatorsrdquo on page 1-98

Copy Constructors

StructArray(const StructArrayamp rhs)

StructArray(const Arrayamp rhs)

Creates a shared data copy of a StructArray object

const StructArrayamp rhs Value to copy

1 API Reference

1-96

const Arrayamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Copy Assignment Operators

StructArrayamp operator=(const StructArrayamp rhs)

StructArrayamp operator=(const Arrayamp rhs)

Assigns a shared data copy to a StructArray object

const StructArrayamp rhs Value to copyconst Arrayamp rhs Value specified as ArrayTypeSTRUCT object

StructArrayamp Updated instance

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

Move Constructors

StructArray(StructArrayampamp rhs)

StructArray(Arrayampamp rhs)

Moves contents of a StructArray object to a new instance

StructArrayampamp rhs Value to moveArrayampamp rhs Value specified as ArrayTypeSTRUCT object

InvalidArrayTypeException

Type of input Array is not ArrayTypeSTRUCT

matlabdataStructArray

1-97

Move Assignment OperatorsStructArrayamp operator=(StructArrayampamp rhs)

Assigns the input to this StructArray object

StructArrayampamp rhs Value to move

StructArrayamp Updated instance

None

Destructor~StructArray()

Description

Free memory for StructArray object

Member Functionsbull ldquogetFieldNamesrdquo on page 1-98bull ldquogetNumberOfFieldsrdquo on page 1-99

getFieldNamesRangeltForwardIterator MatlabFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enable access to allfields in StructArray object

None

1 API Reference

1-98

getNumberOfFieldssize_t getNumberOfFields() const

size_t Number of fields

None

ExamplesCreate StructArray

Suppose that you have the following MATLAB structure

s = struct(loc east west data [1 2 3] [4 5 6 7 8])

Create a variable containing the data for loc east

val = s(1)data

The following C++ code creates these variables

include MatlabDataArrayhpp

int main() using namespace matlabdata ArrayFactory factory

StructArray S = factorycreateStructArray( 12 loc data ) S[0][loc] = factorycreateCharArray(east) S[0][data] = factorycreateArrayltuint8_tgt( 1 3 1 2 3 ) S[1][loc] = factorycreateCharArray(west) S[1][data] = factorycreateArrayltdoublegt( 1 5 4 5 6 7 8 )

ReferenceltArraygt val = S[0][data] return 0

bull ldquoCreate Structure Array and Send to MATLABrdquo

matlabdataStructArray

1-99

See AlsoMATLABFieldIdentifier | Range | createStructArray

TopicsldquoCreate Structure Array and Send to MATLABrdquo

Introduced in R2017b

1 API Reference

1-100

matlabdataReferenceltStructArraygtC++ class to get reference to StructArray

DescriptionThe StructArrayExt class extends the APIs available to a reference to a StructArray

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

Member Functionsbull ldquogetFieldNamesrdquo on page 1-101bull ldquogetNumberOfFieldsrdquo on page 1-101

getFieldNamesRangeltForwardIterator MATLABFieldIdentifier constgt getFieldNames() const

RangeltForwardIteratorMatlabFieldIdentifierconstgt

Contains begin and end which enables access to allfields in StructArray object

None

getNumberOfFieldssize_t getNumberOfFields() const

matlabdataReferenceltStructArraygt

1-101

size_t Number of fields

None

See AlsoReferenceltTypedArrayltTgtgt | StructArray

Introduced in R2017b

1 API Reference

1-102

matlabdataStructElement type for MATLAB struct arrays

DescriptionStruct is the element type for a StructArray object

Class DetailsNamespace matlabdataInclude Structhpp

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-103bull ldquoEnd Iteratorsrdquo on page 1-103

Begin Iteratorsconst_iterator begin() const

const_iterator cbegin() const

const_iterator Iterator to beginning of list of fields specified asTypedIteratorltArray constgt

None

End Iteratorsconst_iterator end() const

const_iterator cend() const

matlabdataStruct

1-103

const_iterator Iterator to end of list of fields specified asTypedIteratorltArray constgt

None

Indexing Operators

operator[]Array operator[](stdstring idx) const

Enables [] indexing on a StructArray object Indexing is 0-based

stdstring idx Field name

Array Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in this StructArray

See AlsoldquocreateStructArrayrdquo on page 1-17 | StructArray

Introduced in R2017b

1 API Reference

1-104

matlabdataReferenceltStructgtC++ class to get reference to element of StructArray

DescriptionUse the ReferenceltStructgt class to access an element of a StructArray

Class DetailsNamespace matlabdataInclude StructRefhpp

Indexing Operators

operator[]ReferenceltArraygt operator[](stdstring idx)

Array operator[](stdstring idx) const

Index into the Struct with a field name

stdstring idx Field name

ReferenceltArraygt Reference to Array found at specified fieldArray Shared copy of Array found at specified field

InvalidFieldNameException

Field does not exist in the struct

matlabdataReferenceltStructgt

1-105

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-106bull ldquoEnd Iteratorsrdquo on page 1-106

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of list of fields specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

1 API Reference

1-106

Cast

Struct()operator Struct() const

Create a shared copy of the Struct

Struct Shared copy

None

See Also

Introduced in R2017b

matlabdataReferenceltStructgt

1-107

matlabdataTypedArrayltTgtTemplated C++ class to access array data

DescriptionThe templated TypedArray class provides typesafe APIs to handle all array types(except sparse arrays) inside an array This class defines the following iterator types

using iterator = TypedIteratorltTgt

using const_iterator = TypedIteratorltT constgt

Class DetailsNamespace matlabdataBase class matlabdataArrayInclude TypedArrayhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_t

1 API Reference

1-108

uint64_tchar16_tboolstdcomplexltdoublegtstdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorrdquo on page 1-109bull ldquoCopy Assignment Operatorrdquo on page 1-110bull ldquoMove Constructorrdquo on page 1-110bull ldquoMove Assignment Operatorrdquo on page 1-111

Copy ConstructorTypedArray(const TypedArrayltTgtamp rhs)

TypedArray(const Arrayamp rhs)

Creates a shared data copy of the input

matlabdataTypedArrayltTgt

1-109

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Copy Assignment Operator

TypedArrayltTgtamp operator=(const TypedArrayltTgtamp rhs)

TypedArrayltTgtamp operator=(const Arrayamp rhs)

Assigns a shared data copy of the input to this TypedArrayltTgt

const TypedArrayltTgtamp rhs Value to be copiedconst Arrayamp rhs Value specified as matlabdataArray object

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Move Constructor

TypedArray(TypedArrayltTgtampamp rhs)

TypedArray(Arrayampamp rhs)

Moves contents of the input to a new instance

TypedArrayltTgtampamp rhs Value to be movedArrayampamp rhs Value specified as matlabdataArray object

InvalidArrayTypeException

Type of input does not match

1 API Reference

1-110

Move Assignment Operator

TypedArrayltTgtamp operator=(TypedArrayltTgtampamp rhs)

TypedArrayltTgtamp operator=(Arrayampamp rhs)

Moves the input to this TypedArrayltTgt object

TypedArrayltTgtampamp rhs Value to move

TypedArrayltTgtamp Updated instance

InvalidArrayTypeException

Type of input Array does not match the type forTypedArrayltTgt

Destructorvirtual ~TypedArray()

Iteratorsbull ldquoBegin Iteratorsrdquo on page 1-111bull ldquoEnd Iteratorsrdquo on page 1-112

Begin Iterators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

matlabdataTypedArrayltTgt

1-111

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

Indexing Operators

operator[]ArrayElementTypedRefltT stdis_constltTgtvaluegt operator[](size_tidx)

ArrayElementTypedRefltT truegt operator[](size_t idx) const

Enables [] indexing on a TypedArray Indexing is 0-based

size_t idx First array index

1 API Reference

1-112

ArrayElementTypedRefltTstdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltTtruegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

None

Suppose that you have a cell array c Assign a value to a ReferenceltArraygt object andcall the member function getType

ReferenceltArraygt r = c[0][0]auto t = c[0][0]getType

Member Functions

releasebuffer_ptr_tltTgt release()

Release the underlying buffer from the Array If the Array is shared a copy of the bufferis made otherwise no copy is made After the buffer is released the array contains noelements

buffer_ptr_tltTgt A unique_ptr with the data pointer

InvalidArrayTypeException

This TypedArray does not support releasing the buffer

matlabdataTypedArrayltTgt

1-113

ExamplesAssign Values to Array Elements

Create an array equivalent to the MATLAB array [1 2 3 4] then replace eachelement of the array with a single value

include MatlabDataArrayhpp

int main() matlabdataArrayFactory factory Create an array equivalent to the MATLAB array [1 2 3 4] matlabdataTypedArrayltdoublegt D = factorycreateArrayltdoublegt( 22 1324 ) Change the values for (autoamp elem D) elem = 55 return 0

bull ldquoBring Result of MATLAB Calculation Into C++rdquo

See AlsoArray | ArrayType

TopicsldquoBring Result of MATLAB Calculation Into C++rdquo

Introduced in R2017b

1 API Reference

1-114

matlabdataReferenceltTypedArrayltTgtgtC++ class to get reference to TypedArray

DescriptionThe ReferenceltTypedArrayltTgtgt class extends the APIs available to a reference to anArray It derives from the ReferenceltArraygt class and provides iterators and type-safe indexing ReferenceltTypedArrayltTgtgt is not thread-safe - do not pass referencesto TypedArray objects between threads

TypedArrayRef is defined in TypedArrayRefhpp as

template lttypename Tgtusing TypedArrayRef = ReferenceltTypedArrayltTgtgt

Class DetailsNamespace matlabdataBase class ReferenceltArraygtInclude TypedArrayRefhpp

ConstructorReference(const ReferenceltArraygtamp rhs)

Description

Create a ReferenceltTypedArrayltTgtgt object from a ReferenceltArraygt object

Parametersconst ReferenceltArraygtamprhs

Value to copy

matlabdataReferenceltTypedArrayltTgtgt

1-115

ThrowsTypeMismatchException Element of Array does not match ltTgt

Iteratorsbull ldquoBegin Interatorsrdquo on page 1-116bull ldquoEnd Iteratorsrdquo on page 1-116

Begin Interators

iterator begin()

const_iterator begin() const

const_iterator cbegin() const

iterator Iterator to beginning of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

None

End Iterators

iterator end()

const_iterator end() const

const_iterator cend() const

iterator Iterator to end of array specified asTypedIteratorltTgt

const_iterator Iterator specified as TypedIteratorlttypenamestdadd_constltTgttypegt

1 API Reference

1-116

None

Indexing Operators

operator[]ArrayElementTypedRefltarr_elem_type stdis_constltTgtvaluegtoperator[](size_t idx)

ArrayElementTypedRefltarr_elem_type truegt operator[](size_t idx)const

Enables [] indexing on a reference to an Array Indexing is 0-based

size_t idx First array index

ArrayElementTypedRefltarr_elem_typestdis_constltTgtvaluegt

Temporary object containing the index specified If typeT is const then the return value allows the element ofthe array to be retrieved but not modified Otherwisethe element can be modified or retrieved

ArrayElementTypedRefltarr_elem_type truegt

Temporary object containing the index specified Thereturn value allows the element of the array to beretrieved but not modified

InvalidFieldNameException

Field name is invalid for a struct

Other Operators

operator=ReferenceltTypedArrayltTgtgtamp operator= (TypedArrayltTgt rhs)

matlabdataReferenceltTypedArrayltTgtgt

1-117

Assign a TypedArray to an element of the referenced Array The Array being indexedmust be non-const

TypedArrayltTgt rhs Value to assign

ReferenceltTypedArrayltTgtgtamp

Updated instance

None

See Also

Introduced in R2017b

1 API Reference

1-118

matlabdataTypedIteratorltTgtTemplated C++ class to provide random access iterator

DescriptionTypedIterator is the return type of all begin and end functions that support randomaccess

Class DetailsNamespace matlabdataInclude TypedIteratorhpp

Template ParametersT Type of element referred to

Template Instantiationsdoublefloatint8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_tchar16_tboolstdcomplexltdoublegt

matlabdataTypedIteratorltTgt

1-119

stdcomplexltfloatgtstdcomplexltint8_tgtstdcomplexltuint8_tgtstdcomplexltint16_tgtstdcomplexltuint16_tgtstdcomplexltint32_tgtstdcomplexltuint32_tgtstdcomplexltint64_tgtstdcomplexltuint64_tgtmatlabdataArraymatlabdataStructmatlabdataEnumerationmatlabdataMATLABString

Constructorsbull ldquoCopy Constructorsrdquo on page 1-120bull ldquoCopy Assignment Operatorsrdquo on page 1-121bull ldquoMove Constructorsrdquo on page 1-121bull ldquoMove Assignment Operatorsrdquo on page 1-121

Copy Constructors

TypedIterator(const TypedIteratorltTgtamp rhs)

Creates a shared data copy of a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

None

1 API Reference

1-120

Copy Assignment OperatorsTypedIteratorltTgtamp operator=(const TypedIteratorltTgtamp rhs)

Assigns a shared data copy to a TypedIterator object

const TypedIteratorltTgtamprhs

Value to copy

TypedIteratorltTgtamp Updated instance

None

Move ConstructorsTypedIterator(TypedIteratorltTgt ampamprhs)

Moves contents of a TypedIterator object to a new instance

TypedIteratorltTgtampamp rhs Value to move

None

Move Assignment OperatorsTypedIteratorltTgtamp operator=(TypedIteratorltTgtampamp rhs)

Assigns the input to this TypedIterator object

TypedIteratorltTgtampamp rhs Value to move

TypedIteratorltTgtamp Updated instance

None

matlabdataTypedIteratorltTgt

1-121

Other Operatorsbull ldquooperator++rdquo on page 1-122bull ldquooperator--rdquo on page 1-122bull ldquooperator++rdquo on page 1-123bull ldquooperator--rdquo on page 1-123bull ldquooperator+=rdquo on page 1-123bull ldquooperator-=rdquo on page 1-124bull ldquooperator=rdquo on page 1-124bull ldquooperatorltrdquo on page 1-124bull ldquooperatorgtrdquo on page 1-125bull ldquooperatorlt=rdquo on page 1-125bull ldquooperatorgt=rdquo on page 1-125bull ldquooperator+rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperator-rdquo on page 1-126bull ldquooperatorrdquo on page 1-127bull ldquooperator-gtrdquo on page 1-127bull ldquooperator[]rdquo on page 1-127

operator++TypedIteratorltTgtamp operator++()

Pre-increment operator

TypedIteratorltTgtamp Original iterator

None

operator--TypedIteratorltTgtamp operator--()

1 API Reference

1-122

Pre-decrement operator

TypedIteratorltTgtamp Original iterator

None

operator++TypedIteratorltTgt operator++(int)

Post-increment operator

TypedIteratorltTgt Copy of original iterator

None

operator--TypedIteratorltTgt operator--(int)

Post-decrement operator

TypedIteratorltTgt Copy of original iterator

None

operator+=TypedIteratorltTgtamp operator+=(difference_type d)

Addition assignment operator

difference_type d Amount to add specified as stdptrdiff_t

matlabdataTypedIteratorltTgt

1-123

TypedIteratorltTgtamp Updated instance

None

operator-=TypedIteratorltTgtamp operator-=(difference_type d)

Subtraction assignment operator

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgtamp Updated instance

None

operator=bool operator=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if iterators do not point to same element

None

operatorltbool operatorlt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

1 API Reference

1-124

bool Returns true if left-side iterator is less than right-sideiterator

operatorgtbool operatorgt(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than right-side iterator

operatorlt=bool operatorlt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is less than or equal toright-side iterator

None

operatorgt=bool operatorgt=(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if left-side iterator is greater than orequal to right-side iterator

None

matlabdataTypedIteratorltTgt

1-125

operator+TypedIteratorltTgt operator+(difference_type d) const

Creates an iterator that is added to this one by the amount passed in

difference_type d Amount to add specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-TypedIteratorltTgt operator-(difference_type d) const

Creates an iterator that is decremented from this one by the amount passed in

difference_type d Amount to subtract specified as stdptrdiff_t

TypedIteratorltTgt Updated instance

None

operator-difference_type operator-(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

difference_type Difference between iterators specified asstdptrdiff_t

None

1 API Reference

1-126

operatorreference operator() const

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator-gtpointer operator-gt()

pointer Pointer to element pointed to by this iterator specifiedas

bull T for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

operator[]reference operator[](const size_tamp rhs) const

Get a reference using a linear index

reference Element pointed to by this iterator specified as

bull Tamp for arithmetic typesbull ReferenceltTgt for non-arithmetic types

None

matlabdataTypedIteratorltTgt

1-127

Free Function

operator==bool operator==(const TypedIteratorltTgtamp rhs) const

const TypedIteratorltTgtamprhs

Iterator to compare

bool Returns true if both iterators point to same element

None

See Also

Introduced in R2017b

1 API Reference

1-128

matlabdataapply_visitorCall Visitor class on arrays

Descriptionauto apply_visitor(Array a V visitor) dispatch to visitor class operationsbased on array type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersmatlabdataArray a

The matlabdataArray to operate on with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

matlabdataapply_visitor

1-129

matlabdataapply_visitor_refCall Visitor class on array references

Descriptionauto apply_visitor_ref(const ArrayRefamp a V visitor) dispatch to visitorclass operations based on array reference type

IncludeNamespace matlabdataInclude ArrayVisitorshpp

ParametersconstmatlabdataArrayRefamp a

A matlabdataArrayRef reference to the array to operateon with the visitor class

visitor class V The user-supplied visitor class

Return Valueauto Outputs returned by the visitor

See Also

TopicsldquoOperate on C++ Arrays Using Visitor Patternrdquo

Introduced in R2017b

1 API Reference

1-130

matlabengineMATLABEngineEvaluate MATLAB functions from C++ program

DescriptionThe matlabengineMATLABEngine class uses a MATLAB process as acomputational engine for C++ This class provides an interface between the C++language and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom C++ programs

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Factory MethodsThe matlabengineMATLABEngine class provides methods to start MATLAB and toconnect to a shared MATLAB session synchronously or asynchronously

bull matlabenginestartMATLAB mdash Start MATLAB synchronouslybull matlabenginestartMATLABAsync mdash Start MATLAB asynchronouslybull matlabengineconnectMATLAB mdash Connect to shared MATLAB session

synchronouslybull matlabengineconnectMATLABAsync mdash Connect to shared MATLAB session

asynchronously

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -h

matlabengineMATLABEngine

1-131

bull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup OptionsrdquoFor an example of how to use MATLAB startup options when starting engineapplications see ldquoStart MATLAB with Startup Optionsrdquo

Method Summary

Member Functionsldquofevalrdquo on page 1-133

Evaluate MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-136

Evaluate MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-138 Evaluate MATLAB statement as a string synchronouslyldquoevalAsyncrdquo on page1-139

Evaluate MATLAB statement as a string asynchronously

ldquogetVariablerdquo onpage 1-140

Get variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-141

Get variable from the MATLAB base workspace asynchronously

ldquosetVariablerdquo onpage 1-142

Put variable into the MATLAB base workspace synchronously

ldquosetVariableAsyncrdquoon page 1-142

Put variable into the MATLAB base workspace asynchronously

ldquogetPropertyrdquo onpage 1-143

Get object property value

ldquogetPropertyAsyncrdquoon page 1-144

Get object property value asynchronously

1 API Reference

1-132

ldquosetPropertyrdquo onpage 1-145

Set object property value

ldquosetPropertyAsyncrdquoon page 1-146

Set object property value asynchronously

Member Function Details

fevalstdvectorltmatlabdataArraygt feval(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

matlabdataArray feval(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

ResultType feval(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs )

ResultType feval(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB functions with input arguments synchronously Use feval when youwant to pass arguments from C++ to MATLAB and when you want to return a resultfrom MATLAB to C++

Inputs and outputs can be types defined by the MATLAB Data Array API or can benative C++ types

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

matlabengineMATLABEngine

1-133

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

stdvectorltmatlabdataArraygt

Outputs returned from MATLAB function

matlabdataArray Single output returned from MATLAB functionResultType Output returned from MATLAB function as a user-specified

type Can be a stdtuple if returning multiple arguments

matlabengineMATLABNotAvailableException

The MATLAB session is not available

1 API Reference

1-134

matlabengineMATLABExecutionException

There is a MATLAB runtime error in the function

matlabengineTypeConversionException

The result of a MATLAB function cannot be converted tothe specified type

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

This example passes an array of numeric values to a MATLAB function The codeperforms these steps

bull Creates a matlabdataArray with the dimensions 2-by-3 from a vector ofnumeric values of type double

bull Starts a shared MATLAB sessionbull Passes the data array to the MATLAB sqrt function and returns the result to C++

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabengine

stdvectorltdoublegt cppData 4 8 12 16 20 24

Create a 2-by-3 matlab data array matlabdataArrayFactory factory auto inputArray = factorycreateArray( 2 3 cppDatacbegin() cppDatacend())

Start MATLAB engine stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Pass data array to MATLAB sqrt function And return results auto result = matlabPtr-gtfeval(usqrt inputArray)

When calling feval using native C++ types the input arguments are restricted to scalarvalues For example this code returns the square root of a scalar value

include MatlabEnginehppusing namespace matlabengine

Start MATLAB engine synchronously stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Call sqrt function double result = matlabPtr-gt fevalltdoublegt(usqrt double(27))

matlabengineMATLABEngine

1-135

For functions that return multiple output arguments you can use the MATLAB data APIor if using C++ types a stdtuple For an example see ldquoCall Function with Native C++ Typesrdquo

ldquoCall MATLAB Functions from C++rdquo

ldquoMATLAB Data APIrdquo

fevalAsyncFutureResultltstdvectorltmatlabdataArraygtgt fevalAsync(const matlabengineString ampfunction const size_t numReturned const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const stdvectorltmatlabdataArraygt ampargs const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltmatlabdataArraygt fevalAsync(const matlabengineString ampfunction const matlabdataArray amparg const stdshared_ptrltmatlabengineStreamBuffergt amp output = stdshared_ptrltmatlabengineStreamBuffergt() const stdshared_ptrltmatlabengineStreamBuffergt amp error = stdshared_ptrltmatlabengineStreamBuffergt())

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction const stdshared_ptrltmatlabengineStreamBuffergt ampoutput const stdshared_ptrltmatlabengineStreamBuffergt amperror RhsArgsampamp rhsArgs)

FutureResultltResultTypegt fevalAsync(const matlabengineString ampfunction RhsArgsampamp rhsArgs)

Evaluate MATLAB function with input arguments and returned values asynchronously

constmatlabengineString ampfunction

Name of the MATLAB function or script to evaluate

const size_tnumReturned

Number of returned values

conststdvectorltmatlabdataArraygt ampargs

Multiple input arguments to pass to the MATLAB function ina stdvector The vector is converted to a column array inMATLAB

1 API Reference

1-136

constmatlabdataArrayarg

Single input argument to pass to the MATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt ampoutput =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the standard output from theMATLAB function

conststdshared_ptrltmatlabengineStreamBuffergt amperror =stdshared_ptrltmatlabengineStreamBuffergt()

Stream buffer used to store the error message from theMATLAB function

RhsArgsampamprhsArgs

Native C++ data types used for function inputs feval acceptsscalar inputs of these C++ data types bool int8_tint16_t int32_t int64_t uint8_t uint16_tuint32_t uint64_t float double

FutureResult A FutureResult object used to get the result of calling theMATLAB function

None

This example passes the scalar double 127 to the MATLAB sqrt functionasynchronously The FutureResult is then used to get the result

include MatlabDataArrayhppinclude MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() matlabdataArrayFactory factory matlabdataArray argument = factorycreateScalarltdoublegt(127) FutureResultltmatlabdataArraygt future = matlabPtr-gt fevalAsync(convertUTF8StringToUTF16String(sqrt) stdmove(argument))

matlabengineMATLABEngine

1-137

matlabdataTypedArrayltdoublegt result = futureget()

ldquoCall Function Asynchronouslyrdquo

evalvoid eval(const matlabengineString ampstatement const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string synchronously

constmatlabengineString ampstatement

MATLAB statement to evaluate

conststdshared_ptrltmatlabengineStreamBuffergtampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergtamperror

Stream buffer used to store the error message from theMATLAB command

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

There is a runtime error in the MATLAB statement

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB statement

This example evaluates the following MATLAB statement

a = sqrt(127)

1 API Reference

1-138

The statement creates the variable a in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

evalAsyncFutureResultltvoidgt evalAsync(const matlabengineString ampstr const stdshared_ptrltmatlabengineStreamBuffergt ampoutput = stdshared_ptrltmatlabengineStreamBuffergt () const stdshared_ptrltmatlabengineStreamBuffergt amperror = stdshared_ptrltmatlabengineStreamBuffergt ())

Evaluate a MATLAB statement as a string asynchronously

const Stringamp str MATLAB statement to evaluateconststdshared_ptrltmatlabengineStreamBuffergt ampoutput

Stream buffer used to store the standard output from theMATLAB statement

conststdshared_ptrltmatlabengineStreamBuffergt amperror

Stream buffer used to store the error message from theMATLAB command

FutureResult A FutureResult object used to wait for the completion of theMATLAB statement

None

This example evaluates the following MATLAB statement asynchronouslya = sqrt(127)

The statement creates the variable a in the MATLAB base workspace

matlabengineMATLABEngine

1-139

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltvoidgt future = matlabPtr-gt evalAsync(convertUTF8StringToUTF16String(a = sqrt(127)))

ldquoEvaluate MATLAB Statements from C++rdquo

getVariablematlabdataArray getVariable(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace

constmatlabengineStringamp varName

Name of a variable in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variablefrom For more information see global

matlabdataArray

Variable obtained from the MATLAB base or global workspace

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The requested variable does not exist in the specifiedMATLAB base or global workspace

This example gets a variable named varName from the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray varName = matlabPtr-gtgetVariable(convertUTF8StringToUTF16String(varName))

1 API Reference

1-140

ldquoPass Variables from MATLAB to C++rdquo

getVariableAsyncFutureResultltmatlabdataArraygt getVariableAsync(const matlabengineString ampvarName WorkspaceType workspaceType = WorkspaceTypeBASE)

Get a variable from the MATLAB base or global workspace asynchronously

constmatlabengineStringamp varName

Name of the variable in MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

MATLAB workspace (BASE or GLOBAL) to get the variable fromFor more information see global

FutureResult A FutureResult object that you can use to get the variableobtained from the MATLAB workspace as amatlabdataArray

None

This example gets a variable named varName from the MATLAB base workspaceasynchronously

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()FutureResultltmatlabdataArraygt future = matlabPtr-gt getVariableAsync(convertUTF8StringToUTF16String(varName))matlabdataArray varName = futureget()

ldquoPass Variables from MATLAB to C++rdquo

matlabengineMATLABEngine

1-141

setVariablevoid setVariable(const matlabengineString ampvarName const matlabdataArray ampvar WorkspaceType workspaceType = WorkspaceTypeBASE)

Put a variable into the MATLAB base or global workspace If a variable with the samename exists in the MATLAB workspace setVariable overwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

matlabengineMATLABNotAvailableException

The MATLAB session is not available

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from C++ to MATLABrdquo

setVariableAsyncFutureResultltvoidgt setVariableAsync(const matlabengineString ampvarName const matlabdataArray var WorkspaceType workspaceType = WorkspaceTypeBASE)

1 API Reference

1-142

Put a variable into the MATLAB base or global workspace asynchronously If a variablewith the same name exists in the MATLAB base workspace setVariableAsyncoverwrites it

constmatlabengineStringamp varName

Name of the variable to create in the MATLAB workspace

constmatlabdataArray var

Value of the variable to create in the MATLAB workspace

WorkspaceTypeworkspaceType =WorkspaceTypeBASE

Put the variable in the MATLAB BASE or GLOBAL workspaceFor more information see global

None

This example puts the variable named data in the MATLAB base workspace

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArray data = factorycreateArrayltdoublegt( 1 3 4 8 6 )FutureResultltvoidgt future = matlabPtr-gt setVariableAsync(convertUTF8StringToUTF16String(data) data)

ldquoPass Variables from MATLAB to C++rdquo

getPropertymatlabdataArray getProperty(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property

matlabengineMATLABEngine

1-143

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

matlabdataArray

Value of the named property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetProperty returns the exception messageproperty value as a matlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(try surf(4) catch me end))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))matlabdataCharArray message = matlabPtr-gt getProperty(mException convertUTF8StringToUTF16String(message))stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

getPropertyAsyncFutureResultltmatlabdataArraygt getPropertyAsync(const matlabdataArray ampobject const String amppropertyName)

Get the value of an object property asynchronously

1 API Reference

1-144

constmatlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property

FutureResult FutureResult object that is used to synchronize the operation

None

This example evaluates a MATLAB statement in a trycatch block usingMATLABEngineeval The MATLABEnginegetVariable member function returnsthe exception object MATLABEnginegetPropertyAsync returns a FutureResultthat you use to get the exception message property value as amatlabdataCharArray

include MatlabEnginehppusing namespace matlabengine

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabPtr-gteval(convertUTF8StringToUTF16String(trysurf(4)catch meend))matlabdataArray mException = matlabPtr-gt getVariable(convertUTF8StringToUTF16String(me))FutureResultltmatlabdataArraygt future = matlabPtr-gt getPropertyAsync(mException convertUTF8StringToUTF16String(message))matlabdataCharArray message = futureget()stdcout ltlt messages is ltlt messagetoAscii() ltlt stdendl

ldquoGet MATLAB Objects and Access Propertiesrdquo

setPropertyvoid setProperty(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property

matlabdataArray ampobject

MATLAB object

matlabengineMATLABEngine

1-145

const StringamppropertyName

Name of the property to set

constmatlabdataArray amppropertyValue

Value assigned to the property

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABExecutionException

The property does not exist

This example shows how to set a MATLAB object property It creates a MATLAB graphand returns the line handle object Setting the value of the line LineStyle property tothe character changes the property value of the line object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray()matlabPtr-gtsetProperty(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

setPropertyAsyncFutureResultltvoidgt setPropertyAsync(matlabdataArray ampobject const String amppropertyName const matlabdataArray amppropertyValue)

Set the value of an object property asynchronously

matlabdataArray ampobject

MATLAB object

const StringamppropertyName

Name of the property to set

1 API Reference

1-146

constmatlabdataArray amppropertyValue

Value assigned to the property

None

This example shows how to set a MATLAB object property asynchronously It creates aMATLAB graph and returns the line handle object Setting the line LineStyle propertyto the character changes the property value of the object in MATLAB and updates theline style of the graph

include MatlabEnginehppusing namespace matlabenginestdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()matlabdataArrayFactory factorymatlabdataArray yData = factorycreateArrayltdoublegt( 1 5 40 110 47 362 723 )matlabdataArray lineHandle = matlabPtr-gtfeval(convertUTF8StringToUTF16String(plot) yData)matlabdataCharArray lineStyle = factorycreateCharArray() FutureResultltvoidgt future = matlabPtr-gt setPropertyAsync(lineHandle convertUTF8StringToUTF16String(LineStyle) lineStyle)

ldquoSet Property on MATLAB Objectrdquo

See Also

Introduced in R2017b

matlabengineMATLABEngine

1-147

matlabengineconnectMATLABConnect to shared MATLAB session synchronously

Descriptionstdunique_ptrltMATLABEnginegt connectMATLAB()

stdunique_ptrltMATLABEnginegt connectMATLAB(constmatlabengineStringamp name)

Connect synchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-148

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to a MATLABEngine object

ExceptionsmatlabengineEngineException

Throws exception if function fails to connect to the specified MATLABsession

Examples

Connect to Shared MATLAB Session

Connect to a shared MATLAB session named my_matlab

stdunique_ptrltMATLABEnginegt matlabPrt = connectMATLAB(convertUTF8StringToUTF16String(my_matlab))

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineconnectMatlabAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

matlabengineconnectMATLAB

1-149

matlabengineconnectMATLABAsyncConnect to shared MATLAB session asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync()

FutureResultltstdunique_ptrltMATLABEnginegtgt connectMATLABAsync(constmatlabengineStringamp name)

Connect asynchronously to a shared MATLAB session on the local machine

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session The MATLAB desktop is not started

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconstmatlabengineStringamp name

Name of the shared MATLAB session

1 API Reference

1-150

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object that you can use to get the pointer to theMATLABEngine

Examples

Connect to Shared MATLAB Session Asynchronously

Connect to a shared MATLAB session named my_matlab asynchronously Use theFutureResult get method to retrieve the pointer to the MATLABEngine objectFutureResultsltstdunique_ptrltMATLABEnginegtgt future = connectMATLABAsync(convertUTF8StringToUTF16String(my_matlab))stdunique_ptrltMATLABEnginegt matlabPtr = futureget()

bull ldquoConnect C++ to Running MATLAB Sessionrdquo

See AlsomatlabengineconnectMatlab

TopicsldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

matlabengineconnectMATLABAsync

1-151

matlabengineconvertUTF8StringToUTF16StringConvert UTF-8 string to UTF-16 string

Descriptionstdbasic_stringltchar16_tgt convertUTF8StringToUTF16String(conststdstringamp utf8string)

Convert a UTF-8 string to a UTF-16 string Use this function to convert ASCII strings tomatlabengineString strings which are required by MATLAB C++ Enginefunctions

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdstringamputf8string

A UTF-8 string

Return Valuestdbasic_stringltchar16_tgt

A UTF-16 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-152

matlabengineTypeConversionException

The input type cannot be converted tostdbasic_stringltchar16_tgt

Examples

Convert String

Convert a UTF-8 string to a matlabengineString (UTF-16 string)

matlabengineString matlabStatement = convertUTF8StringToUTF16String(sqrt(127))

See AlsomatlabengineString |matlabengineconvertUTF16StringToUTF8String

Introduced in R2017b

matlabengineconvertUTF8StringToUTF16String

1-153

matlabengineconvertUTF16StringToUTF8StringConvert UTF-16 string to UTF-8 string

Descriptionstdstring convertUTF16StringToUTF8String(conststdbasic_stringltchar16_tgtamp utf16string)

Convert a UTF-16 string to a UTF-8 string

IncludeNamespace matlabengineInclude MatlabEnginehpp

Parametersconststdbasic_stringltchar16_tgtamputf16string

A UTF-16 string

Return Valuestdstring A UTF-8 string

ExceptionsmatlabengineOutofMemoryException

The function failed to allocate memory

1 API Reference

1-154

matlabengineTypeConversionException

The input type cannot be converted to stdstring

Examples

Convert String

Convert a matlabengineString (UTF-16 string) to a stdstring (UTF-8string)

matlabengineString matlabStatement = (usqrt(127))stdstring cmdString = convertUTF16StringToUTF8String(matlabStatement)

See AlsomatlabengineString |matlabengineconvertUTF8StringToUTF16String

Introduced in R2017b

matlabengineconvertUTF16StringToUTF8String

1-155

matlabenginefindMATLABFind shared MATLAB sessions synchronously

DescriptionstdvectorltStringgt findMATLAB()

Find all shared MATLAB sessions on the local machine

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValuestdvectorltStringgt

A vector of the names of all shared MATLAB sessions on the localmachine or an empty vector if no shared MATLAB sessions areavailable

ExceptionsmatlabengineEngineException

Throws exception if the call fails while searching for shared MATLABsessions

Examples

1 API Reference

1-156

Find Shared MATLAB Session Synchronously

stdvectorltStringgt names = findMATLAB()

See AlsomatlabenginefindMATLABAsync

Introduced in R2017b

matlabenginefindMATLAB

1-157

matlabenginefindMATLABAsyncFind shared MATLAB sessions asynchronously

DescriptionFutureResultltstdvectorltStringgtgt findMATLABAsync()

Find all shared MATLAB sessions on the local machine asynchronously

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersNone

Return ValueFutureResultltstdvectorltStringgtgt

A FutureResult object that you can use to get the names of sharedMATLAB sessions on the local machine

Examples

Find Shared MATLAB Session Asynchronously

Find the names of all shared MATLAB sessions on the local machine asynchronouslyUse the FutureResult get method to retrieve the names

1 API Reference

1-158

FutureResultltstdvectorltStringgtgt futureNames = findMATLABAsync()stdvectorltStringgt matlabSessions = futureNamesget()

See AlsomatlabenginefindMATLAB

Introduced in R2017b

matlabenginefindMATLABAsync

1-159

matlabengineFutureResultRetrieve result from asynchronous operation

DescriptionA future result is an object that you can use to retrieve the result of MATLAB functionsor statements The FutureResult class provides all member functions of the C++stdfuture class

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Functions Delegated to stdfutureoperator= share get wait wait_for wait_until

1 API Reference

1-160

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement You cannot cancelasynchronous operations that use matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution had already begun

bool Was command canceled if execution had already begun

bool flag = futurecancel()

No exceptions thrown

matlabengineFutureResult

1-161

See Also

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

1 API Reference

1-162

matlabenginestartMATLABStart MATLAB synchronously

Descriptionstdunique_ptrltMATLABEnginegt startMATLAB(const stdvectorltStringgtampoptions = stdvectorltStringgt())

Start MATLAB synchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtampoptions

Options used to start MATLAB See ldquoSpecify Startup Optionsrdquo

Return Valuestdunique_ptrltMATLABEnginegt

Pointer to the MATLABEngine object

matlabenginestartMATLAB

1-163

ExceptionsmatlabengineEngineException

MATLAB failed to start

Examples

Start MATLAB Synchronously

Start MATLAB synchronously and return a unique pointer to the MATLABEngine object

stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB()

Start MATLAB with Startup Options

Start MATLAB with the -nojvm option and return a unique pointer to theMATLABEngine object

stdvectorltStringgt optionVecoptionVecpush_back(convertUTF8StringToUTF16String(-nojvm))stdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB(optionVec)

bull ldquoStart MATLAB Sessions from C++rdquo

See AlsomatlabengineMATLABEngine | matlabenginestartMATLABAsync

TopicsldquoStart MATLAB Sessions from C++rdquo

Introduced in R2017b

1 API Reference

1-164

matlabenginestartMATLABAsyncStart MATLAB asynchronously

DescriptionFutureResultltstdunique_ptrltMATLABEnginegtgt startMATLABAsync(conststdvectorltStringgtamp options = stdvectorltStringgt())

Start MATLAB asynchronously in a separate process with optional MATLAB startupoptions

IncludeNamespace matlabengineInclude MatlabEnginehpp

ParametersconststdvectorltStringgtamp options

Startup options used to launch MATLAB

Return ValueFutureResultltstdunique_ptrltMATLABEnginegtgt

A FutureResult object used to get the pointer to theMATLABEngine

Examples

matlabenginestartMATLABAsync

1-165

Start MATLAB Asynchronously

Start MATLAB asynchronously and return a FutureResult object Use theFutureResult to get a pointer to the MATLABEngine objectFutureResultltstdunique_ptrltMATLABEnginegtgt matlabFuture = startMATLAB()stdunique_ptrltMATLABEnginegt matlabPtr = matlabFutureget()

bull ldquoSpecify Startup Optionsrdquo

See AlsomatlabenginestartMATLAB

TopicsldquoSpecify Startup Optionsrdquo

Introduced in R2017b

1 API Reference

1-166

matlabengineterminateEngineClientFree engine resources during runtime

Descriptionvoid matlabengineterminateEngineClient releases all MATLAB engineresources during runtime when you no longer need the MATLAB engine in yourapplication program

Note Programs cannot start a new MATLAB engine or connect to a shared MATLABsession after calling terminateEngineClient

IncludeNamespace matlabengineInclude MatlabEnginehpp

ExamplesTerminate the engine session to free resources Start MATLAB sessionstdunique_ptrltMATLABEnginegt matlabPtr = startMATLAB() Terminate MATLAB sessionmatlabengineterminateEngineClient()

See AlsomatlabenginestartMATLAB

Introduced in R2017b

matlabengineterminateEngineClient

1-167

matlabengineWorkspaceTypeType of MATLAB workspace

DescriptionThe matlabengineWorkspaceType enum class specifies the MATLAB workspaceto pass variables to or get variables fromBASE Variables scoped to the MATLAB base workspace

(command line and nonfunction scripts)GLOBAL Variables scoped to the MATLAB global workspace

(command line functions and scripts)

MATLAB scopes variables by workspace Variables that are scoped to the baseworkspace must be passed to functions as arguments Variables scoped to the globalworkspace can be accessed by any function that defines the specific variable name asglobal

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

ExamplesThis example

bull Connects to a shared MATLAB sessionbull Creates a matlabdataArray containing numeric values of type doublebull Puts the array in the MATLAB global workspaceinclude MatlabDataArrayhppinclude MatlabEnginehppinclude ltiostreamgt

static void putGlobalVar()

1 API Reference

1-168

using namespace matlabengine

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

Create matlab data array factory matlabdataArrayFactory factory

Create data variable matlabdataArray data = factorycreateArrayltdoublegt ( 1 5 40 110 47 362 723 )

Put data variable in MATLAB global workspace matlabPtr-gtsetVariable(convertUTF8StringToUTF16String(data) data WorkspaceTypeGLOBAL)

See AlsomatlabdataArrayFactory | matlabengineMATLABEngine |matlabengineconvertUTF8StringToUTF16String

TopicsldquoPass Variables from C++ to MATLABrdquoldquoPass Variables from MATLAB to C++rdquo

Introduced in R2017b

matlabengineWorkspaceType

1-169

matlabengineStringDefine UTF16 string

DescriptionType definition for stdbasic_stringltchar16_tgt

ExamplesThis example defines a variable containing the name of a shared MATLAB session Passthis string to the matlabengineconnectMATLAB function to connect to the namedsessionmatlabengineString session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

See AlsomatlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoMATLAB Engine API for C++rdquoldquoConnect C++ to Running MATLAB Sessionrdquo

Introduced in R2017b

1 API Reference

1-170

matlabengineStreamBufferDefine stream buffer

DescriptionType definition for stdbasic_streafbufltchar16_tgt

ExamplesThis example defines string buffers to return output from the evaluation of a MATLABfunction by the MATLABEngineeval member function This function uses a bufferderived from matlabengineStreamBuffer to return output from MATLAB to C++include MatlabEnginehppinclude MatlabDataArrayhppinclude ltiostreamgt

using namespace matlabengineusing SBuf = stdbasic_stringbufltchar16_tgt

void printFromBuf(const stdshared_ptrltSBufgt buf) Get text from buf auto text_ = buf-gtstr() stdcout ltlt ltlt convertUTF16StringToUTF8String(text_) ltlt ltlt stdendl

int main()

Create Array factory matlabdataArrayFactory factory

Connect to named shared MATLAB session started as matlab -r matlabengineshareEngine(myMatlabEngine) String session(convertUTF8StringToUTF16String(myMatlabEngine)) stdunique_ptrltMATLABEnginegt matlabPtr = connectMATLAB(session)

auto outBuf = stdmake_sharedltSBufgt() auto errBuf = stdmake_sharedltSBufgt()

matlabPtr-gteval(convertUTF8StringToUTF16String(matlabengineengineName) outBuf errBuf) printFromBuf(outBuf) printFromBuf(errBuf) return 0

matlabengineStreamBuffer

1-171

See AlsomatlabengineconnectMATLAB |matlabengineconvertUTF16StringToUTF8String |matlabengineconvertUTF8StringToUTF16String

TopicsldquoRedirect MATLAB Command Window Output to C++rdquo

Introduced in R2017b

1 API Reference

1-172

matlabengineSharedFutureResultRetrieve result from asynchronous operation as shared future

DescriptionA shared future result is an object that you use to retrieve the result of MATLABfunctions or statements any number of times

Class DetailsNamespace matlabengineInclude MatlabEnginehpp

Constructor SummaryCreate a FutureResult object using one of these asynchronous functions

bull Asynchronous member functions defined by matlabengineMATLABEnginebull matlabenginestartMATLABAsync

matlabengineconnectMATLABAsync andmatlabenginefindMATLABAsync

Method Summary

Member Functionsldquocancelrdquo on page 1-161

Cancel the operation held by the FutureResult object

Member Function Delegated to stdshared_futureoperator= get valid wait wait_for wait_until

matlabengineSharedFutureResult

1-173

matlabengineEngineException

Cannot start or connect to MATLAB session

matlabengineCancelException

Execution of command is canceled

matlabengineInterruptedException

Evaluation of command is interrupted

matlabengineMATLABNotAvailableException

The MATLAB session is not available

matlabengineMATLABSyntaxException

There is a syntax error in the MATLAB function

matlabengineMATLABExecutionException

MATLAB runtime error in the function

matlabengineTypeConversionException

The result from a MATLAB function cannot be convertedto the specified type

Method Details

cancelbool FutureResultcancel(bool allowInterrupt = true)

Cancel the evaluation of the MATLAB function or statement

Note that you cannot cancel asynchronous start connection or find operations which areinitiated using these functions matlabenginestartMATLABAsyncmatlabengineconnectMATLABAsync or matlabenginefindMATLABAsync

boolallowInterrupt

If false do not interrupt if execution has already begun

bool True if the MATLAB command can be canceled

bool flag = futurecancel()

None

1 API Reference

1-174

See AlsomatlabengineFutureResult

TopicsldquoCall Function Asynchronouslyrdquo

Introduced in R2017b

matlabengineSharedFutureResult

1-175

commathworksengineMatlabEngine classPackage commathworksengine

Java class using MATLAB as a computational engine

DescriptionThe commathworksengineMatlabEngine class uses a MATLAB process as acomputational engine for Javareg This class provides an interface between the Javalanguage and MATLAB enabling you to evaluate MATLAB functions and expressionsfrom Java

Constructor SummaryThe MatlabEngine class provides static methods to start MATLAB and to connect to ashared MATLAB session synchronously or asynchronously Only these static methodscan instantiate this class

bull Start MATLAB synchronously mdash ldquostartMatlabrdquo on page 1-178bull Connect to shared MATLAB session synchronously mdash ldquoconnectMatlabrdquo on page 1-180bull Start MATLAB asynchronously mdash ldquostartMatlabAsyncrdquo on page 1-179bull Connect to shared MATLAB session asynchronously mdash ldquoconnectMatlabAsyncrdquo on

page 1-181

Unsupported Startup OptionsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -n

1 API Reference

1-176

bull -ebull -softwareopenglbull -logfile

For information on MATLAB startup options see ldquoCommonly Used Startup Optionsrdquo

Method Summary

Static MethodsldquostartMatlabrdquo onpage 1-178

Start MATLAB synchronously

ldquostartMatlabAsyncrdquoon page 1-179

Start MATLAB asynchronously

ldquofindMatlabrdquo onpage 1-179

Find all available shared MATLAB sessions from a local machinesynchronously

ldquofindMatlabAsyncrdquoon page 1-180

Find all available shared MATLAB sessions from a local machineasynchronously

ldquoconnectMatlabrdquo onpage 1-180

Connect to a shared MATLAB session on a local machinesynchronously

ldquoconnectMatlabAsyncrdquo on page 1-181

Connect to a shared MATLAB session on a local machineasynchronously

Member VariableNULL_WRITER Use a writer that ignores the contents from the MATLAB

command window

Member Functionsldquofevalrdquo on page 1-182

Evaluate a MATLAB function with arguments synchronously

ldquofevalAsyncrdquo onpage 1-183

Evaluate a MATLAB function with arguments asynchronously

ldquoevalrdquo on page 1-184 Evaluate a MATLAB expression as a string synchronously

commathworksengineMatlabEngine class

1-177

ldquoevalAsyncrdquo on page1-185

Evaluate a MATLAB expression as a string asynchronously

ldquogetVariablerdquo onpage 1-186

Get a variable from the MATLAB base workspace synchronously

ldquogetVariableAsyncrdquoon page 1-187

Get a variable from the MATLAB base workspace asynchronously

ldquoputVariablerdquo onpage 1-187

Put a variable into the MATLAB base workspace synchronously

ldquoputVariableAsyncrdquoon page 1-188

Put a variable into the MATLAB base workspace asynchronously

ldquodisconnectrdquo on page1-188

Disconnect from the current MATLAB session synchronously

ldquodisconnectAsyncrdquoon page 1-189

Disconnect from the current MATLAB session asynchronously

ldquoquitrdquo on page 1-189 Force the shutdown of the current MATLAB sessionsynchronously

ldquoquitAsyncrdquo on page1-189

Force the shutdown of the current MATLAB sessionasynchronously

ldquocloserdquo on page 1-190

Disconnect or terminate the current MATLAB session

Method Details

startMatlabstatic MatlabEngine startMatlab(String[] options)

static MatlabEngine startMatlab()

Start MATLAB synchronously

String[] options Startup options used to start MATLAB engine For options seeldquoStartup and Shutdownrdquo

1 API Reference

1-178

Instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start

MatlabEngine engine = MatlabEnginestartMatlab()

ldquoStart and Close MATLAB Session from Javardquo

startMatlabAsyncstatic FutureltMatlabEnginegt startMatlabAsync(String[] options)

static FutureltMatlabEnginegt startMatlabAsync()

Start MATLAB asynchronously

String[] options Startup options used to start MATLAB For options seeldquoStartup and Shutdownrdquo

Instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEnginestartMatlabAsync()

ldquoStart and Close MATLAB Session from Javardquo

findMatlabstatic String[] findMatlab()

Find all shared MATLAB sessions on the local machine synchronously

commathworksengineMatlabEngine class

1-179

An array of the names of all shared MATLAB sessions on the local machine or an emptyvector if there are no shared MATLAB sessions available on the local machine

commathworksengineEngineException

If there is a failure during the search for MATLAB sessions

String[] engines = MatlabEnginefindMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

findMatlabAsyncstatic FutureltSting[]gt findMatlabAsync()

Find all shared MATLAB sessions on local machine asynchronously

An instance of FutureltString[]gt

FutureltString[]gt future = MatlabEnginefindMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabstatic MatlabEngine connectMatlab(String name)

static MatlabEngine connectMatlab()

Connect to a shared MATLAB session on local machine synchronously

bull If you specify the name of a shared MATLAB session but the engine cannot find asession with that name the engine throws an exception

bull If you do not specify a name and there is no shared MATLAB session available theengine starts a new shared MATLAB session with default options

1 API Reference

1-180

bull If you do not specify a name and there are shared MATLAB sessions available theengine connects to the first available session

String name Name of the shared MATLAB session Use ldquofindMatlabrdquo on page1-179 to get the names of shared MATLAB sessions

An instance of MatlabEngine

commathworksengineEngineException

MATLAB fails to start or connect

MatlabEngine engine = MatlabEngineconnectMatlab()

ldquoConnect Java to Running MATLAB Sessionrdquo

connectMatlabAsyncstatic FutureltMatlabEnginegt connectMatlabAsync(String name)

static FutureltMatlabEnginegt connectMatlabAsync

Connect to a shared MATLAB session on local machine asynchronously The behavior isthe same as that of connectMatlab except the mechanism is asynchronous

String name Name of the shared MATLAB session

An instance of FutureltMatlabEnginegt

FutureltMatlabEnginegt future = MatlabEngineconnectMatlabAsync()

ldquoConnect Java to Running MATLAB Sessionrdquo

commathworksengineMatlabEngine class

1-181

fevalltTgt T feval(int nlhs String func Writer output Writer errorObjecthellip args)

ltTgt T feval(int nlhs String func Objecthellip args)

ltTgt T feval(String func Writer output Writer error Objecthellip args)

ltTgt T feval(String func Objecthellip args)

Evaluate MATLAB functions with input arguments synchronously

String func Name of the MATLAB function or script to evaluateint nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

Result of executing the MATLAB function

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

1 API Reference

1-182

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is a MATLAB runtime error in the function

commathworksengineUnsupportedTypeExeption

There is an unsupported data type

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB function

double result = enginefeval(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

fevalAsyncltTgt FutureltTgt fevalAsync(int nlhs String func Writer outputWriter error Objecthellip args)

ltTgt FutureltTgt fevalAsync(int nlhs String func Objecthellip args)

ltTgt FutureltTgt fevalAsync(String func Writer output Writer errorObjecthellip args)

ltTgt FutureltTgt fevalAsync(String func Objecthellip args)

Evaluate MATLAB functions with input arguments asynchronously

String func Name of the MATLAB function or script to evaluate

commathworksengineMatlabEngine class

1-183

int nlhs Number of expected outputs Default is 1

If nlhs is greater than 1 the returned type T must beltObject[]gt

If nlhs is 0 the returned type T must be ltVoidgt or ltgt

If nlhs is 1 the returned type T can be the expected type orltObjectgt if the type is not known

Writer output Stream used to store the standard output from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABfunction If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

Object args Arguments to pass to the MATLAB function

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginefevalAsync(sqrt 4)

ldquoExecute MATLAB Functions from Javardquo

evalvoid eval(String command Writer output Writer error)

void eval(String command)

Evaluate a MATLAB statement as a string synchronously

1 API Reference

1-184

String command MATLAB statement to evaluateWriter output Stream used to store the standard output from the MATLAB

statement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe output from the MATLAB command window

Writer error Stream used to store the standard error from the MATLABstatement If you do not specify a writer the output is written tothe command window or terminal Use NULL_WRITER to ignorethe error message from the MATLAB command window

javautilconcurrentCancellationException

Evaluation of a MATLAB function was canceled

javalangInterruptedException

Evaluation of a MATLAB function was interrupted

javalangIllegalStateException

The MATLAB session is not available

commathworksengineMatlabExcecutionException

There is an error in the MATLAB statement duringruntime

commathworksengineMatlabSyntaxException

There is a syntax error in the MATLAB statement

engineeval(result = sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

evalAsyncFutureltVoidgt evalAsync(String command Writer output Writer error)

FutureltVoidgt evalAsync(String command)

Evaluate a MATLAB statement as a string asynchronously

String command MATLAB statement to evaluate

commathworksengineMatlabEngine class

1-185

Writer output Stream used to store the standard output from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the output from the MATLABcommand window

Writer error Stream used to store the standard error from theMATLAB statement If you do not specify a writer theoutput is written to the command window or terminal UseNULL_WRITER to ignore the error message from theMATLAB command window

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineevalAsync(sqrt(4))

ldquoEvaluate MATLAB Statements from Javardquo

getVariableltTgt T getVariable(String varName)

Get a variable from the MATLAB base workspace

String varName Name of a variable in the MATLAB base workspace

Variable passed from the MATLAB base workspace

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

1 API Reference

1-186

javalangIllegalStateException

The MATLAB session is not available

double myVar = enginegetVariable(myVar)

ldquoPass Variables from MATLAB to Javardquo

getVariableAsyncltTgt FutureltTgt getVariableAsync(String varName)

Get a variable from the MATLAB base workspace asynchronously

String varName Name of a variable in MATLAB base workspace

An instance of FutureltTgt

javalangIllegalStateException

The MATLAB session is not available

FutureltDoublegt future = enginegetVariableAsync(myVar)

ldquoPass Variables from MATLAB to Javardquo

putVariablevoid putVariable(String varName T varData)

Put a variable into the MATLAB base workspace

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

commathworksengineMatlabEngine class

1-187

javautilconcurrentCancellationException

Evaluation of this function is canceled

javalangInterruptedException

Evaluation of this function is interrupted

javalangIllegalStateException

The MATLAB session is not available

engineputVariable(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

putVariableAsyncFutureltVoidgt putVariableAsync(String varName T varData)

Put a variable into the MATLAB base workspace asynchronously

String varName Name of a variable to create in the MATLAB base workspaceT varData Value of the variable to create in the MATLAB base workspace

An instance of FutureltVoidgt

javalangIllegalStateException

The MATLAB session is not available

FutureltVoidgt future = engineputVariableAsync(myVar 100)

ldquoPass Variables from Java to MATLABrdquo

disconnectvoid disconnect()

Disconnect from the current MATLAB session

1 API Reference

1-188

commathworksengineEngineException

The current MATLAB session cannot be disconnected

enginedisconnect()

ldquoClose MATLAB Engine Sessionrdquo

disconnectAsyncFutureltVoidgt disconnectAsync()

Disconnect from the current MATLAB session

FutureltVoidgt future = enginedisconnectAsync()

ldquoClose MATLAB Engine Sessionrdquo

quitviod quit()

Force the shutdown of the current MATLAB session

commathworksengineEngineException

The current MATLAB session cannot be shut down

enginequit()

ldquoClose MATLAB Engine Sessionrdquo

quitAsyncFutureltVoidgt quitAsync()

commathworksengineMatlabEngine class

1-189

Force the shutdown of the current MATLAB session asynchronously without waiting fortermination

An instance of FutureltVoidgt

FutureltVoidgt future = enginequitAsync()

ldquoClose MATLAB Engine Sessionrdquo

closevoid close()

MatlabEngine provides the close() method to implement thejavalangAutoCloseable interface for MatlabEngine objects This close()method enables you to use a try-with-resources statement to automatically disconnect orterminate the MATLAB session at the end of the statement

The MatlabEngine close() method disconnects or terminates the current MATLABsession depending on the context

bull If a Java process starts the MATLAB session as a default non-shared sessionclose() terminates MATLAB

bull If the MATLAB session is a shared session close() disconnects MATLAB from thisJava process MATLAB terminates when there are no other connections

To force the shutdown or disconnection of the current MATLAB session explicitly callMatlabEnginequit() MatlabEnginedisconnect() or their asynchronouscounterparts

engineclose()

ldquoClose MATLAB Engine Sessionrdquo

1 API Reference

1-190

Examples

Evaluate Function Asynchronously

This example shows how to evaluate a MATLAB function asynchronously The workflowis

bull Open a MATLAB sessionbull Invoke the MATLAB sqrt function with arguments asynchronouslybull Get the result of the MATLAB functionbull Close the MATLAB engine

import commathworksengineMatlabEngine

FutureltMatlabEnginegt engFuture = MatlabEnginestartMatlabAsync()MatlabEngine engine = engFutureget()double myVar = 4FutureltDoublegt future = enginefevalAsync(sqrt myVar)double result = futureget()Systemoutprintln(result)

See AlsomatlabengineengineName | matlabengineisEngineShared |matlabengineshareEngine

TopicsldquoBuild Java Engine ProgramsrdquoldquoStart and Close MATLAB Session from Javardquo

Introduced in R2016b

commathworksengineMatlabEngine class

1-191

commathworksmatlabtypesComplex classPackage commathworksmatlabtypes

Java class to pass complex data to and from MATLAB

DescriptionThe Complex class provides Java support for MATLAB complex arrays Use this class topass complex data to MATLAB The MATLAB engine passes complex data to Java as aninstance of Complex

All MATLAB numeric types are converted to double in Java

Constructor SummaryComplex(double real double imag) constructs an instance of Complex with thespecified real and imaginary values

Field Summarydouble real The real part of the complex datadouble imag The imaginary part of the complex data

Examples

Pass Complex Variable to MATLAB Function

import commathworksengineMatlabEngine

MatlabEngine engine = MatlabEnginestartMatlab()

1 API Reference

1-192

Complex c = new Complex(23)Complex cj = enginefeval(conjc)

bull ldquoUsing Complex Variables in Javardquo

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoUsing Complex Variables in Javardquo

Introduced in R2016b

commathworksmatlabtypesComplex class

1-193

commathworksmatlabtypesHandleObject classPackage commathworksmatlabtypes

Java class to represent MATLAB handle objects

DescriptionJava represents handle objects that are passed from MATLAB as instances of theHandleObject class When passing a handle object back to MATLAB Java passes areference to the HandleObject instance This reference can be either an array or ascalar depending on the original handle object passed to Java from MATLAB

You can pass a handle object only to the MATLAB session in which it was originallycreated You cannot construct a HandleObject in Java

Examples

Get Handle Object from MATLAB

This example starts a shared MATLAB session and creates a containersMap object inthe MATLAB workspace The statement evaluated in the MATLAB workspace returns ahandle variable that refers to the Map object

The engine getVariable function returns the MATLAB handle variable as aHandleObject instance This instance is used to call the MATLABcontainersMapkeys function to obtain the Map keys

import commathworksengineMatlabEngineimport commathworksmatlabtypes

MatlabEngine engine = MatlabEnginestartMatlab()engineeval(cm = containersMap(idname11mw))

1 API Reference

1-194

HandleObject handle = enginegetVariable(cm)String[] cells = enginefeval(keys handle)

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex | commathworksmatlabtypesStruct

TopicsldquoUsing MATLAB Handle Objects in Javardquo

Introduced in R2016b

commathworksmatlabtypesHandleObject class

1-195

commathworksmatlabtypesStruct classPackage commathworksmatlabtypes

Java class to pass MATLAB struct to and from MATLAB

DescriptionThe Struct class provides support for passing data between MATLAB and Java as aMATLAB struct The Struct class implements the javautilMap interface

The Struct class is designed as an immutable type Attempting to change the mappingskeys or values of the returned Struct causes an UnsupportedOperationExceptionCalling these methods can cause the exception put() putAll() remove()entrySet() keySet() and values()

For an example see ldquoUsing MATLAB Structures in Javardquo

Constructor SummaryStruct s = new Struct(field1value1field2value2 ) creates aninstance of Struct with the specified field names and values

Method SummarycontainsKey(Object key) Returns true if this map contains a

mapping for the specified keycontainsValue(Object value) Returns true if this map maps one or more

keys to the specified valueentrySet() Returns a Set view of the mappings

contained in this mapequals(Object o) Compares the specified object with this

map for equality

1 API Reference

1-196

get(Object key) Returns the value to which the specifiedkey is mapped or null if this map containsno mapping for the key

hashCode() Returns the hash code value for this mapisEmpty() Returns true if this map contains no key-

value mappingskeySet() Returns a Set view of the keys contained

in this mapsize() Returns the number of key-value mappings

in this mapvalues() Returns a Collection view of the values

contained in this map

Examples

Create Struct for MATLAB Function Argument

Create a Struct and assign a key and value

import commathworksengineimport commathworksmatlabtypes

class StructProperties public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() int[] y = 12345 double[] color = 100507 Struct s = new Struct(ColorcolorLineWidth2) engfeval(plotys)

bull ldquoUsing MATLAB Structures in Javardquo

commathworksmatlabtypesStruct class

1-197

See AlsocommathworksmatlabtypesCellStr |commathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject

TopicsldquoUsing MATLAB Structures in Javardquo

Introduced in R2016b

1 API Reference

1-198

commathworksmatlabtypesCellStr classPackage commathworksmatlabtypes

Java class to represent MATLAB cell array of char vectors

DescriptionThe CellStr class provides support for passing data from Java to MATLAB as aMATLAB cell array of char vectors (called a cellstr in MATLAB see cellstr) Thereare MATLAB functions that require cell arrays of char vectors as inputs To passarguments from Java to a MATLAB function requiring cellst inputs use the JavaCellStr class to create a compatible type

A MATLAB cellstr is mapped to a Java String array

Constructor SummaryCellStr(Object stringArray) creates a CellStr using a String or String arrayThe String array can have multiple dimensions

Method SummaryObject getStringArray() Get the String or String array used to

create the CellStrboolean equals(CellStr1CellStr2) Compare one CellStr instance with

another Two CellStr instances are equalif the String or String array they containare the same

commathworksmatlabtypesCellStr class

1-199

Examples

Construct CellStrThis example constructs a CellStr named keySet and puts the variable in theMATLAB base workspaceimport commathworksengineimport commathworksmatlabtypes

class javaCellstr public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() CellStr keySet = new CellStr(new String[]JanFebMarApr) engputVariable(mapKeyskeySet) engclose()

Construct CellStr Array

This example creates a CellStr array and passes it to the MATLAB plot function tochange the appearance of the graph produced by MATLAB The call to the MATLABprint function exports the figure as a jpeg file named myPlotjpg

import commathworksengineimport commathworksmatlabtypes

class CellStrArray public static void main(String[] args) throws Exception MatlabEngine eng = MatlabEnginestartMatlab() String[][] strArray = new String[2][2] strArray[0][0] = MarkerFaceColor strArray[0][1] = MarkerEdgeColor strArray[1][0] = green strArray[1][1] = red CellStr markerCellStr = new CellStr(strArray) engputVariable(MmarkerCellStr) engeval(plot(110--bsM)) engeval(print(myPlot-djpeg)) engclose()

1 API Reference

1-200

See AlsocommathworksmatlabtypesComplex |commathworksmatlabtypesHandleObject |commathworksmatlabtypesStruct

TopicsldquoPass Java CellStr to MATLABrdquo

Introduced in R2016b

commathworksmatlabtypesCellStr class

1-201

engClose (C and Fortran)Quit MATLAB engine session

C Syntaxinclude enginehint engClose(Engine ep)

Fortran Syntaxinclude enginehinteger4 engClose(ep)mwPointer ep

Argumentsep

Engine pointer

Returns0 on success and 1 otherwise Possible failure includes attempting to terminate analready-terminated MATLAB engine session

DescriptionThis routine sends a quit command to the MATLAB engine session and closes theconnection

1 API Reference

1-202

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIXreg operating systemsbull engwindemoc for a C example on Microsoftreg Windowsreg operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen

Introduced before R2006a

engClose (C and Fortran)

1-203

engEvalString (C and Fortran)Evaluate expression in string

C Syntaxinclude enginehint engEvalString(Engine ep const char string)

Fortran Syntaxinclude enginehinteger4 engEvalString(ep string)mwPointer epcharacter() string

Argumentsep

Engine pointerstring

String to execute

Returns1 if the engine session is no longer running or the engine pointer is invalid or NULLOtherwise returns 0 even if the MATLAB engine session cannot evaluate the command

DescriptionengEvalString evaluates the expression contained in string for the MATLAB enginesession ep previously started by engOpen

1 API Reference

1-204

UNIX Operating Systems

On UNIX systems engEvalString sends commands to the MATLAB workspace bywriting down a pipe connected to the MATLAB stdin process MATLAB reads back fromstdout any output resulting from the command that ordinarily appears on the screeninto the buffer defined by engOutputBuffer

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Microsoft Windows Operating Systems

On a Windows system engEvalString communicates with MATLAB software using aComponent Object Model (COM) interface

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engOutputBuffer

Introduced before R2006a

engEvalString (C and Fortran)

1-205

engGetVariable (C and Fortran)Copy variable from MATLAB engine workspace

C Syntaxinclude enginehmxArray engGetVariable(Engine ep const char name)

Fortran Syntaxinclude enginehmwPointer engGetVariable(ep name)mwPointer epcharacter() name

Argumentsep

Engine pointername

Name of mxArray to get from MATLAB workspace

ReturnsPointer to a newly allocated mxArray structure or NULL if the attempt failsengGetVariable fails if the named variable does not exist

DescriptionengGetVariable reads the named mxArray from the MATLAB engine sessionassociated with ep

1 API Reference

1-206

The limit for the size of data transferred is 2 GB

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengPutVariable mxDestroyArray

Introduced before R2006a

engGetVariable (C and Fortran)

1-207

engGetVisible (C)Determine visibility of MATLAB engine session

C Syntaxinclude enginehint engGetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Pointer to value returned from engGetVisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengGetVisible returns the current visibility setting for MATLAB engine session ep Avisible engine session runs in a window on the Windows desktop thus making the engineavailable for user interaction MATLAB removes an invisible session from the desktop

ExamplesThe following code opens engine session ep and disables its visibility

1 API Reference

1-208

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengSetVisible

engGetVisible (C)

1-209

Engine (C)Type for MATLAB engine

DescriptionA handle to a MATLAB engine object

Engine is a C language opaque type

You can call MATLAB software as a computational engine by writing C and Fortranprograms that use the MATLAB engine library Engine is the link between yourprogram and the separate MATLAB engine process

The header file containing this type is

include engineh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc shows how to call the MATLAB engine functions from a C programbull engwindemoc show how to call the MATLAB engine functions from a C program for

Windows systemsbull fengdemoF shows how to call the MATLAB engine functions from a Fortran

program

See AlsoengOpen

1 API Reference

1-210

engOpen (C and Fortran)Start MATLAB engine session

C Syntaxinclude enginehEngine engOpen(const char startcmd)

Fortran Syntaxinclude enginehmwPointer engOpen(startcmd)character() startcmd

Argumentsstartcmd

String to start the MATLAB process On Windows systems the startcmd stringmust be NULL

ReturnsPointer to an engine handle or NULL if the open fails

DescriptionThis routine allows you to start a MATLAB process for using MATLAB as acomputational engine

engOpen starts a MATLAB process using the command specified in the stringstartcmd establishes a connection and returns an engine pointer

engOpen (C and Fortran)

1-211

On UNIX systems if startcmd is NULL or the empty string engOpen starts a MATLABprocess on the current host using the command matlab If startcmd is a hostnameengOpen starts a MATLAB process on the designated host by embedding the specifiedhostname string into the larger string

rsh hostname bincsh -c setenv DISPLAY hostname0 matlab

If startcmd is any other string (has white space in it or nonalphanumeric characters)MATLAB executes the string literally

On UNIX systems engOpen performs the following steps

1 Creates two pipes2 Forks a new process Sets up the pipes to pass stdin and stdout from MATLAB

(parent) software to two file descriptors in the engine program (child)3 Executes a command to run MATLAB software (rsh for remote execution)

On Windows systems engOpen opens a COM channel to MATLAB The MATLABsoftware you registered during installation starts If you did not register duringinstallation enter the following command at the MATLAB prompt

matlab -regserver

See ldquoMATLAB COM Integrationrdquo for additional details

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

Introduced before R2006a

1 API Reference

1-212

engOpenSingleUse (C)Start MATLAB engine session for single nonshared use

C Syntaxinclude enginehEngine engOpenSingleUse(const char startcmd void dcom int retstatus)

Argumentsstartcmd

String to start MATLAB process On Microsoft Windows systems the startcmdstring must be NULL

dcomReserved for future use must be NULL

retstatusReturn status possible cause of failure

Returns

Microsoft Windows Operating Systems Only

Pointer to an engine handle or NULL if the open fails

UNIX Operating Systems

Not supported on UNIX systems

engOpenSingleUse (C)

1-213

DescriptionThis routine allows you to start multiple MATLAB processes using MATLAB as acomputational engine

engOpenSingleUse starts a MATLAB process establishes a connection and returns aunique engine identifier or NULL if the open fails Each call to engOpenSingleUsestarts a new MATLAB process

engOpenSingleUse opens a COM channel to MATLAB This starts the MATLABsoftware you registered during installation If you did not register during installationenter the following command at the MATLAB prompt

matlab -regserver

engOpenSingleUse allows single-use instances of an engine serverengOpenSingleUse differs from engOpen which allows multiple applications to use thesame engine server

See ldquoMATLAB COM Integrationrdquo for additional details

1 API Reference

1-214

engOutputBuffer (C and Fortran)Specify buffer for MATLAB output

C Syntaxinclude enginehint engOutputBuffer(Engine ep char p int n)

Fortran Syntaxinclude enginehinteger4 engOutputBuffer(ep p)mwPointer epcharactern p

Argumentsep

Engine pointerp

Pointer to character buffern

Length of buffer p

Returns1 if you pass it a NULL engine pointer Otherwise returns 0

engOutputBuffer (C and Fortran)

1-215

DescriptionengOutputBuffer defines a character buffer for engEvalString to return any outputthat ordinarily appears on the screen

The default behavior of engEvalString is to discard any standard output caused by thecommand it is executing A call to engOutputBuffer with a buffer of nonzero lengthtells any subsequent calls to engEvalString to save output in the character bufferpointed to by p

To turn off output buffering in C use

engOutputBuffer(ep NULL 0)

To turn off output buffering in Fortran use

engOutputBuffer(ep )

Note The buffer returned by engEvalString is not NULL terminated

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systemsbull fengdemoF for a Fortran example

See AlsoengOpen engEvalString

Introduced before R2006a

1 API Reference

1-216

engPutVariable (C and Fortran)Put variable into MATLAB engine workspace

C Syntaxinclude enginehint engPutVariable(Engine ep const char name const mxArray pm)

Fortran Syntaxinclude enginehinteger4 engPutVariable(ep name pm)mwPointer ep pmcharacter() name

Argumentsep

Engine pointername

Name of mxArray in the engine workspacepm

mxArray pointer

Returns0 if successful and 1 if an error occurs

DescriptionengPutVariable writes mxArray pm to the engine ep giving it the variable name name

engPutVariable (C and Fortran)

1-217

If the mxArray does not exist in the workspace the function creates it If an mxArraywith the same name exists in the workspace the function replaces the existing mxArraywith the new mxArray

The limit for the size of data transferred is 2 GB

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The engine application owns the original mxArray and is responsible for freeing itsmemory Although the engPutVariable function sends a copy of the mxArray to theMATLAB workspace the engine application does not need to account for or free memoryfor the copy

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull engdemoc for a C example on UNIX operating systemsbull engwindemoc for a C example on Microsoft Windows operating systems

See AlsoengGetVariable

Introduced before R2006a

1 API Reference

1-218

engSetVisible (C)Show or hide MATLAB engine session

C Syntaxinclude enginehint engSetVisible(Engine ep bool value)

Argumentsep

Engine pointervalue

Value to set the Visible property to Set value to 1 to make the engine windowvisible or to 0 to make it invisible

Returns

Microsoft Windows Operating Systems Only

0 on success and 1 otherwise

DescriptionengSetVisible makes the window for the MATLAB engine session ep either visible orinvisible on the Windows desktop You can use this function to enable or disable userinteraction with the MATLAB engine session

engSetVisible (C)

1-219

ExamplesThe following code opens engine session ep and disables its visibility

Engine epbool vis

ep = engOpen(NULL)engSetVisible(ep 0)

To determine the current visibility setting use

engGetVisible(ep ampvis)

See AlsoengGetVisible

1 API Reference

1-220

matClose (C and Fortran)Close MAT-file

C Syntaxinclude mathint matClose(MATFile mfp)

Fortran Syntaxinclude mathinteger4 matClose(mfp)mwPointer mfp

Argumentsmfp

Pointer to MAT-file information

ReturnsEOF in C (-1 in Fortran) for a write error and 0 if successful

DescriptionmatClose closes the MAT-file associated with mfp

ExamplesSee the following examples in matlabrootexternexampleseng_mat

matClose (C and Fortran)

1-221

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen

Introduced before R2006a

1 API Reference

1-222

matDeleteVariable (C and Fortran)Delete array from MAT-file

C Syntaxinclude mathint matDeleteVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathinteger4 matDeleteVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to delete

Returns0 if successful and nonzero otherwise

DescriptionmatDeleteVariable deletes the named mxArray from the MAT-file pointed to by mfp

matDeleteVariable (C and Fortran)

1-223

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

Introduced before R2006a

1 API Reference

1-224

MATFile (C and Fortran)Type for MAT-file

DescriptionA handle to a MAT-file object A MAT-file is the data file format MATLAB software usesfor saving data to your disk

MATFile is a C language opaque type

The MAT-file interface library contains routines for reading and writing MAT-files Callthese routines from your own CC++ and Fortran programs using MATFile to accessyour data file

The header file containing this type is

include math

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1Fbull matdemo2F

See AlsomatOpen matClose matPutVariable matGetVariable mxDestroyArray

MATFile (C and Fortran)

1-225

matGetDir (C and Fortran)List of variables in MAT-file

C Syntaxinclude mathchar matGetDir(MATFile mfp int num)

Fortran Syntaxinclude mathmwPointer matGetDir(mfp num)mwPointer mfpinteger4 num

Argumentsmfp

Pointer to MAT-file informationnum

Pointer to the variable containing the number of mxArrays in the MAT-file

ReturnsPointer to an internal array containing pointers to the names of the mxArrays in theMAT-file pointed to by mfp In C each name is a NULL-terminated string The numoutput argument is the length of the internal array (number of mxArrays in the MAT-file) If num is zero mfp contains no arrays

matGetDir returns NULL in C (0 in Fortran) If matGetDir fails sets num to a negativenumber

1 API Reference

1-226

DescriptionThis routine provides you with a list of the names of the mxArrays contained within aMAT-file

matGetDir allocates memory for the internal array of strings using a mxCalloc Freethe memory using mxFree when you are finished with the array

MATLAB variable names can be up to length mxMAXNAM defined in the C header filematrixh

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo2F

Introduced before R2006a

matGetDir (C and Fortran)

1-227

matGetFp (C)File pointer to MAT-file

C Syntaxinclude mathFILE matGetFp(MATFile mfp)

Argumentsmfp

Pointer to MAT-file information

ReturnsC file handle to the MAT-file with handle mfp Returns NULL if mfp is a handle to aMAT-file in HDF5-based format

DescriptionUse matGetFp to obtain a C file handle to a MAT-file Standard C library routines likeferror and feof use file handle to investigate errors

Introduced before R2006a

1 API Reference

1-228

matGetNextVariable (C and Fortran)Next array in MAT-file

C Syntaxinclude mathmxArray matGetNextVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing the next mxArray from theMAT-file pointed to by mfp The function returns the name of the mxArray in name

matGetNextVariable returns NULL in C (0 in Fortran) for end of file or if there is anerror condition In C use feof and ferror from the Standard C Library to determinestatus

matGetNextVariable (C and Fortran)

1-229

DescriptionmatGetNextVariable allows you to step sequentially through a MAT-file and readevery mxArray in a single pass The function reads and returns the next mxArray fromthe MAT-file pointed to by mfp

Use matGetNextVariable immediately after opening the MAT-file with matOpen andnot with other MAT-file routines Otherwise the concept of the next mxArray isundefined

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariable is notguaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariableInfo matGetVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-230

matGetNextVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetNextVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetNextVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Pointer to the variable containing the mxArray name

ReturnsPointer to a newly allocated mxArray structure representing header information for thenext mxArray from the MAT-file pointed to by mfp The function returns the name of themxArray in name

matGetNextVariableInfo returns NULL in C (0 in Fortran) when the end of file isreached or if there is an error condition In C use feof and ferror from the Standard CLibrary to determine status

matGetNextVariableInfo (C and Fortran)

1-231

DescriptionmatGetNextVariableInfo loads only the array header information includingeverything except pr pi ir and jc from the current file offset

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetNextVariableInfo sets them to -1 instead These headers are forinformational use only Never pass this data back to the MATLAB workspace or save it toMAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

The order of variables returned from successive calls to matGetNextVariableInfo isnot guaranteed to be the same order in which the variables were written

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdgnscbull matdemo2F

See AlsomatGetNextVariable matGetVariableInfo

Introduced before R2006a

1 API Reference

1-232

matGetVariable (C and Fortran)Array from MAT-file

C Syntaxinclude mathmxArray matGetVariable(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariable(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing the mxArray named byname from the MAT-file pointed to by mfp

matGetVariable returns NULL in C (0 in Fortran) if the attempt to return the mxArraynamed by name fails

matGetVariable (C and Fortran)

1-233

DescriptionThis routine allows you to copy an mxArray out of a MAT-file

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable mxDestroyArray

Introduced before R2006a

1 API Reference

1-234

matGetVariableInfo (C and Fortran)Array header information only

C Syntaxinclude mathmxArray matGetVariableInfo(MATFile mfp const char name)

Fortran Syntaxinclude mathmwPointer matGetVariableInfo(mfp name)mwPointer mfpcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to get from MAT-file

ReturnsPointer to a newly allocated mxArray structure representing header information for themxArray named by name from the MAT-file pointed to by mfp

matGetVariableInfo returns NULL in C (0 in Fortran) if the attempt to return headerinformation for the mxArray named by name fails

matGetVariableInfo (C and Fortran)

1-235

DescriptionmatGetVariableInfo loads only the array header information including everythingexcept pr pi ir and jc It recursively creates the cells and structures through theirleaf elements but does not include pr pi ir and jc

If pr pi ir and jc are nonzero values when loaded with matGetVariablematGetVariableInfo sets them to -1 instead These headers are for informational useonly Never pass this data back to the MATLAB workspace or save it to MAT-files

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomatGetVariable

Introduced before R2006a

1 API Reference

1-236

matlabengineconnect_matlabConnect shared MATLAB session to MATLAB Engine for Python

Syntaxeng = matlabengineconnect_matlab(name=None)eng = matlabengineconnect_matlab( ___ async)

Descriptioneng = matlabengineconnect_matlab(name=None) connects to the sharedMATLAB session name and returns a MatlabEngine object as eng The inputargument name specifies the name of a MATLAB session that is already running on yourlocal machine

bull If you specify name and the engine cannot find a shared MATLAB session of the samename then you receive an EngineError exception

bull If you do not specify name and the engine cannot find any shared MATLAB sessionsthen it starts a new shared MATLAB session If there are shared MATLAB sessionsrunning the engine connects to the first available session

bull If you do not specify name and the engine finds multiple shared MATLAB sessionsrunning then it connects to the first available session

eng = matlabengineconnect_matlab( ___ async) connects asynchronously ifasync is True

Examples

Connect to MATLAB Session

Connect to a shared MATLAB session that is already running on your local machine

matlabengineconnect_matlab

1-237

import matlabengineeng = matlabengineconnect_matlab()engsqrt(40)

20

matlabengineconnect_matlab connects to the first available shared MATLABsession If no MATLAB sessions are shared matlabengineconnect_matlab starts anew session

Connect to MATLAB Sessions by Name

When there are multiple shared MATLAB sessions on your local machine connect to twodifferent sessions one at a time by specifying their names

Connect to the first shared MATLAB session

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

Connect to the second shared MATLAB session

eng = matlabengineconnect_matlab(MATLAB_7090)engsqrt(40)

20

bull ldquoConnect Python to Running MATLAB Sessionrdquo

Input Argumentsname mdash Name of shared MATLAB sessioncharacter array

Name of the shared MATLAB session specified as a character array

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

1 API Reference

1-238

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

Output Argumentseng mdash Pythonreg variable for communicating with MATLABMatlabEngine object

Python variable for communicating with MATLAB returned as a MatlabEngine objecteng communicates with a shared MATLAB session that is already running on your localmachine

Limitationsbull Do not connect the engine multiple times to the same shared MATLAB session

See AlsomatlabengineMatlabEngine | matlabenginefind_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabengineconnect_matlab

1-239

matlabenginefind_matlabFind shared MATLAB sessions to connect to MATLAB Engine for Python

Syntaxnames = matlabenginefind_matlab()

Descriptionnames = matlabenginefind_matlab() finds all shared MATLAB sessions on yourlocal machine and returns their names in a tuple Any name in names can be the inputargument to matlabengineconnect_matlab If there are no shared sessionsrunning on your local machine matlabenginefind_matlab returns an emptytuple

Examples

Find Shared MATLAB Sessions

Identify the shared MATLAB sessions running on your local machine and connect to oneof them

import matlabenginenames = matlabenginefind_matlab()names

(MATLAB_6830 MATLAB_7090)

There are two shared MATLAB sessions running so matlabenginefind_matlabreturns two names in a tuple

Connect to the first shared MATLAB session

1 API Reference

1-240

eng = matlabengineconnect_matlab(MATLAB_6830)

bull ldquoConnect Python to Running MATLAB Sessionrdquo

See Alsomatlabengineconnect_matlab

TopicsldquoConnect Python to Running MATLAB Sessionrdquo

Introduced in R2015b

matlabenginefind_matlab

1-241

matlabengineFutureResult classPackage matlabengine

Results of asynchronous call to MATLAB function stored in Python object

DescriptionThe FutureResult class stores results of an asynchronous call to a MATLAB function ina Python object

ConstructionThe MATLAB Engine for Python creates a FutureResult object when a MATLABfunction is called asynchronously There is no need to callmatlabengineFutureResult() to create FutureResult objects of your own

Methods

cancel Cancel asynchronous call to MATLAB function from Pythoncancelled Cancellation status of asynchronous call to MATLAB function from Pythondone Completion status of asynchronous call to MATLAB function from Pythonresult Result of asynchronous call to MATLAB function from Python

ExceptionsSyntaxError Python exception syntax error in function

callTypeError Python exception data type of output

argument not supported

1 API Reference

1-242

matlabengineCancelledError MATLAB engine cannot cancel functioncall

matlabengineInterruptedError Function call interruptedmatlabengineMatlabExecutionError

Function call fails to execute

matlabengineRejectedExecutionError

Engine terminated

matlabengineTimeoutError Result cannot be returned within thetimeout period

Examples

Get Result of Asynchronous MATLAB Call from Python

Call the MATLAB sqrt function from Python Set async to True to make the functioncall asynchronously

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquo

See AlsomatlabengineMatlabEngine

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from Pythonrdquo

matlabengineFutureResult class

1-243

Introduced in R2014b

1 API Reference

1-244

cancelClass matlabengineFutureResultPackage matlabengine

Cancel asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancel()

Descriptiontf = FutureResultcancel() cancels a call to a MATLAB function calledasynchronously from Python FutureResultcancel returns True if it successfullycancels the function and False if it cannot cancel the function

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status returned as either True or False The status tf is True ifFutureResultcancel successfully cancels the asynchronous function call and isFalse otherwise

Examples

Cancel an Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval function Thencancel it

cancel

1-245

import matlabengineeng = matlabenginestart_matlab()ret = engeval(while 1 endnargout=0async=True)tf = retcancel()print(tf)

True

See Also

1 API Reference

1-246

cancelledClass matlabengineFutureResultPackage matlabengine

Cancellation status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultcancelled()

Descriptiontf = FutureResultcancelled() returns the cancellation status of a call to aMATLAB function called asynchronously from Python FutureResultcancelledreturns True if a previous call to FutureResultcancel succeeded and Falseotherwise

Output Argumentstf mdash Cancellation statusTrue | False

Cancellation status of an asynchronous function call returned as either True or False

Examples

Check Cancellation Status of Asynchronous Call

Start an endless loop in MATLAB with an asynchronous call to the eval functionCancel it and check that the engine stopped the loopimport matlabengineeng = matlabenginestart_matlab()

cancelled

1-247

ret = engeval(while 1 endnargout=0async=True)eval_stop = retcancel()tf = retcancelled()print(tf)

True

See Also

1 API Reference

1-248

doneClass matlabengineFutureResultPackage matlabengine

Completion status of asynchronous call to MATLAB function from Python

Syntaxtf = FutureResultdone()

Descriptiontf = FutureResultdone() returns the completion status of a MATLAB functioncalled asynchronously from Python FutureResultdone returns True if the functionhas finished and False if it has not finished

Output Argumentstf mdash Completion status of asynchronous function callTrue | False

Completion status of an asynchronous function call returned as either True or False

Examples

Check If Asynchronous Call Finished

Call the MATLAB sqrt function with async = True Check the status of ret to learn ifsqrt is finished

import matlabengineeng = matlabenginestart_matlab()

done

1-249

ret = engsqrt(40async=True)tf = retdone()print(tf)

True

When retdone() returns True then you can call retresult() to return the squareroot

See Also

1 API Reference

1-250

resultClass matlabengineFutureResultPackage matlabengine

Result of asynchronous call to MATLAB function from Python

Syntaxret = FutureResultresult(timeout=None)

Descriptionret = FutureResultresult(timeout=None) returns the actual result of a call to aMATLAB function called asynchronously from Python

Input Argumentstimeout mdash Timeout value in secondsNone (default) | Python float

Timeout value in seconds specified as Python data type float to wait for result of thefunction call If timeout = None the FutureResultresult function waits until thefunction call finishes and then returns the result

Output Argumentsret mdash Result of asynchronous function callPython object

Result of an asynchronous function call returned as a Python object that is the actualoutput argument of a call to a MATLAB function

result

1-251

Examples

Get MATLAB Output Argument from Asynchronous Call

Call the MATLAB sqrt function from Python Set async to True and get the squareroot from the FutureResult object

import matlabengineeng = matlabenginestart_matlab()future = engsqrt(40async=True)ret = futureresult()print(ret)

20

See Also

1 API Reference

1-252

matlabengineMatlabEngine classPackage matlabengine

Python object using MATLAB as computational engine within Python session

DescriptionThe MatlabEngine class uses a MATLAB process as a computational engine for PythonYou can call MATLAB functions as methods of a MatlabEngine object because thefunctions are dynamically invoked when you call them You also can call functions andscripts that you define You can send data to and retrieve data from the MATLABworkspace associated with a MatlabEngine object

ConstructionThe matlabenginestart_matlab function creates a MatlabEngine object each timeit is called There is no need to call matlabengineMatlabEngine() to createMatlabEngine objects of your own

MethodsYou can call any MATLAB function as a method of a MatlabEngine object The enginedynamically invokes a MATLAB function when you call it The syntax shows positionalkeyword and output arguments of a function call

ret =MatlabEnginematlabfunc(argsnargout=1async=Falsestdout=sysstsdoutstderr=sysstderr)

Replace matlabfunc with the name of any MATLAB function (such as isprime orsqrt) Replace args with input arguments for the MATLAB function you call Thekeyword arguments specify

matlabengineMatlabEngine class

1-253

bull The number of output arguments the function returnsbull Whether the engine calls the function asynchronouslybull Where the engine sends standard output and standard error coming from the function

Specify keyword arguments only when specifying values that are not the default valuesshown in the syntax

Input Arguments to MATLAB FunctionArgument Description Python Typeargs Input arguments to

MATLAB function specifiedas positional arguments

Any Python types that theengine can convert toMATLAB types

Keyword Arguments to EngineArgument Description Python Typenargout Number of output

arguments from MATLABfunction

intDefault 1

async Flag to call MATLABfunction asynchronously

boolDefault False

stdout Standard output StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstdout

stderr Standard error StringIOStringIO object(Python 27)ioStringIO object(Python 3x)Default sysstderr

1 API Reference

1-254

Output ArgumentsOutput Type Description Required Keyword

ArgumentsPython variable One output argument from

MATLAB functionDefault values

tuple Multiple output argumentsfrom MATLAB function

nargout=n (where n gt 1)

None No output argument fromMATLAB function

nargout=0

FutureResult object A placeholder for outputarguments fromasynchronous call toMATLAB function

async=True

ExceptionsMatlabExecutionError Function call fails to executeRejectedExecutionError MATLAB engine terminatedSyntaxError Syntax error in a function callTypeError Data type of an input or output argument

not supported

Attributesworkspace Python dictionary containing references to

MATLAB variables You can assign data toand get data from a MATLAB variablethrough the workspace The name of eachMATLAB variable you create becomes akey in the workspace dictionary The keysin workspace must be valid MATLABidentifiers (for example you cannot usenumbers as keys)

matlabengineMatlabEngine class

1-255

Examples

Call MATLAB Functions from Python

Call the MATLAB sqrt function from Python using the engine

import matlabengineeng = matlabenginestart_matlab()ret = engsqrt(40)print(ret)

20

Put Array Into MATLAB Workspace

Create an array in Python and put it into the MATLAB workspace

import matlabengineeng = matlabenginestart_matlab()px = englinspace(006281000)

px is a MATLAB array but englinspace returned it to Python To use it in MATLABput the array into the MATLAB workspace

engworkspace[mx] = px

When you add an entry to the engine workspace dictionary you create a MATLABvariable as well The engine converts the data to a MATLAB data type

Get Data from MATLAB Workspace

Get pi from the MATLAB workspace and copy it to a Python variable

import matlabengineeng = matlabenginestart_matlab()engeval(a = pinargout=0)mpi = engworkspace[a]print(mpi)

1 API Reference

1-256

314159265359

bull ldquoCall MATLAB Functions from Pythonrdquobull ldquoCall MATLAB Functions Asynchronously from Pythonrdquobull ldquoRedirect Standard Output and Error to Pythonrdquo

See AlsomatlabengineFutureResult | matlabenginestart_matlab

TopicsldquoCall MATLAB Functions from PythonrdquoldquoCall MATLAB Functions Asynchronously from PythonrdquoldquoRedirect Standard Output and Error to Pythonrdquo

Introduced in R2014b

matlabengineMatlabEngine class

1-257

matlabenginestart_matlabStart MATLAB Engine for Python

Syntaxeng = matlabenginestart_matlab()

eng = matlabenginestart_matlab(option)eng = matlabenginestart_matlab(async)eng = matlabenginestart_matlab(background)eng = matlabenginestart_matlab( ___ )

Descriptioneng = matlabenginestart_matlab() starts a new MATLAB process and returnsPython variable eng which is a MatlabEngine object for communicating with theMATLAB process

If MATLAB cannot be started the engine raises an EngineError exception

eng = matlabenginestart_matlab(option) uses startup options specified byoption

For example call matlabenginestart_matlab(-desktop) to start the MATLABdesktop from Python

eng = matlabenginestart_matlab(async) starts MATLAB asynchronously ifasync is True

eng = matlabenginestart_matlab(background) starts MATLABasynchronously if background is True

eng = matlabenginestart_matlab( ___ ) can include any of the input argumentsin previous syntaxes

1 API Reference

1-258

Examples

Start MATLAB Engine from Python

Start an engine and a new MATLAB process from the Python command line

import matlabengineeng = matlabenginestart_matlab()

Start Multiple Engines

Start a different MATLAB process from each engine

import matlabengineeng1 = matlabenginestart_matlab()eng2 = matlabenginestart_matlab()

Start MATLAB Desktop with Engine

Start an engine with the MATLAB desktop

import matlabengineeng = matlabenginestart_matlab(-desktop)

You also can start the desktop after you start the engineimport matlabengineeng = matlabenginestart_matlab()engdesktop(nargout=0)

Note You can call MATLAB functions from both the desktop and Python

Start Engine Asynchronously

Start the engine with async=True While MATLAB starts you can enter commands atthe Python command line

matlabenginestart_matlab

1-259

import matlabenginefuture = matlabenginestart_matlab(async=True)eng = futureresult()engsqrt(4)

20

bull ldquoStart and Stop MATLAB Engine for Pythonrdquo

Input Argumentsoption mdash Startup options for MATLAB process-nodesktop (default) | string

Startup options for the MATLAB process specified as a string You can specify multiplestartup options with option

The engine supports -desktop to start MATLAB with the desktop In addition theengine supports all MATLAB startup options except for the options listed inldquoLimitationsrdquo on page 1-261Example matlabenginestart_matlab(-desktop -r format short) startsthe desktop from Python The engine passes -r format short to MATLAB

async mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargumentExample matlabenginestart_matlab(async=True)

background mdash Start MATLAB synchronously or asynchronouslyFalse (default) | logical

Start MATLAB synchronously or asynchronously specified as a logical keywordargument background is an alias for async and will be removed in a future releaseExample matlabenginestart_matlab(background=True)

1 API Reference

1-260

Output Argumentseng mdash Python variable for communicating with MATLABMatlabEngine object | FutureResult object

Python variable for communicating with MATLAB returned as a MatlabEngine objectif async or background is set to False or a FutureResult object if async orbackground is set to True

Each time you call matlabenginestart_matlab it starts a new MATLAB process

LimitationsThe engine does not support these MATLAB startup options

bull -hbull -helpbull -bull -nbull -ebull -softwareopenglbull -logfile

See AlsomatlabengineMatlabEngine

TopicsldquoStart and Stop MATLAB Engine for PythonrdquoldquoSpecify Startup OptionsrdquoldquoCommonly Used Startup Optionsrdquo

Introduced in R2014b

matlabenginestart_matlab

1-261

matOpen (C and Fortran)Open MAT-file

C Syntaxinclude mathMATFile matOpen(const char filename const char mode)

Fortran Syntaxinclude mathmwPointer matOpen(filename mode)character() filename mode

Argumentsfilename

Name of file to openmode

File opening mode The following table lists valid values for moder Opens file for reading only determines the current version of the MAT-

file by inspecting the files and preserves the current versionu Opens file for update both reading and writing If the file does not exist

does not create a file (equivalent to the r+ mode of fopen) Determinesthe current version of the MAT-file by inspecting the files and preservesthe current version

w Opens file for writing only deletes previous contents if anyw4 Creates a MAT-file compatible with MATLAB Versions 4 software and

earlierw6 Creates a MAT-file compatible with MATLAB Version 5 (R8) software or

earlier Equivalent to wL mode

1 API Reference

1-262

wL Opens file for writing character data using the default character set foryour system Use MATLAB Version 6 or 65 software to read theresulting MAT-file

If you do not use the wL mode switch MATLAB writes character data tothe MAT-file using Unicodereg character encoding by default

Equivalent to w6 modew7 Creates a MAT-file compatible with MATLAB Version 70 (R14) software

or earlier Equivalent to wz modewz Opens file for writing compressed data By default the MATLAB save

function compresses workspace variables as they are saved to a MAT-fileTo use the same compression ratio when creating a MAT-file with thematOpen function use the wz option

Equivalent to w7 modew73 Creates a MAT-file in an HDF5-based format that can store objects that

occupy more than 2 GB

ReturnsFile handle or NULL in C (0 in Fortran) if the open fails

DescriptionThis routine opens a MAT-file for reading and writing

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnscbull matdemo1F

matOpen (C and Fortran)

1-263

bull matdemo2F

See AlsomatClose save

Introduced before R2006a

1 API Reference

1-264

matPutVariable (C and Fortran)Array to MAT-file

C Syntaxinclude mathint matPutVariable(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariable(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library along with matGetFp to determine status

matPutVariable (C and Fortran)

1-265

DescriptionThis routine puts an mxArray into a MAT-file

matPutVariable writes mxArray pm to the MAT-file mfp If the mxArray does notexist in the MAT-file the function appends it to the end If an mxArray with the samename exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatGetVariable matGetFp

Introduced before R2006a

1 API Reference

1-266

matPutVariableAsGlobal (C and Fortran)Array to MAT-file as originating from global workspace

C Syntaxinclude mathint matPutVariableAsGlobal(MATFile mfp const char name const mxArray pm)

Fortran Syntaxinclude mathinteger4 matPutVariableAsGlobal(mfp name pm)mwPointer mfp pmcharacter() name

Argumentsmfp

Pointer to MAT-file informationname

Name of mxArray to put into MAT-filepm

mxArray pointer

Returns0 if successful and nonzero if an error occurs In C use feof and ferror from theStandard C Library with matGetFp to determine status

matPutVariableAsGlobal (C and Fortran)

1-267

DescriptionThis routine puts an mxArray into a MAT-file matPutVariableAsGlobal is likematPutVariable except that MATLAB software loads the array into the globalworkspace and sets a reference to it in the local workspace If you write to a MATLAB 4format file matPutVariableAsGlobal does not load it as global and has the sameeffect as matPutVariable

matPutVariableAsGlobal writes mxArray pm to the MAT-file mfp If the mxArraydoes not exist in the MAT-file the function appends it to the end If an mxArray with thesame name exists in the file the function replaces the existing mxArray with the newmxArray by rewriting the file

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

The size of the new mxArray can be different from the existing mxArray

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdemo1F

See AlsomatPutVariable matGetFp

Introduced before R2006a

1 API Reference

1-268

mexAtExit (C and Fortran)Register function to call when MEX function clears or MATLAB terminates

C Syntaxinclude mexhint mexAtExit(void (ExitFcn)(void))

Fortran Syntaxinclude fintrfhinteger4 mexAtExit(ExitFcn)subroutine ExitFcn()

ArgumentsExitFcn

Pointer to function you want to run on exit

ReturnsAlways returns 0

DescriptionUse mexAtExit to register a function to call just before clearing the MEX function orterminating MATLAB mexAtExit gives your MEX function a chance to perform taskssuch as freeing persistent memory and closing files Other typical tasks include closingstreams or sockets

mexAtExit (C and Fortran)

1-269

Each MEX function can register only one active exit function at a time If you callmexAtExit more than once MATLAB uses the ExitFcn from the more recentmexAtExit call as the exit function

If a MEX function is locked you cannot clear the MEX file Therefore if you attempt toclear a locked MEX file MATLAB does not call the ExitFcn

In Fortran declare the ExitFcn as external in the Fortran routine that callsmexAtExit if it is not within the scope of the file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See AlsomexLock mexUnlock

Introduced before R2006a

1 API Reference

1-270

mexCallMATLAB (C and Fortran)Call MATLAB function user-defined function or MEX file

C Syntaxinclude mexhint mexCallMATLAB(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhinteger4 mexCallMATLAB(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

Argumentsnlhs

Number of output arguments Must be less than or equal to 50plhs

Array of pointers to output argumentsnrhs

Number of input arguments Must be less than or equal to 50prhs

Array of pointers to input argumentsfunctionName

Character string containing name of the MATLAB built-in function operator user-defined function or MEX file you are calling

mexCallMATLAB (C and Fortran)

1-271

If functionName is an operator place the operator inside a pair of single quotes forexample +

Returns0 if successful and a nonzero value if unsuccessful

DescriptionCall mexCallMATLAB to invoke internal MATLAB numeric functions MATLABoperators user-defined functions or other MEX files Both mexCallMATLAB andmexEvalString execute MATLAB commands Use mexCallMATLAB for returningresults (left side arguments) back to the MEX file The mexEvalString function cannotreturn values to the MEX file

For a complete description of the input and output arguments passed to functionNamesee mexFunction

Error HandlingIf functionName detects an error MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt To trap errors use the mexCallMATLABWithTrapfunction

Limitationsbull Avoid using the mexCallMATLAB function in Simulinkreg S-functions If you do do not

store the resulting plhs mxArray pointers in any S-function block state that persistsafter the MEX function finishes Outputs of mexCallMATLAB have temporary scopeand are automatically destroyed at the end of the MEX function call

bull It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLABFor example this function returns two variables but only assigns one of them a value

function [ab] = foo(c)a = 2c

1 API Reference

1-272

If you then call foo using mexCallMATLAB the unassigned output variable is nowtype mxUNKNOWN_CLASS

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexevalstringcbull mexcallmatlabwithtrapc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxisclassc

See AlsomexFunction mexCallMATLABWithTrap mexEvalString mxDestroyArray

Tipsbull MATLAB allocates dynamic memory to store the arrays in plhs for mexCallMATLAB

MATLAB automatically deallocates the dynamic memory when you exit the MEX fileHowever if heap space is at a premium call mxDestroyArray when you are finishedwith the arrays in plhs

Note The plhs argument for mexCallMATLAB is not the same as the plhs formexFunction Do not destroy an mxArray returned in plhs for mexFunction

mexCallMATLAB (C and Fortran)

1-273

Introduced before R2006a

1 API Reference

1-274

mexCallMATLABWithTrap (C and Fortran)Call MATLAB function user-defined function or MEX-file and capture error information

C Syntaxinclude mexhmxArray mexCallMATLABWithTrap(int nlhs mxArray plhs[] int nrhs mxArray prhs[] const char functionName)

Fortran Syntaxinclude fintrfhmwPointer mexCallMATLABWithTrap(nlhs plhs nrhs prhs functionName)integer4 nlhs nrhsmwPointer plhs() prhs()character() functionName

ArgumentsFor more information about arguments see mexCallMATLAB

nlhsNumber of desired output arguments

plhsArray of pointers to output arguments

nrhsNumber of input arguments

prhsArray of pointers to input arguments

functionNameCharacter string containing the name of the MATLAB built-in function operatorfunction or MEX-file that you are calling

mexCallMATLABWithTrap (C and Fortran)

1-275

ReturnsNULL if no error occurred otherwise a pointer to an mxArray of class MException

DescriptionThe mexCallMATLABWithTrap function performs the same function as mexCallMATLABHowever if MATLAB detects an error when executing functionName MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexCallMATLABWithTrap For information about MException see ldquoRespond to anExceptionrdquo

See AlsomexCallMATLAB MException

Introduced in R2008b

1 API Reference

1-276

mexErrMsgIdAndTxt (C and Fortran)Display error message with identifier and return to MATLAB prompt

C Syntaxinclude mexhvoid mexErrMsgIdAndTxt(const char errorid const char errormsg )

Fortran Syntaxinclude fintrfhsubroutine mexErrMsgIdAndTxt(errorid errormsg)character() errorid errormsg

Argumentserrorid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

errormsgString to display In C the string can include conversion specifications used by theANSIreg C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexErrMsgIdAndTxt function writes an error message to the MATLAB windowFor more information see the error function syntax statement using a message

mexErrMsgIdAndTxt (C and Fortran)

1-277

identifier After the error message prints MATLAB terminates the MEX file and returnscontrol to the MATLAB prompt

Calling mexErrMsgIdAndTxt does not clear the MEX file from memory SomexErrMsgIdAndTxt does not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgIdAndTxt automatically frees the allocated memory

Note If you get warnings when using mexErrMsgIdAndTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errorid and errormsg the mexErrMsgIdAndTxt functiondetermines where the error occurred and displays the following information Forexample in the function foo mexErrMsgIdAndTxt displays

Error using foo

If you compile your MEX file with the MinGW-w64 compiler see the limitations withexception handling topic in ldquoTroubleshooting and Limitations Compiling CC++ MEXFiles with MinGW-w64rdquo

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrcbull matrixDividecbull timestwoFbull xtimesyF

1 API Reference

1-278

Validate char Input

The following code snippet checks if input argument prhs[0] is a string If not thecode displays a warning If there is an error reading the input string the code displaysan error message and terminates the MEX file

char bufint buflen

if (mxIsChar(prhs[0])) if (mxGetString(prhs[0] buf buflen) == 0) mexPrintf(The input string is sn buf) else mexErrMsgIdAndTxt(MyProgConvertString Could not convert string data) exit MEX file else mexWarnMsgIdAndTxt(MyProgInputString Input should be a string to print properly)

continue with processing

See Alsoerror | mexWarnMsgIdAndTxt

TopicsldquoMemory Considerations for Class DestructorsrdquoldquoTroubleshooting and Limitations Compiling CC++ MEX Files with MinGW-w64rdquo

Introduced before R2006a

mexErrMsgIdAndTxt (C and Fortran)

1-279

mexErrMsgTxt (C and Fortran)Display error message and return to MATLAB prompt

Note mexErrMsgTxt is not recommended Use mexErrMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexErrMsgTxt(const char errormsg)

Fortran Syntaxsubroutine mexErrMsgTxt(errormsg)character() errormsg

Argumentserrormsg

String containing the error message to display

DescriptionmexErrMsgTxt writes an error message to the MATLAB window After the errormessage prints MATLAB terminates the MEX-file and returns control to the MATLABprompt

Calling mexErrMsgTxt does not clear the MEX-file from memory So mexErrMsgTxtdoes not invoke the function registered through mexAtExit

If your application called mxCalloc or one of the mxCreate routines to allocatememory mexErrMsgTxt automatically frees the allocated memory

1 API Reference

1-280

Note If you get warnings when using mexErrMsgTxt you might have a memorymanagement compatibility problem For more information see ldquoMemory ManagementIssuesrdquo

RemarksIn addition to the errormsg the mexerrmsgtxt function determines where the erroroccurred and displays the following information If an error labeled Print my errormessage occurs in the function foo mexerrmsgtxt displays

Error using fooPrint my error message

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexErrMsgTxt (C and Fortran)

1-281

mexEvalString (C and Fortran)Execute MATLAB command in caller workspace

C Syntaxinclude mexhint mexEvalString(const char command)

Fortran Syntaxinclude fintrfhinteger4 mexEvalString(command)character() command

Argumentscommand

String containing MATLAB command to execute

Returns0 if successful and 1 if an error occurs

DescriptionCall mexEvalString to invoke a MATLAB command in the workspace of the caller

mexEvalString and mexCallMATLAB both execute MATLAB commands UsemexCallMATLAB for returning results (left side arguments) back to the MEX file ThemexEvalString function cannot return values to the MEX file

1 API Reference

1-282

All arguments that appear to the right of an equal sign in the command string must becurrent variables of the caller workspace

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction For more information see ldquoVariable Namesrdquo

Error HandlingIf command detects an error MATLAB returns control to the MEX-file andmexEvalString returns 1 If you want to trap errors use themexEvalStringWithTrap function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexevalstringc

See AlsomexCallMATLAB mexEvalStringWithTrap

Introduced before R2006a

mexEvalString (C and Fortran)

1-283

mexEvalStringWithTrap (C and Fortran)Execute MATLAB command in caller workspace and capture error information

C Syntaxinclude mexhmxArray mexEvalStringWithTrap(const char command)

Fortran Syntaxinclude fintrfhmwPointer mexEvalStringWithTrap(command)character() command

Argumentscommand

String containing the MATLAB command to execute

ReturnsObject ME of class MException

DescriptionThe mexEvalStringWithTrap function performs the same function as mexEvalStringHowever if MATLAB detects an error when executing command MATLAB returnscontrol to the line in the MEX-file immediately following the call tomexEvalStringWithTrap

1 API Reference

1-284

See AlsomexEvalString MException mexCallMATLAB

Introduced before R2006a

mexEvalStringWithTrap (C and Fortran)

1-285

mexFunction (C and Fortran)Entry point to CC++ or Fortran MEX file

C Syntaxinclude mexhvoid mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

Fortran Syntaxinclude fintrfhsubroutine mexFunction(nlhs plhs nrhs prhs)integer nlhs nrhsmwPointer plhs() prhs()

Argumentsnlhs

Number of expected output mxArraysplhs

Array of pointers to the expected output mxArraysnrhs

Number of input mxArraysprhs

Array of pointers to the input mxArrays Do not modify any prhs values in yourMEX file Changing the data in these read-only mxArrays can produce undesiredside effects

1 API Reference

1-286

DescriptionmexFunction is not a routine you call Rather mexFunction is the name of the gatewayfunction in C (subroutine in Fortran) which every MEX file requires When you invoke aMEX function MATLAB software finds and loads the corresponding MEX file of thesame name MATLAB then searches for a symbol named mexFunction within the MEXfile If it finds one it calls the MEX function using the address of the mexFunctionsymbol MATLAB displays an error message if it cannot find a routine namedmexFunction inside the MEX file

When you invoke a MEX file MATLAB automatically seeds nlhs plhs nrhs and prhswith the calling arguments In the syntax of the MATLAB language functions have thegeneral form

[abc] = fun(def)

where the denotes more items of the same format The abc are left-sideoutput arguments and the def are right-side input arguments The argumentsnlhs and nrhs contain the number of left side and right side arguments respectivelyprhs is an array of mxArray pointers whose length is nrhs plhs is an array whoselength is nlhs where your function must set pointers for the output mxArrays

Note It is possible to return an output value even if nlhs = 0 which corresponds toreturning the result in the ans variable

To experiment with passing input arguments build the mexfunctionc examplefollowing the instructions in ldquoTable of MEX File Source Code Filesrdquo

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctioncbull mexlockfF

mexFunction (C and Fortran)

1-287

See Also

TopicsldquoIntroducing MEX Filesrdquo

Introduced before R2006a

1 API Reference

1-288

mexFunctionName (C and Fortran)Name of current MEX function

C Syntaxinclude mexhconst char mexFunctionName(void)

Fortran Syntaxinclude fintrfhcharacter() mexFunctionName()

ReturnsName of the current MEX function

DescriptionmexFunctionName returns the name of the current MEX function

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

Introduced before R2006a

mexFunctionName (C and Fortran)

1-289

mexGet (C)Value of specified graphics property

Note Do not use mexGet Use mxGetProperty instead

C Syntaxinclude mexhconst mxArray mexGet(double handle const char property)

Argumentshandle

Handle to a particular graphics objectproperty

Graphics property

ReturnsValue of the specified property in the specified graphics object on success Returns NULLon failure Do not modify the return argument from mexGet Changing the data in aconst (read-only) mxArray can produce undesired side effects

DescriptionCall mexGet to get the value of the property of a certain graphics object mexGet is theAPI equivalent of the MATLAB get function To set a graphics property value callmexSet

1 API Reference

1-290

See AlsomxGetProperty mxSetProperty

mexGet (C)

1-291

mexGetVariable (C and Fortran)Copy of variable from specified workspace

C Syntaxinclude mexhmxArray mexGetVariable(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariable(workspace varname)character() workspace varname

Argumentsworkspace

Specifies where mexGetVariable searches for array varname The possible valuesarebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of the variable to copy

ReturnsCopy of the variable on success Returns NULL in C (0 on Fortran) on failure A commoncause of failure is specifying a variable that is not currently in the workspace Perhapsthe variable was in the workspace at one time but has since been cleared

1 API Reference

1-292

DescriptionCall mexGetVariable to get a copy of the specified variable The returned mxArraycontains a copy of all the data and characteristics that the variable had in the otherworkspace Modifications to the returned mxArray do not affect the variable in theworkspace unless you write the copy back to the workspace with mexPutVariable

Use mxDestroyArray to destroy the mxArray created by this routine when you arefinished with it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

See AlsomexGetVariablePtr mexPutVariable mxDestroyArray

mexGetVariable (C and Fortran)

1-293

mexGetVariablePtr (C and Fortran)Read-only pointer to variable from another workspace

C Syntaxinclude mexhconst mxArray mexGetVariablePtr(const char workspace const char varname)

Fortran Syntaxinclude fintrfhmwPointer mexGetVariablePtr(workspace varname)character() workspace varname

Argumentsworkspace

Specifies which workspace you want mexGetVariablePtr to search The possiblevalues arebase Search for the variable in the base workspacecaller Search for the variable in the caller workspaceglobal Search for the variable in the global workspace

varnameName of a variable in another workspace This is a variable name not an mxArraypointer

ReturnsRead-only pointer to the mxArray on success Returns NULL in C (0 in Fortran) onfailure

1 API Reference

1-294

DescriptionCall mexGetVariablePtr to get a read-only pointer to the specified variable varnameinto your MEX-file workspace This command is useful for examining an mxArrays dataand characteristics If you want to change data or characteristics use mexGetVariable(along with mexPutVariable) instead of mexGetVariablePtr

If you simply want to examine data or characteristics mexGetVariablePtr offerssuperior performance because the caller wants to pass only a pointer to the array

See AlsomexGetVariable

Introduced before R2006a

mexGetVariablePtr (C and Fortran)

1-295

mexIsLocked (C and Fortran)Determine if MEX-file is locked

C Syntaxinclude mexhbool mexIsLocked(void)

Fortran Syntaxinclude fintrfhinteger4 mexIsLocked()

ReturnsLogical 1 (true) if the MEX-file is locked logical 0 (false) if the file is unlocked

DescriptionCall mexIsLocked to determine if the MEX-file is locked By default MEX-files areunlocked meaning you can clear the MEX-file at any time

To unlock a MEX-file call mexUnlock

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-296

See AlsomexLock mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexIsLocked (C and Fortran)

1-297

mexLock (C and Fortran)Prevent clearing MEX-file from memory

C Syntaxinclude mexhvoid mexLock(void)

Fortran Syntaxinclude fintrfhsubroutine mexLock()

DescriptionBy default MEX files are unlocked meaning you can clear them at any time CallmexLock to prohibit clearing a MEX file

To unlock a MEX file call mexUnlock Do not use the munlock function

mexLock increments a lock count If you call mexLock n times call mexUnlock n timesto unlock your MEX file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

1 API Reference

1-298

See AlsomexIsLocked mexMakeArrayPersistent mexMakeMemoryPersistent mexUnlockclear

mexLock (C and Fortran)

1-299

mexMakeArrayPersistent (C and Fortran)Make array persist after MEX file completes

C Syntaxinclude mexhvoid mexMakeArrayPersistent(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mexMakeArrayPersistent(pm)mwPointer pm

Argumentspm

Pointer to an mxArray created by an mxCreate function

DescriptionBy default an mxArray allocated by an mxCreate function is not persistent TheMATLAB memory management facility automatically frees a nonpersistent mxArraywhen the MEX function finishes If you want the mxArray to persist through multipleinvocations of the MEX function call the mexMakeArrayPersistent function

Do not assign an array created with the mexMakeArrayPersistent function to theplhs output argument of a MEX file

Note If you create a persistent mxArray you are responsible for destroying it usingmxDestroyArray when the MEX file is cleared If you do not destroy a persistentmxArray MATLAB leaks memory See mexAtExit to see how to register a function that

1 API Reference

1-300

gets called when the MEX file is cleared See mexLock to see how to lock your MEX fileso that it is never cleared

See AlsomexAtExit mxDestroyArray mexLock mexMakeMemoryPersistent and themxCreate functions

Introduced before R2006a

mexMakeArrayPersistent (C and Fortran)

1-301

mexMakeMemoryPersistent (C and Fortran)Make memory allocated by MATLAB software persist after MEX-function completes

C Syntaxinclude mexhvoid mexMakeMemoryPersistent(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mexMakeMemoryPersistent(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of memory allocated by one of the MATLAB memoryallocation routines

DescriptionBy default memory allocated by MATLAB is nonpersistent so it is freed automaticallywhen the MEX function finishes If you want the memory to persist callmexMakeMemoryPersistent

Note If you create persistent memory you are responsible for freeing it when the MEXfunction is cleared If you do not free the memory MATLAB leaks memory To freememory use mxFree See mexAtExit to see how to register a function that gets calledwhen the MEX function is cleared See mexLock to see how to lock your MEX function sothat it is never cleared

1 API Reference

1-302

See AlsomexAtExit mexLock mexMakeArrayPersistent mxCalloc mxFree mxMallocmxRealloc

Introduced before R2006a

mexMakeMemoryPersistent (C and Fortran)

1-303

mexPrintf (C and Fortran)ANSI C PRINTF-style output routine

C Syntaxinclude mexhint mexPrintf(const char message )

Fortran Syntaxinclude fintrfhinteger4 mexPrintf(message)character() message

Argumentsmessage

String to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

ReturnsNumber of characters printed including characters specified with backslash codes suchas n and b

1 API Reference

1-304

DescriptionThis routine prints a string on the screen and in the diary (if the diary is in use) Itprovides a callback to the standard C printf routine already linked inside MATLABsoftware which avoids linking the entire stdio library into your MEX file

In a C MEX file call mexPrintf instead of printf to display a string

Note If you want the literal in your message use in the message string since hasspecial meaning to printf Failing to do so causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See Alsosprintf mexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexPrintf (C and Fortran)

1-305

mexPutVariable (C and Fortran)Array from MEX-function into specified workspace

C Syntaxinclude mexhint mexPutVariable(const char workspace const char varname const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mexPutVariable(workspace varname pm)character() workspace varnamemwPointer pm

Argumentsworkspace

Specifies scope of the array you are copying Values for workspace arebase Copy mxArray to the base workspacecaller Copy mxArray to the caller workspaceglobal Copy mxArray to the list of global variables

varnameName of mxArray in the workspace

pmPointer to the mxArray

1 API Reference

1-306

Returns0 on success 1 on failure A possible cause of failure is that pm is NULL in C (0 inFortran)

DescriptionCall mexPutVariable to copy the mxArray at pointer pm from your MEX-function intothe specified workspace MATLAB software gives the name varname to the copiedmxArray in the receiving workspace

mexPutVariable makes the array accessible to other entities such as MATLAB user-defined functions or other MEX-functions

If a variable of the same name exists in the specified workspace mexPutVariableoverwrites the previous contents of the variable with the contents of the new mxArrayFor example suppose the MATLAB workspace defines variable Peaches as

Peaches1 2 3 4

and you call mexPutVariable to copy Peaches into the same workspace

mexPutVariable(base Peaches pm)

The value passed by mexPutVariable replaces the old value of Peaches

Do not use MATLAB function names for variable names Common variable names thatconflict with function names include i j mode char size or path To determinewhether a particular name is associated with a MATLAB function use the whichfunction

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexgetarrayc

mexPutVariable (C and Fortran)

1-307

See AlsomexGetVariable

1 API Reference

1-308

mexSet (C)Set value of specified graphics property

Note Do not use mexSet Use mxSetProperty instead

C Syntaxinclude mexhint mexSet(double handle const char property mxArray value)

Argumentshandle

Handle to a particular graphics objectproperty

String naming a graphics propertyvalue

Pointer to an mxArray holding the new value to assign to the property

Returns0 on success 1 on failure Possible causes of failure include

bull Specifying a nonexistent propertybull Specifying an illegal value for that property for example specifying a string value for

a numerical property

mexSet (C)

1-309

DescriptionCall mexSet to set the value of the property of a certain graphics object mexSet is theAPI equivalent of the MATLAB set function To get the value of a graphics property callmexGet

See AlsomxGetProperty mxSetProperty

1 API Reference

1-310

mexSetTrapFlag (C and Fortran)Control response of MEXCALLMATLAB to errors

C Syntaxinclude mexhvoid mexSetTrapFlag(int trapflag)

Note mexSetTrapFlag will be removed in a future version UsemexCallMATLABWithTrap instead

Fortran Syntaxsubroutine mexSetTrapFlag(trapflag)integer4 trapflag

Argumentstrapflag

Control flag Possible values are0 On error control returns to the MATLAB prompt1 On error control returns to your MEX-file

DescriptionCall mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB

If you do not call mexSetTrapFlag then whenever MATLAB detects an error in a call tomexCallMATLAB MATLAB automatically terminates the MEX-file and returns controlto the MATLAB prompt Calling mexSetTrapFlag with trapflag set to 0 is equivalentto not calling mexSetTrapFlag at all

mexSetTrapFlag (C and Fortran)

1-311

If you call mexSetTrapFlag and set the trapflag to 1 then whenever MATLABdetects an error in a call to mexCallMATLAB MATLAB does not automatically terminatethe MEX-file Rather MATLAB returns control to the line in the MEX-file immediatelyfollowing the call to mexCallMATLAB The MEX-file is then responsible for taking anappropriate response to the error

If you call mexSetTrapFlag the value of the trapflag you set remains in effect untilthe next call to mexSetTrapFlag within that MEX-file or if there are no more calls tomexSetTrapFlag until the MEX-file exits If a routine defined in a MEX-file callsanother MEX-file MATLAB

1 Saves the current value of the trapflag in the first MEX-file2 Calls the second MEX-file with the trapflag initialized to 0 within that file3 Restores the saved value of trapflag in the first MEX-file when the second MEX-

file exits

See AlsomexCallMATLAB mexCallMATLABWithTrap mexAtExit mexErrMsgTxt

Introduced in R2008b

1 API Reference

1-312

mexUnlock (C and Fortran)Allow clearing MEX-file from memory

C Syntaxinclude mexhvoid mexUnlock(void)

Fortran Syntaxinclude fintrfhsubroutine mexUnlock()

DescriptionBy default MEX-files are unlocked meaning you can clear them at any time CallingmexLock locks a MEX-file so that you cannot clear it from memory Call mexUnlock toremove the lock

mexLock increments a lock count If you called mexLock n times call mexUnlock ntimes to unlock your MEX-file

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

mexUnlock (C and Fortran)

1-313

See AlsomexIsLocked mexLock mexMakeArrayPersistent mexMakeMemoryPersistentclear

1 API Reference

1-314

mexWarnMsgIdAndTxt (C and Fortran)Warning message with identifier

C Syntaxinclude mexhvoid mexWarnMsgIdAndTxt(const char warningid const char warningmsg )

Fortran Syntaxinclude fintrfhsubroutine mexWarnMsgIdAndTxt(warningid warningmsg)character() warningid warningmsg

Argumentswarningid

String containing a MATLAB message identifier For information on creatingidentifiers see ldquoMessage Identifiersrdquo

warningmsgString to display In C the string can include conversion specifications used by theANSI C printf function

In C any arguments used in the message Each argument must have a correspondingconversion specification Refer to your C documentation for printf conversiontables

DescriptionThe mexWarnMsgIdAndTxt function writes a warning message to the MATLABcommand prompt The warnings displayed are the same as warnings issued by the

mexWarnMsgIdAndTxt (C and Fortran)

1-315

MATLAB warning function To control the information displayed or suppressed call thewarning function with the desired settings before calling your MEX-file

Unlike mexErrMsgIdAndTxt calling mexWarnMsgIdAndTxt does not terminate theMEX-file

See AlsomexErrMsgIdAndTxt warning

Introduced before R2006a

1 API Reference

1-316

mexWarnMsgTxt (C and Fortran)Warning message

Note mexWarnMsgTxt is not recommended Use mexWarnMsgIdAndTxt instead

C Syntaxinclude mexhvoid mexWarnMsgTxt(const char warningmsg)

Fortran Syntaxsubroutine mexWarnMsgTxt(warningmsg)character() warningmsg

Argumentswarningmsg

String containing the warning message to display

DescriptionmexWarnMsgTxt causes MATLAB software to display the contents of warningmsgmexWarnMsgTxt does not terminate the MEX-file

See AlsomexErrMsgIdAndTxt mexWarnMsgIdAndTxt

mexWarnMsgTxt (C and Fortran)

1-317

mwIndex (C and Fortran)Type for index values

DescriptionmwIndex is a type that represents index values such as indices into arrays Use thisfunction for cross-platform flexibility By default mwIndex is equivalent to int in CWhen using the mex -largeArrayDims switch mwIndex is equivalent to size_t in CIn Fortran mwIndex is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwIndex is a preprocessor macro The Fortran header file containing thistype is

include fintrfh

See Alsomex mwSize mwSignedIndex

Introduced before R2006a

1 API Reference

1-318

mwPointer (Fortran)Platform-independent pointer type

DescriptionmwPointer is a preprocessor macro that declares the appropriate Fortran typerepresenting a pointer to an mxArray or to other data that is not of a native Fortrantype such as memory allocated by mxMalloc On 32-bit platforms the Fortran type thatrepresents a pointer is INTEGER4 on 64-bit platforms it is INTEGER8 The Fortranpreprocessor translates mwPointer to the Fortran declaration that is appropriate for theplatform on which you compile your file

If your Fortran compiler supports preprocessing you can use mwPointer to declarefunctions arguments and variables that represent pointers If you cannot usemwPointer ensure that your declarations have the correct size for the platform on whichyou are compiling Fortran code

The Fortran header file containing this type is

include fintrfh

ExamplesThis example declares the arguments for mexFunction in a Fortran MEX file

subroutine mexFunction(nlhs plhs nrhs prhs)mwPointer plhs() prhs()integer nlhs nrhs

For additional examples see the Fortran files with names ending in F in thematlabrootexternexamples folder

Introduced in R2006a

mwPointer (Fortran)

1-319

mwSignedIndex (C and Fortran)Signed integer type for size values

DescriptionmwSignedIndex is a signed integer type that represents size values such as arraydimensions Use this function for cross-platform flexibility By default mwSignedIndexis equivalent to ptrdiff_t in C++ In Fortran mwSignedIndex is similarly equivalentto INTEGER4 or INTEGER8 based on platform and compilation flags

The C header file containing this type is

include matrixh

The Fortran header file containing this type is

include fintrfh

See AlsomwSize mwIndex

Introduced in R2009a

1 API Reference

1-320

mwSize (C and Fortran)Type for size values

DescriptionmwSize is a type that represents size values such as array dimensions Use this functionfor cross-platform flexibility By default mwSize is equivalent to size_t in C mwSize isan unsigned type meaning a nonnegative integer

When using the mex -compatibleArrayDims switch mwSize is equivalent to int in CIn Fortran mwSize is similarly equivalent to INTEGER4 or INTEGER8 based onplatform and compilation flags

The C header file containing this type is

include matrixh

In Fortran mwSize is a preprocessor macro The Fortran header file containing this typeis

include fintrfh

See Alsomex mwIndex mwSignedIndex

Introduced before R2006a

mwSize (C and Fortran)

1-321

mxAddField (C and Fortran)Add field to structure array

C Syntaxinclude matrixhextern int mxAddField(mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxAddField(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of the field you want to add

ReturnsField number on success or -1 if inputs are invalid or an out-of-memory conditionoccurs

1 API Reference

1-322

DescriptionCall mxAddField to add a field to a structure array Create the values with themxCreate functions and use mxSetFieldByNumber to set the individual values for thefield

See AlsomxRemoveField mxSetFieldByNumber

Introduced before R2006a

mxAddField (C and Fortran)

1-323

mxArray (C)Type for MATLAB array

DescriptionThe fundamental type underlying MATLAB data For information on how the MATLABarray works with MATLAB-supported variables see ldquoMATLAB Datardquo

mxArray is a C language opaque type

All C MEX-files start with a gateway routine called mexFunction which requiresmxArray for both input and output parameters For information about the C MEX-filegateway routine see ldquoComponents of MEX Filerdquo

Once you have MATLAB data in your MEX-file use functions in the Matrix Library tomanipulate the data and functions in the MEX Library to perform operations in theMATLAB environment You use mxArray to pass data to and from these functions

Use any of the mxCreate functions to create data and the correspondingmxDestroyArray function to free memory

The header file containing this type is

include matrixh

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomexFunction mxClassID mxCreateDoubleMatrix mxCreateNumericArraymxCreateString mxDestroyArray mxGetData mxSetData

1 API Reference

1-324

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquobull For troubleshooting mxArray errors in other MathWorks products search the

documentation for that product or see MATLAB Answerstrade topic Subscripting intoan mxArray is not supported

Introduced before R2006a

mxArray (C)

1-325

mxArrayToString (C)Array to string

C Syntaxinclude matrixhchar mxArrayToString(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string Returns NULL on failure Possible reasons for failure include out ofmemory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToString to copy the character data of an mxCHAR array into a C-stylestring The C-style string is always terminated with a NULL character and stored incolumn-major order

If the array contains multiple rows the rows are copied column-wise into a single array

This function is similar to mxGetString except that

bull It does not require the length of the string as an inputbull It supports both multi-byte and single-byte encoded characters On Windows and

Linuxreg platforms the default encoding is specified by the user locale setting

1 API Reference

1-326

mxArrayToString does not free the dynamic memory that the char pointer points toTherefore you typically free the C-style string (using mxFree) immediately after youhave finished using it

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexatexitc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxArrayToUTF8String mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetString

Introduced before R2006a

mxArrayToString (C)

1-327

mxArrayToUTF8String (C)Array to string in UTF-8 encoding

C Syntaxinclude matrixhchar mxArrayToUTF8String(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to mxCHAR array

ReturnsC-style string in UTF-8 encoding Returns NULL on failure Possible reasons for failureinclude out of memory and specifying an array that is not an mxCHAR array

DescriptionCall mxArrayToUTF8String to copy the character data of an mxCHAR array into a C-style string The data is stored in column-major order If the array contains multiplerows the rows are copied column-wise into a single array

mxArrayToUTF8String does not free the dynamic memory that the char pointer pointsto Use mxFree to free memory

See AlsomxArrayToString mxFree mxCreateCharArray mxCreateString mxGetString

1 API Reference

1-328

Introduced in R2015a

mxArrayToUTF8String (C)

1-329

mxAssert (C)Check assertion value for debugging purposes

C Syntaxinclude matrixhvoid mxAssert(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionLike the ANSI C assert macro mxAssert checks the value of an assertion andcontinues execution only if the assertion holds If expr evaluates to logical 1 (true)mxAssert does nothing If expr evaluates to logical 0 (false) mxAssert terminates theMEX file and prints an error to the MATLAB command window The error contains theexpression of the failed assertion the file name and line number where the failedassertion occurred and the error_message text The error_message allows you tospecify a better description of why the assertion failed Use an empty string if you do notwant a description to follow the failed assertion message

The mex script turns off these assertions when building optimized MEX functions so useassertions for debugging purposes only To use mxAssert build the MEX file using themex -g filename syntax

Assertions are a way of maintaining internal consistency of logic Use them to keepyourself from misusing your own code and to prevent logical errors from propagating

1 API Reference

1-330

before they are caught Do not use assertions to prevent users of your code from misusingit

Assertions can be taken out of your code by the C preprocessor You can use these checksduring development and then remove them when the code works properly letting youuse them for troubleshooting during development without slowing down the finalproduct

See AlsomxAssertS mexErrMsgIdAndTxt

Introduced before R2006a

mxAssert (C)

1-331

mxAssertS (C)Check assertion value without printing assertion text

C Syntaxinclude matrixhvoid mxAssertS(int expr char error_message)

Argumentsexpr

Value of assertionerror_message

Description of why assertion failed

DescriptionmxAssertS is like mxAssert except mxAssertS does not print the text of the failedassertion

See AlsomxAssert

Introduced before R2006a

1 API Reference

1-332

mxCalcSingleSubscript (C and Fortran)Offset from first element to desired element

C Syntaxinclude matrixhmwIndex mxCalcSingleSubscript(const mxArray pm mwSize nsubs mwIndex subs)

Fortran Syntaxinclude fintrfhmwIndex mxCalcSingleSubscript(pm nsubs subs)mwPointer pmmwSize nsubsmwIndex subs

Argumentspm

Pointer to an mxArraynsubs

Number of elements in the subs array Typically you set nsubs equal to the numberof dimensions in the mxArray that pm points to

subsAn array of integers Each value in the array specifies that dimensions subscript InC syntax the value in subs[0] specifies the row subscript and the value insubs[1] specifies the column subscript Use zero-based indexing for subscripts Forexample to express the starting element of a two-dimensional mxArray in subs setsubs[0] to 0 and subs[1] to 0

In Fortran syntax the value in subs(1) specifies the row subscript and the value insubs(2) specifies the column subscript Use 1-based indexing for subscripts For

mxCalcSingleSubscript (C and Fortran)

1-333

example to express the starting element of a two-dimensional mxArray in subs setsubs(1) to 1 and subs(2) to 1

ReturnsThe number of elements or index between the start of the mxArray and the specifiedsubscript This number is the linear index equivalent of the subscripts Many MatrixLibrary routines (for example mxGetField) require an index as an argument

If subs describes the starting element of an mxArray mxCalcSingleSubscriptreturns 0 If subs describes the final element of an mxArray mxCalcSingleSubscriptreturns N-1 (where N is the total number of elements)

DescriptionCall mxCalcSingleSubscript to determine how many elements there are between thebeginning of the mxArray and a given element of that mxArray The function convertssubscripts to linear indices

For example given a subscript like (57) mxCalcSingleSubscript returns thedistance from the first element of the array to the (57) element Remember that themxArray data type internally represents all data elements in a one-dimensional array nomatter how many dimensions the MATLAB mxArray appears to have For examplesshowing the internal representation see ldquoData Storagerdquo

Avoid using mxCalcSingleSubscript to traverse the elements of an array In C it ismore efficient to find the starting address of the array and then use pointerautoincrementing to access successive elements For example to find the startingaddress of a numerical array call mxGetPr or mxGetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

1 API Reference

1-334

See AlsomxGetCell mxSetCell

Introduced before R2006a

mxCalcSingleSubscript (C and Fortran)

1-335

mxCalloc (C and Fortran)Allocate dynamic memory for array initialized to 0 using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxCalloc(mwSize n mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxCalloc(n size)mwSize n size

Argumentsn

Number of elements to allocate This must be a nonnegative numbersize

Number of bytes per element (The C sizeof operator calculates the number of bytesper element)

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxCalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxCalloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-336

DescriptionmxCalloc allocates contiguous heap space sufficient to hold n elements of size byteseach and initializes this newly allocated memory to 0 Use mxCalloc instead of theANSI C calloc function to allocate memory in MATLAB applications

In MEX files but not MAT or engine applications mxCalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatacbull phonebookcbull revordc

mxCalloc (C and Fortran)

1-337

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxsetdimensionsc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistentmxDestroyArray mxFree mxMalloc mxRealloc

Introduced before R2006a

1 API Reference

1-338

mxChar (C)Type for string array

DescriptionMATLAB stores an mxArray string as type mxChar to represent the C-style char typeMATLAB uses 16-bit unsigned integer character encoding for Unicode characters

The header file containing this type is

include matrixh

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxcreatecharmatrixfromstrc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCharArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

mxChar (C)

1-339

Introduced before R2006a

1 API Reference

1-340

mxClassID (C)Enumerated value identifying class of array

C Syntaxtypedef enum mxUNKNOWN_CLASS mxCELL_CLASS mxSTRUCT_CLASS mxLOGICAL_CLASS mxCHAR_CLASS mxVOID_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_CLASS

Undetermined class You cannot specify this category for an mxArray however ifmxGetClassID cannot identify the class it returns this value

mxCELL_CLASSIdentifies a cell mxArray

mxSTRUCT_CLASSIdentifies a structure mxArray

mxClassID (C)

1-341

mxLOGICAL_CLASSIdentifies a logical mxArray an mxArray of mxLogical data

mxCHAR_CLASSIdentifies a string mxArray an mxArray whose data is represented as mxChar

mxVOID_CLASSReserved

mxDOUBLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxSINGLE_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT8_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT16_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT32_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

1 API Reference

1-342

mxINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxUINT64_CLASSIdentifies a numeric mxArray whose data is stored as the type specified in theMATLAB Primitive Types table

mxFUNCTION_CLASSIdentifies a function handle mxArray

DescriptionVarious Matrix Library functions require or return an mxClassID argumentmxClassID identifies how the mxArray represents its data elements

The following table shows MATLAB types with their equivalent C types Use the typefrom the right-most column for reading mxArrays with the mxClassID value shown inthe left columnMATLAB Primitive Types

mxClassID Value MATLAB Type MEX Type C Primitive TypemxINT8_CLASS int8 int8_T char bytemxUINT8_CLASS uint8 uint8_T unsigned char bytemxINT16_CLASS int16 int16_T shortmxUINT16_CLASS uint16 uint16_T unsigned shortmxINT32_CLASS int32 int32_T intmxUINT32_CLASS uint32 uint32_T unsigned intmxINT64_CLASS int64 int64_T long longmxUINT64_CLASS uint64 uint64_T unsigned long longmxSINGLE_CLASS single float floatmxDOUBLE_CLASS double double double

mxClassID (C)

1-343

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetClassID mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-344

mxClassIDFromClassName (Fortran)Identifier corresponding to class

Fortran Syntaxinclude fintrfhinteger4 mxClassIDFromClassName(classname)character() classname

Argumentsclassname

character array specifying a MATLAB class name For a list of valid classnamechoices see the mxIsClass reference page

ReturnsNumeric identifier used internally by MATLAB software to represent the MATLAB classclassname Returns unknown if classname is not a recognized MATLAB class

DescriptionUse mxClassIDFromClassName to obtain an identifier for any MATLAB class Thisfunction is most commonly used to provide a classid argument tomxCreateNumericArray and mxCreateNumericMatrix

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matsqint8F

mxClassIDFromClassName (Fortran)

1-345

See AlsomxGetClassName mxCreateNumericArray mxCreateNumericMatrix mxIsClass

Introduced before R2006a

1 API Reference

1-346

mxComplexity (C)Flag specifying whether array has imaginary components

C Syntaxtypedef enum mxComplexity mxREAL=0 mxCOMPLEX

ConstantsmxREAL

Identifies an mxArray with no imaginary componentsmxCOMPLEX

Identifies an mxArray with imaginary components

DescriptionVarious Matrix Library functions require an mxComplexity argument You can set anmxComplex argument to either mxREAL or mxCOMPLEX

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptc

See AlsomxCreateNumericArray mxCreateDoubleMatrix mxCreateSparse

mxComplexity (C)

1-347

Introduced before R2006a

1 API Reference

1-348

mxCopyCharacterToPtr (Fortran)CHARACTER values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyCharacterToPtr(y px n)character() ymwPointer pxmwSize n

Argumentsy

character Fortran arraypx

Pointer to character or name arrayn

Number of elements to copy

DescriptionmxCopyCharacterToPtr copies n character values from the Fortran characterarray y into the MATLAB character vector pointed to by px This subroutine is essentialfor copying character data between MATLAB pointer arrays and ordinary Fortrancharacter arrays

See AlsomxCopyPtrToCharacter mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

mxCopyCharacterToPtr (Fortran)

1-349

Introduced before R2006a

1 API Reference

1-350

mxCopyComplex16ToPtr (Fortran)COMPLEX16 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex16ToPtr(y pr pi n)complex16 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX16 Fortran arraypr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex16ToPtr copies n COMPLEX16 values from the Fortran COMPLEX16array y into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex16ToPtr (Fortran)

1-351

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyPtrToComplex16 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-352

mxCopyComplex8ToPtr (Fortran)COMPLEX8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyComplex8ToPtr(y pr pi n)complex8 y(n)mwPointer pr pimwSize n

Argumentsy

COMPLEX8 Fortran arraypr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyComplex8ToPtr copies n COMPLEX8 values from the Fortran COMPLEX8 arrayy into the MATLAB arrays pointed to by pr and pi

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyComplex8ToPtr (Fortran)

1-353

See AlsomxCopyPtrToComplex8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-354

mxCopyInteger1ToPtr (Fortran)INTEGER1 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger1ToPtr(y px n)integer1 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER1 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger1ToPtr copies n INTEGER1 values from the Fortran INTEGER1 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyInteger1ToPtr (Fortran)

1-355

bull matsqint8F

See AlsomxCopyPtrToInteger1 mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-356

mxCopyInteger2ToPtr (Fortran)INTEGER2 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger2ToPtr(y px n)integer2 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER2 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger2ToPtr copies n INTEGER2 values from the Fortran INTEGER2 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger2 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger2ToPtr (Fortran)

1-357

Introduced before R2006a

1 API Reference

1-358

mxCopyInteger4ToPtr (Fortran)INTEGER4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyInteger4ToPtr(y px n)integer4 y(n)mwPointer pxmwSize n

Argumentsy

INTEGER4 Fortran arraypx

Pointer to the real or imaginary data of the arrayn

Number of elements to copy

DescriptionmxCopyInteger4ToPtr copies n INTEGER4 values from the Fortran INTEGER4 arrayy into the MATLAB array pointed to by px either a real or an imaginary array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyPtrToInteger4 mxCreateNumericArray mxCreateNumericMatrix

mxCopyInteger4ToPtr (Fortran)

1-359

Introduced before R2006a

1 API Reference

1-360

mxCopyPtrToCharacter (Fortran)CHARACTER values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToCharacter(px y n)mwPointer pxcharacter() ymwSize n

Argumentspx

Pointer to character or name arrayy

character Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToCharacter copies n character values from the MATLAB array pointedto by px into the Fortran character array y This subroutine is essential for copyingcharacter data from MATLAB pointer arrays into ordinary Fortran character arrays

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxCopyPtrToCharacter (Fortran)

1-361

See AlsomxCopyCharacterToPtr mxCreateCharArray mxCreateStringmxCreateCharMatrixFromStrings

Introduced before R2006a

1 API Reference

1-362

mxCopyPtrToComplex16 (Fortran)COMPLEX16 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex16(pr pi y n)mwPointer pr picomplex16 y(n)mwSize n

Argumentspr

Pointer to the real data of a double-precision MATLAB arraypi

Pointer to the imaginary data of a double-precision MATLAB arrayy

COMPLEX16 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex16 copies n COMPLEX16 values from the MATLAB arrayspointed to by pr and pi into the Fortran COMPLEX16 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex16 (Fortran)

1-363

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull convecF

See AlsomxCopyComplex16ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-364

mxCopyPtrToComplex8 (Fortran)COMPLEX8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToComplex8(pr pi y n)mwPointer pr picomplex8 y(n)mwSize n

Argumentspr

Pointer to the real data of a single-precision MATLAB arraypi

Pointer to the imaginary data of a single-precision MATLAB arrayy

COMPLEX8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToComplex8 copies n COMPLEX8 values from the MATLAB arrays pointedto by pr and pi into the Fortran COMPLEX8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToComplex8 (Fortran)

1-365

See AlsomxCopyComplex8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-366

mxCopyPtrToInteger1 (Fortran)INTEGER1 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger1(px y n)mwPointer pxinteger1 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER1 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger1 copies n INTEGER1 values from the MATLAB array pointed toby px either a real or imaginary array into the Fortran INTEGER1 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexamplesrefbook

mxCopyPtrToInteger1 (Fortran)

1-367

bull matsqint8F

See AlsomxCopyInteger1ToPtr mxCreateNumericArray mxCreateNumericMatrix

Introduced before R2006a

1 API Reference

1-368

mxCopyPtrToInteger2 (Fortran)INTEGER2 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger2(px y n)mwPointer pxinteger2 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER2 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger2 copies n INTEGER2 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER2 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger2ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger2 (Fortran)

1-369

Introduced before R2006a

1 API Reference

1-370

mxCopyPtrToInteger4 (Fortran)INTEGER4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToInteger4(px y n)mwPointer pxinteger4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of the arrayy

INTEGER4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToInteger4 copies n INTEGER4 values from the MATLAB array pointed toby px either a real or an imaginary array into the Fortran INTEGER4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

See AlsomxCopyInteger4ToPtr mxCreateNumericArray mxCreateNumericMatrix

mxCopyPtrToInteger4 (Fortran)

1-371

Introduced before R2006a

1 API Reference

1-372

mxCopyPtrToPtrArray (Fortran)Pointer values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToPtrArray(px y n)mwPointer pxmwPointer y(n)mwSize n

Argumentspx

Pointer to pointer arrayy

Fortran array of mwPointer valuesn

Number of pointers to copy

DescriptionmxCopyPtrToPtrArray copies n pointers from the MATLAB array pointed to by px intothe Fortran array y This subroutine is essential for copying the output of matGetDirinto an array of pointers After calling this function each element of y contains a pointerto a string You can convert these strings to Fortran character arrays by passing eachelement of y as the first argument to mxCopyPtrToCharacter

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToPtrArray (Fortran)

1-373

bull matdemo2F

See AlsomatGetDir mxCopyPtrToCharacter

Introduced before R2006a

1 API Reference

1-374

mxCopyPtrToReal4 (Fortran)REAL4 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal4(px y n)mwPointer pxreal4 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a single-precision MATLAB arrayy

REAL4 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal4 copies n REAL4 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL4 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyPtrToReal4 (Fortran)

1-375

See AlsomxCopyReal4ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-376

mxCopyPtrToReal8 (Fortran)REAL8 values from pointer array to Fortran array

Fortran Syntaxinclude fintrfhsubroutine mxCopyPtrToReal8(px y n)mwPointer pxreal8 y(n)mwSize n

Argumentspx

Pointer to the real or imaginary data of a double-precision MATLAB arrayy

REAL8 Fortran arrayn

Number of elements to copy

DescriptionmxCopyPtrToReal8 copies n REAL8 values from the MATLAB array pointed to by pxeither a pr or pi array into the Fortran REAL8 array y

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyPtrToReal8 (Fortran)

1-377

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyReal8ToPtr mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-378

mxCopyReal4ToPtr (Fortran)REAL4 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal4ToPtr(y px n)real4 y(n)mwPointer pxmwSize n

Argumentsy

REAL4 Fortran arraypx

Pointer to the real or imaginary data of a single-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal4ToPtr copies n REAL4 values from the Fortran REAL4 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

mxCopyReal4ToPtr (Fortran)

1-379

See AlsomxCopyPtrToReal4 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-380

mxCopyReal8ToPtr (Fortran)REAL8 values from Fortran array to pointer array

Fortran Syntaxinclude fintrfhsubroutine mxCopyReal8ToPtr(y px n)real8 y(n)mwPointer pxmwSize n

Argumentsy

REAL8 Fortran arraypx

Pointer to the real or imaginary data of a double-precision MATLAB arrayn

Number of elements to copy

DescriptionmxCopyReal8ToPtr copies n REAL8 values from the Fortran REAL8 array y into theMATLAB array pointed to by px either a pr or pi array

Sets up standard Fortran arrays for passing as arguments to or from the computationroutine of a MEX-file Use this subroutine with Fortran compilers that do not support theVAL construct

ExamplesSee the following examples in matlabrootexternexampleseng_mat

mxCopyReal8ToPtr (Fortran)

1-381

bull matdemo1F

bull fengdemoF

See the following examples in matlabrootexternexamplesrefbook

bull timestwoFbull xtimesyF

See AlsomxCopyPtrToReal8 mxCreateNumericArray mxCreateNumericMatrixmxGetData mxGetImagData

Introduced before R2006a

1 API Reference

1-382

mxCreateCellArray (C and Fortran)N-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the created cell For example to create a three-dimensionalcell mxArray set ndim to 3

dimsDimensions array Each element in the dimensions array contains the size of themxArray in that dimension For example in C setting dims[0] to 5 and dims[1] to7 establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellArray (C and Fortran)

1-383

DescriptionUse mxCreateCellArray to create a cell mxArray with size defined by ndim and dimsFor example in C to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims[0] = 4 dims[1] = 8 dims[2] = 7

In Fortran to establish a three-dimensional cell mxArray having dimensions 4-by-8-by-7 set

ndim = 3dims(1) = 4 dims(2) = 8 dims(3) = 7

The created cell mxArray is unpopulated mxCreateCellArray initializes each cell toNULL To put data into a cell call mxSetCell

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateCellMatrix mxGetCell mxSetCell mxIsCell

Introduced before R2006a

1 API Reference

1-384

mxCreateCellMatrix (C and Fortran)2-D cell array

C Syntaxinclude matrixhmxArray mxCreateCellMatrix(mwSize m mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCellMatrix(m n)mwSize m n

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

mxCreateCellMatrix (C and Fortran)

1-385

DescriptionUse mxCreateCellMatrix to create an m-by-n two-dimensional cell mxArray Thecreated cell mxArray is unpopulated mxCreateCellMatrix initializes each cell to NULLin C (0 in Fortran) To put data into cells call mxSetCell

mxCreateCellMatrix is identical to mxCreateCellArray except thatmxCreateCellMatrix can create two-dimensional mxArrays only butmxCreateCellArray can create mxArrays having any number of dimensions greaterthan 1

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray

Introduced before R2006a

1 API Reference

1-386

mxCreateCharArray (C and Fortran)N-D mxChar array

C Syntaxinclude matrixhmxArray mxCreateCharArray(mwSize ndim const mwSize dims)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharArray(ndim dims)mwSize ndimmwSize dims(ndim)

Argumentsndim

Number of dimensions in the mxArray specified as a positive number If you specify0 1 or 2 mxCreateCharArray creates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 character mxArray The dims array must have at least ndimelements

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateCharArray (C and Fortran)

1-387

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateCharArray to create an N-dimensional mxChar array The createdmxArray is unpopulated that is mxCreateCharArray initializes each cell to NULL in C(0 in Fortran)

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateCharMatrixFromStrings mxCreateString

1 API Reference

1-388

mxCreateCharMatrixFromStrings (C and Fortran)2-D mxChar array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateCharMatrixFromStrings(mwSize m const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateCharMatrixFromStrings(m str)mwSize mcharacter() str(m)

Argumentsm

Number of rows in the mxArray The value you specify for m is the number of stringsin str

strIn C an array of strings containing at least m strings In Fortran a characternarray of size m where each element of the array is n bytes

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray Another possible reasonfor failure is that str contains fewer than m strings

mxCreateCharMatrixFromStrings (C and Fortran)

1-389

DescriptionUse mxCreateCharMatrixFromStrings to create a two-dimensional mxArray whereeach row is initialized to a string from str In C the created mxArray has dimensions m-by-max where max is the length of the longest string in str In Fortran the createdmxArray has dimensions m-by-n where n is the number of characters in str(i)

The mxArray represents its data elements as mxChar rather than as C char

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrc

See AlsomxCreateCharArray mxCreateString mxGetString

Introduced before R2006a

1 API Reference

1-390

mxCreateDoubleMatrix (C and Fortran)2-D double-precision floating-point array

C Syntaxinclude matrixhmxArray mxCreateDoubleMatrix(mwSize m mwSize n mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleMatrix(m n ComplexFlag)mwSize m ninteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsComplexFlag

If the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEX

mxCreateDoubleMatrix (C and Fortran)

1-391

file terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateDoubleMatrix to create an m-by-n mxArray mxCreateDoubleMatrixinitializes each element in the pr array to 0 If you set ComplexFlag to mxCOMPLEX in C(1 in Fortran) mxCreateDoubleMatrix also initializes each element in the pi array to0

If you set ComplexFlag to mxREAL in C (0 in Fortran) mxCreateDoubleMatrixallocates enough memory to hold m-by-n real elements If you set ComplexFlag tomxCOMPLEX in C (1 in Fortran) mxCreateDoubleMatrix allocates enough memory tohold m-by-n real elements and m-by-n imaginary elements

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its associated real and complex elements

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull matrixDividecbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull matsqF

1 API Reference

1-392

bull timestwoFbull xtimesyF

See AlsomxCreateNumericArray

Introduced before R2006a

mxCreateDoubleMatrix (C and Fortran)

1-393

mxCreateDoubleScalar (C and Fortran)Scalar double-precision array initialized to specified value

C Syntaxinclude matrixhmxArray mxCreateDoubleScalar(double value)

Fortran Syntaxinclude fintrfhmwPointer mxCreateDoubleScalar(value)real8 value

Argumentsvalue

Value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateDoubleScalar to create a scalar double mxArray When you finish usingthe mxArray call mxDestroyArray to destroy it

1 API Reference

1-394

See AlsomxGetPr mxCreateDoubleMatrix

Alternatives

C Language

In C you can replace the statements

pa = mxCreateDoubleMatrix(1 1 mxREAL)mxGetPr(pa) = value

with a call to mxCreateDoubleScalar

pa = mxCreateDoubleScalar(value)

Fortran Language

In Fortran you can replace the statements

pm = mxCreateDoubleMatrix(1 1 0)mxCopyReal8ToPtr(value mxGetPr(pm) 1)

with a call to mxCreateDoubleScalar

pm = mxCreateDoubleScalar(value)

Introduced before R2006a

mxCreateDoubleScalar (C and Fortran)

1-395

mxCreateLogicalArray (C)N-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalArray(mwSize ndim const mwSize dims)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateLogicalArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray There are ndim elements in the dims array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalArray to create an N-dimensional mxArray of mxLogicalelements After creating the mxArray mxCreateLogicalArray initializes all itselements to logical 0 mxCreateLogicalArray differs from mxCreateLogicalMatrixin that the latter can create two-dimensional arrays only

1 API Reference

1-396

mxCreateLogicalArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

See AlsomxCreateLogicalMatrix mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalArray (C)

1-397

mxCreateLogicalMatrix (C)2-D logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalMatrix(mwSize m mwSize n)

Argumentsm

Number of rowsn

Number of columns

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateLogicalMatrix to create an m-by-n mxArray of mxLogical elementsmxCreateLogicalMatrix initializes each element in the array to logical 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray

1 API Reference

1-398

See AlsomxCreateLogicalArray mxCreateSparseLogicalMatrixmxCreateLogicalScalar

Introduced before R2006a

mxCreateLogicalMatrix (C)

1-399

mxCreateLogicalScalar (C)Scalar logical array

C Syntaxinclude matrixhmxArray mxCreateLogicalScalar(mxLogical value)

Argumentsvalue

Logical value to which you want to initialize the array

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateLogicalScalar to create a scalar logical mxArraymxCreateLogicalScalar is a convenience function that replaces the following code

pa = mxCreateLogicalMatrix(1 1)mxGetLogicals(pa) = value

When you finish using the mxArray call mxDestroyArray to destroy it

1 API Reference

1-400

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxIsLogicalScalarmxIsLogicalScalarTrue mxGetLogicals mxDestroyArray

Introduced before R2006a

mxCreateLogicalScalar (C)

1-401

mxCreateNumericArray (C and Fortran)N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateNumericArray(mwSize ndim const mwSize dims mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericArray(ndim dims classid ComplexFlag)mwSize ndimmwSize dims(ndim)integer4 classid ComplexFlag

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classid

1 API Reference

1-402

value from a MATLAB class name See the Description on page 1-403 section formore information

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericArray to create an N-dimensional mxArray in which all dataelements have the numeric data type specified by classid After creating the mxArraymxCreateNumericArray initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericArray also initializes all itsimaginary data elements to 0 mxCreateNumericArray differs frommxCreateDoubleMatrix as follows

bull All data elements in mxCreateDoubleMatrix are double-precision floating-pointnumbers The data elements in mxCreateNumericArray can be any numerical typeincluding different integer precisions

bull mxCreateDoubleMatrix can create two-dimensional arrays onlymxCreateNumericArray can create arrays of two or more dimensions

mxCreateNumericArray allocates dynamic memory to store the created mxArrayWhen you finish with the created mxArray call mxDestroyArray to deallocate itsmemory

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

mxCreateNumericArray (C and Fortran)

1-403

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull doubleelementcbull matrixDividecbull matsqint8F

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-404

Introduced before R2006a

mxCreateNumericArray (C and Fortran)

1-405

mxCreateNumericMatrix (C and Fortran)2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateNumericMatrix(mwSize m mwSize n mxClassID classid mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateNumericMatrix(m n classid ComplexFlag)mwSize m ninteger4 classid ComplexFlag

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS in C causes eachpiece of numerical data in the mxArray to be represented as a 16-bit signed integerIn Fortran use the function mxClassIDFromClassName to derive the classidvalue from a MATLAB class name

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

1 API Reference

1-406

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateNumericMatrix to create a 2-D mxArray in which all data elements havethe numeric data type specified by classid After creating the mxArraymxCreateNumericMatrix initializes all its real data elements to 0 If ComplexFlagequals mxCOMPLEX in C (1 in Fortran) mxCreateNumericMatrix also initializes all itsimaginary data elements to 0 mxCreateNumericMatrix allocates dynamic memory tostore the created mxArray When you finish using the mxArray call mxDestroyArrayto destroy it

The following table shows the C classid values and the Fortran data types that areequivalent to MATLAB classesMATLAB Class Name C classid Value Fortran Typeint8 mxINT8_CLASS BYTEuint8 mxUINT8_CLASS int16 mxINT16_CLASS INTEGER2uint16 mxUINT16_CLASS int32 mxINT32_CLASS INTEGER4uint32 mxUINT32_CLASS int64 mxINT64_CLASS INTEGER8uint64 mxUINT64_CLASS single mxSINGLE_CLASS REAL4

COMPLEX8double mxDOUBLE_CLASS REAL8

COMPLEX16

mxCreateNumericMatrix (C and Fortran)

1-407

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrc

The following Fortran statements create a 4-by-3 matrix of REAL4 elements having noimaginary components

C Create 4x3 mxArray of REAL4 mxCreateNumericMatrix(4 3 + mxClassIDFromClassName(single) 0)

See AlsomxClassId mxClassIdFromClassName mxComplexity mxDestroyArraymxCreateUninitNumericMatrix mxCreateNumericArray

Introduced before R2006a

1 API Reference

1-408

mxCreateSparse (C and Fortran)2-D sparse array

C Syntaxinclude matrixhmxArray mxCreateSparse(mwSize m mwSize n mwSize nzmax mxComplexity ComplexFlag)

Fortran Syntaxinclude fintrfhmwPointer mxCreateSparse(m n nzmax ComplexFlag)mwSize m n nzmaxinteger4 ComplexFlag

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparse should allocate to hold the pr ir and ifComplexFlag is mxCOMPLEX in C (1 in Fortran) pi arrays Set the value of nzmax tobe greater than or equal to the number of nonzero elements you plan to put into themxArray but make sure that nzmax is less than or equal to mn nzmax is greaterthan or equal to 1

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX in C (1 in Fortran) Otherwise set ComplexFlag to mxREAL in C (0 inFortran)

mxCreateSparse (C and Fortran)

1-409

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray In that case tryreducing nzmax m or n

DescriptionCall mxCreateSparse to create an unpopulated sparse double mxArray The returnedsparse mxArray contains no sparse information and cannot be passed as an argument toany MATLAB sparse functions To make the returned sparse mxArray useful initializethe pr ir jc and (if it exists) pi arrays

mxCreateSparse allocates space for

bull A pr array of length nzmaxbull A pi array of length nzmax but only if ComplexFlag is mxCOMPLEX in C (1 in

Fortran)bull An ir array of length nzmaxbull A jc array of length n+1

When you finish using the sparse mxArray call mxDestroyArray to reclaim all its heapspace

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

1 API Reference

1-410

See AlsomxDestroyArray mxSetNzmax mxSetPr mxSetPi mxSetIr mxSetJcmxComplexity

Introduced before R2006a

mxCreateSparse (C and Fortran)

1-411

mxCreateSparseLogicalMatrix (C)2-D sparse logical array

C Syntaxinclude matrixhmxArray mxCreateSparseLogicalMatrix(mwSize m mwSize n mwSize nzmax)

Argumentsm

Number of rowsn

Number of columnsnzmax

Number of elements that mxCreateSparseLogicalMatrix should allocate to holdthe data Set the value of nzmax to be greater than or equal to the number of nonzeroelements you plan to put into the mxArray but make sure that nzmax is less than orequal to mn nzmax is greater than or equal to 1

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

1 API Reference

1-412

DescriptionUse mxCreateSparseLogicalMatrix to create an m-by-n mxArray of mxLogicalelements mxCreateSparseLogicalMatrix initializes each element in the array tological 0

Call mxDestroyArray when you finish using the mxArray mxDestroyArraydeallocates the mxArray and its elements

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxCreateSparse mxIsLogical

Introduced before R2006a

mxCreateSparseLogicalMatrix (C)

1-413

mxCreateString (C and Fortran)1-N array initialized to specified string

C Syntaxinclude matrixhmxArray mxCreateString(const char str)

Fortran Syntaxinclude fintrfhmwPointer mxCreateString(str)character() str

Argumentsstr

String used to initialize mxArray data Only ASCII characters are supported

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionUse mxCreateString to create an mxArray initialized to str Many MATLAB functions(for example strcmp and upper) require string array inputs

1 API Reference

1-414

mxCreateString supports both multi-byte and single-byte encoded characters OnWindows and Linux platforms the default encoding is specified by the user localesetting

Free the mxArray when you are finished using it by calling mxDestroyArray

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull revordcbull revordF

See the following examples in matlabrootexternexamplesmx

bull mxcreatestructarraycbull mxisclassc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxCreateCharMatrixFromStrings mxCreateCharArray

Introduced before R2006a

mxCreateString (C and Fortran)

1-415

mxCreateStructArray (C and Fortran)N-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructArray(mwSize ndim const mwSize dims int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructArray(ndim dims nfields fieldnames)mwSize ndimmwSize dims(ndim)integer4 nfieldscharacter() fieldnames(nfields)

Argumentsndim

Number of dimensions If you set ndim to be less than 2 mxCreateStructArraycreates a two-dimensional mxArray

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray Typically the dims array should have ndim elements

nfieldsNumber of fields in each element Positive integer

fieldnamesList of field names Field names must be valid MATLAB identifiers which meansthey cannot be NULL or empty

1 API Reference

1-416

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionCall mxCreateStructArray to create an unpopulated structure mxArray Each elementof a structure mxArray contains the same number of fields (specified in nfields) Eachfield has a name the list of names is specified in fieldnames A MATLAB structuremxArray is conceptually identical to an array of structs in the C language

Each field holds one mxArray pointer mxCreateStructArray initializes each field toNULL in C (0 in Fortran) Call mxSetField or mxSetFieldByNumber to place a non-NULL mxArray pointer in a field

When you finish using the returned structure mxArray call mxDestroyArray to reclaimits space

Any trailing singleton dimensions specified in the dims argument are automaticallyremoved from the resulting array For example if ndim equals 5 and dims equals [4 17 1 1] the resulting array is given the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

mxCreateStructArray (C and Fortran)

1-417

See AlsomxDestroyArray mxAddField mxRemoveField mxSetFieldmxSetFieldByNumber namelengthmax

Introduced before R2006a

1 API Reference

1-418

mxCreateStructMatrix (C and Fortran)2-D structure array

C Syntaxinclude matrixhmxArray mxCreateStructMatrix(mwSize m mwSize n int nfields const char fieldnames)

Fortran Syntaxinclude fintrfhmwPointer mxCreateStructMatrix(m n nfields fieldnames)mwSize m ninteger4 nfieldscharacter() fieldnames(nfields)

Argumentsm

Number of rows must be a positive integern

Number of columns must be a positive integernfields

Number of fields in each elementfieldnames

List of field names

Each structure field name must begin with a letter and is case-sensitive The rest of thename can contain letters numerals and underscore characters To determine themaximum length of a field name use the namelengthmax function

mxCreateStructMatrix (C and Fortran)

1-419

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxCreateStructMatrix and mxCreateStructArray are almost identical The onlydifference is that mxCreateStructMatrix can create only two-dimensional mxArrayswhile mxCreateStructArray can create an mxArray having two or more dimensions

C ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray namelengthmax

Introduced before R2006a

1 API Reference

1-420

mxCreateUninitNumericArray (C)Uninitialized N-D numeric array

C Syntaxinclude matrixhmxArray mxCreateUninitNumericArray(size_t ndim size_t dims mxClassID classid mxComplexity ComplexFlag)

Argumentsndim

Number of dimensions If you specify a value for ndim that is less than 2mxCreateUninitNumericArray automatically sets the number of dimensions to 2

dimsDimensions array Each element in the dimensions array contains the size of thearray in that dimension For example setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray Usually there are ndim elements in the dims array

classidIdentifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericArray (C)

1-421

DescriptionCall mxCreateUninitNumericArray to create an N-dimensional mxArray in which alldata elements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericArray allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericMatrix mxCreateNumericArray

Introduced in R2015a

1 API Reference

1-422

mxCreateUninitNumericMatrix (C)Uninitialized 2-D numeric matrix

C Syntaxinclude matrixhmxArray mxCreateUninitNumericMatrix(size_t m size_t n mxClassID classid mxComplexity ComplexFlag)

Argumentsm

Number of rowsn

Number of columnsclassid

Identifier for the class of the array which determines the way the numerical data isrepresented in memory For example specifying mxINT16_CLASS causes each pieceof numerical data in the mxArray to be represented as a 16-bit signed integer

ComplexFlagIf the mxArray you are creating is to contain imaginary data set ComplexFlag tomxCOMPLEX Otherwise set ComplexFlag to mxREAL

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEX-file) application returns NULL If unsuccessful in a MEX-file the MEX-file terminatesand returns control to the MATLAB prompt The function is unsuccessful when there isnot enough free heap space to create the mxArray

mxCreateUninitNumericMatrix (C)

1-423

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxcreateuninitnumericmatrixc

DescriptionCall mxCreateUninitNumericMatrix to create a 2-D mxArray in which all dataelements have the numeric data type specified by classid Data elements are notinitialized

mxCreateUninitNumericMatrix allocates dynamic memory to store the createdmxArray Call mxDestroyArray to deallocate the memory

The following table shows the C classid values that are equivalent to MATLAB classesMATLAB Class Name C classid Valueint8 mxINT8_CLASSuint8 mxUINT8_CLASSint16 mxINT16_CLASSuint16 mxUINT16_CLASSint32 mxINT32_CLASSuint32 mxUINT32_CLASSint64 mxINT64_CLASSuint64 mxUINT64_CLASSsingle mxSINGLE_CLASSdouble mxDOUBLE_CLASS

See AlsomxDestroyArray mxCreateUninitNumericArray mxCreateNumericMatrix

1 API Reference

1-424

Introduced in R2015a

mxCreateUninitNumericMatrix (C)

1-425

mxDestroyArray (C and Fortran)Free dynamic memory allocated by MXCREATE functions

C Syntaxinclude matrixhvoid mxDestroyArray(mxArray pm)

Fortran Syntaxinclude fintrfhsubroutine mxDestroyArray(pm)mwPointer pm

Argumentspm

Pointer to the mxArray to free If pm is a NULL pointer the function does nothing

DescriptionmxDestroyArray deallocates the memory occupied by the specified mxArray including

bull Characteristics fields of the mxArray such as size (m and n) and typebull Associated data arrays such as pr and pi for complex arrays and ir and jc for

sparse arraysbull Fields of structure arraysbull Cells of cell arrays

Do not call mxDestroyArray on an mxArray

bull returned in a left-side argument of a MEX file

1 API Reference

1-426

bull returned by the mxGetField or mxGetFieldByNumber functionsbull returned by the mxGetCell function

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull sincallcbull sincallF

See the following examples in matlabrootexternexamplesmex

bull mexcallmatlabcbull mexgetarrayc

See the following examples in matlabrootexternexamplesmx

bull mxisclasscbull mxcreatecellmatrixfF

See AlsomxCalloc mxMalloc mxFree mexMakeArrayPersistentmexMakeMemoryPersistent

Introduced before R2006a

mxDestroyArray (C and Fortran)

1-427

mxDuplicateArray (C and Fortran)Make deep copy of array

C Syntaxinclude matrixhmxArray mxDuplicateArray(const mxArray in)

Fortran Syntaxinclude fintrfhmwPointer mxDuplicateArray(in)mwPointer in

Argumentsin

Pointer to the mxArray you want to copy

ReturnsPointer to the created mxArray if successful If unsuccessful in a standalone (non-MEXfile) application returns NULL in C (0 in Fortran) If unsuccessful in a MEX file the MEXfile terminates and returns control to the MATLAB prompt The function is unsuccessfulwhen there is not enough free heap space to create the mxArray

DescriptionmxDuplicateArray makes a deep copy of an array and returns a pointer to the copy Adeep copy refers to a copy in which all levels of data are copied For example a deep copyof a cell array copies each cell and the contents of each cell (if any)

1 API Reference

1-428

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfFbull mxgetinfcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

Introduced before R2006a

mxDuplicateArray (C and Fortran)

1-429

mxFree (C and Fortran)Free dynamic memory allocated by mxCalloc mxMalloc mxRealloc mxArrayToString ormxArrayToUTF8String functions

C Syntaxinclude matrixhvoid mxFree(void ptr)

Fortran Syntaxinclude fintrfhsubroutine mxFree(ptr)mwPointer ptr

Argumentsptr

Pointer to the beginning of any memory parcel allocated by mxCalloc mxMalloc ormxRealloc If ptr is a NULL pointer the function does nothing

DescriptionmxFree deallocates heap space using the MATLAB memory management facility Thisfunction ensures correct memory management in error and abort (Ctrl+C) conditions

To deallocate heap space MATLAB applications in C should always call mxFree ratherthan the ANSI C free function

In MEX files but excluding MAT or engine standalone applications the MATLABmemory management facility maintains a list of all memory allocated by the followingfunctions

1 API Reference

1-430

bull mxCallocbull mxMallocbull mxReallocbull mxArrayToStringbull mxArrayToUTF8String

The memory management facility automatically deallocates all parcels managed by aMEX file when the MEX file completes and control returns to the MATLAB promptmxFree also removes the memory parcel from the memory management list of parcels

When mxFree appears in a MAT or engine standalone MATLAB application it simplydeallocates the contiguous heap space that begins at address ptr

In MEX files your use of mxFree depends on whether the specified memory parcel ispersistent or nonpersistent By default memory parcels created by mxCallocmxMalloc mxRealloc mxArrayToString and mxArrayToUTF8String arenonpersistent The memory management facility automatically frees all nonpersistentmemory whenever a MEX file completes Thus even if you do not call mxFree MATLABtakes care of freeing the memory for you Nevertheless it is good programming practiceto deallocate memory when you are through using it Doing so generally makes the entiresystem run more efficiently

If an application calls mexMakeMemoryPersistent the specified memory parcelbecomes persistent When a MEX file completes the memory management facility doesnot free persistent memory parcels Therefore the only way to free a persistent memoryparcel is to call mxFree Typically MEX files call mexAtExit to register a cleanuphandler The cleanup handler calls mxFree

Do not use mxFree for an mxArray created by any other functions in the Matrix LibraryAPI Use mxDestroyArray instead

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxcreatecharmatrixfromstrc

mxFree (C and Fortran)

1-431

bull mxisfinitecbull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxMalloc mxRealloc mxArrayToString mxArrayToUTF8String

Introduced before R2006a

1 API Reference

1-432

mxGetCell (C and Fortran)Pointer to element in cell array

C Syntaxinclude matrixhmxArray mxGetCell(const mxArray pm mwIndex index)

Fortran Syntaxinclude fintrfhmwPointer mxGetCell(pm index)mwPointer pmmwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Number of elements in the cell mxArray between the first element and the desiredone See mxCalcSingleSubscript for details on calculating an index in amultidimensional cell array

ReturnsPointer to the ith cell mxArray if successful Otherwise returns NULL in C (0 inFortran) Causes of failure include

bull Specifying the index of a cell array element that has not been populatedbull Specifying a pm that does not point to a cell mxArray

mxGetCell (C and Fortran)

1-433

bull Specifying an index to an element outside the bounds of the mxArraybull Insufficient heap space

Do not call mxDestroyArray on an mxArray returned by the mxGetCell function

DescriptionCall mxGetCell to get a pointer to the mxArray held in the indexed element of the cellmxArray

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateCellArray mxIsCell mxSetCell

Introduced before R2006a

1 API Reference

1-434

mxGetChars (C)Pointer to character array data

C Syntaxinclude matrixhmxChar mxGetChars(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first character in the mxArray Returns NULL if the specified array is not acharacter array

DescriptionCall mxGetChars to access the first character in the mxArray that array_ptr points toOnce you have the starting address you can access any other element in the mxArray

See AlsomxGetString

Introduced before R2006a

mxGetChars (C)

1-435

mxGetClassID (C and Fortran)Class of array

C Syntaxinclude matrixhmxClassID mxGetClassID(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetClassID(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumeric identifier of the class (category) of the mxArray that pm points to For a list ofC-language class identifiers see the mxClassID reference page For user-defined typesmxGetClassId returns a unique value identifying the class of the array contents UsemxIsClass to determine whether an array is of a specific user-defined type

DescriptionUse mxGetClassId to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray then mxGetClassId returns mxLOGICAL_CLASS (in C)

1 API Reference

1-436

mxGetClassId is like mxGetClassName except that the former returns the class as aninteger identifier and the latter returns the class as a string

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxClassID mxGetClassName mxIsClass

Introduced before R2006a

mxGetClassID (C and Fortran)

1-437

mxGetClassName (C and Fortran)Class of array as string

Note Use mxGetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhconst char mxGetClassName(const mxArray pm)

Fortran Syntaxinclude fintrfhcharacter() mxGetClassName(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsClass (as a string) of the mxArray pointed to by pm

DescriptionCall mxGetClassName to determine the class of an mxArray The class of an mxArrayidentifies the kind of data the mxArray is holding For example if pm points to a logicalmxArray mxGetClassName returns logical

1 API Reference

1-438

mxGetClassID is like mxGetClassName except that the former returns the class as aninteger identifier as listed in the mxClassID reference page and the latter returns theclass as a string as listed in the mxIsClass reference page

ExamplesSee the following examples in matlabrootexternexamplesmex

bull mexfunctionc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxGetClassID mxIsClass

Introduced before R2006a

mxGetClassName (C and Fortran)

1-439

mxGetData (C and Fortran)Pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxGetData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionIn C mxGetData returns a void pointer (void ) Since void pointers point to a valuethat has no type cast the return value to the pointer type that matches the type specifiedby pm To see how MATLAB types map to their equivalent C types see the table on themxClassID reference page

1 API Reference

1-440

In Fortran to copy values from the returned pointer use one of the mxCopyPtrTofunctions in the following manner

C Get the data in mxArray pm mxCopyPtrToReal8(mxGetData(pm)data + mxGetNumberOfElements(pm))

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull matrixDividecbull matrixDivideComplexcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxisfinitec

See AlsomxGetImagData mxGetPr mxClassID

Introduced before R2006a

mxGetData (C and Fortran)

1-441

mxGetDimensions (C and Fortran)Pointer to dimensions array

C Syntaxinclude matrixhconst mwSize mxGetDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element in the dimensions array Each integer in the dimensionsarray represents the number of elements in a particular dimension The array is notNULL terminated

DescriptionUse mxGetDimensions to determine how many elements are in each dimension of themxArray that pm points to Call mxGetNumberOfDimensions to get the number ofdimensions in the mxArray

To copy the values to Fortran use mxCopyPtrToInteger4 in the following manner

1 API Reference

1-442

C Get dimensions of mxArray pm mxCopyPtrToInteger4(mxGetDimensions(pm) dims + mxGetNumberOfDimensions(pm))

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetNumberOfDimensions

Introduced before R2006a

mxGetDimensions (C and Fortran)

1-443

mxGetElementSize (C and Fortran)Number of bytes required to store each data element

C Syntaxinclude matrixhsize_t mxGetElementSize(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetElementSize(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of bytes required to store one element of the specified mxArray if successfulReturns 0 on failure The primary reason for failure is that pm points to an mxArrayhaving an unrecognized class If pm points to a cell mxArray or a structure mxArraymxGetElementSize returns the size of a pointer (not the size of all the elements in eachcell or structure field)

DescriptionCall mxGetElementSize to determine the number of bytes in each data element of themxArray For example if the MATLAB class of an mxArray is int16 the mxArray

1 API Reference

1-444

stores each data element as a 16-bit (2-byte) signed integer Thus mxGetElementSizereturns 2

mxGetElementSize is helpful when using a non-MATLAB routine to manipulate dataelements For example the C function memcpy requires (for its third argument) the sizeof the elements you intend to copy

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull doubleelementcbull phonebookc

See AlsomxGetM mxGetN

Introduced before R2006a

mxGetElementSize (C and Fortran)

1-445

mxGetEps (C and Fortran)Value of EPS

C Syntaxinclude matrixhdouble mxGetEps(void)

Fortran Syntaxreal8 mxGetEps

ReturnsValue of the MATLAB eps variable

DescriptionCall mxGetEps to return the value of the MATLAB eps variable This variable holds thedistance from 10 to the next largest floating-point number As such it is a measure offloating-point accuracy The MATLAB pinv and rank functions use eps as a defaulttolerance

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

1 API Reference

1-446

See AlsomxGetInf mxGetNan

Introduced before R2006a

mxGetEps (C and Fortran)

1-447

mxGetField (C and Fortran)Pointer to field value from structure array given index and field name

C Syntaxinclude matrixhmxArray mxGetField(const mxArray pm mwIndex index const char fieldname)

Fortran Syntaxinclude fintrfhmwPointer mxGetField(pm index fieldname)mwPointer pmmwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

fieldnameName of the field whose value you want to extract

1 API Reference

1-448

ReturnsPointer to the mxArray in the specified field at the specified fieldname on successReturns NULL in C (0 in Fortran) if passed an invalid argument or if there is no valueassigned to the specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray Todetermine whether pm points to a structure mxArray call mxIsStruct

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains 10 elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent fieldname Call mxGetFieldNameByNumber ormxGetFieldNumber to get existing field names

bull Insufficient heap space

DescriptionCall mxGetField to get the value held in the specified element of the specified field Inpseudo-C terminology mxGetField returns the value at

pm[index]fieldname

mxGetFieldByNumber is like mxGetField Both functions return the same value Theonly difference is in the way you specify the field mxGetFieldByNumber takes a fieldnumber as its third argument and mxGetField takes a field name as its thirdargument

Do not call mxDestroyArray on an mxArray returned by the mxGetField function

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

mxGetField(pa index field_name)

mxGetField (C and Fortran)

1-449

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where if you have a 1-by-1 structure index is 0

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where if you have a 1-by-1 structure index is 1

ExamplesSee the following example in matlabrootexternexampleseng_mat

bull matreadstructarrayc

See AlsomxGetFieldByNumber mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-450

mxGetFieldByNumber (C and Fortran)Pointer to field value from structure array given index and field number

C Syntaxinclude matrixhmxArray mxGetFieldByNumber(const mxArray pm mwIndex index int fieldnumber)

Fortran Syntaxinclude fintrfhmwPointer mxGetFieldByNumber(pm index fieldnumber)mwPointer pmmwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayindex

Index of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for more details on calculating an indexfieldnumber

Position of the field whose value you want to extract

mxGetFieldByNumber (C and Fortran)

1-451

In C the first field within each element has a field number of 0 the second field hasa field number of 1 and so on The last field has a field number of N-1 where N is thenumber of fields

In Fortran the first 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 field number of N whereN is the number of fields

ReturnsPointer to the mxArray in the specified field for the desired element on success ReturnsNULL in C (0 in Fortran) if passed an invalid argument or if there is no value assigned tothe specified field Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

bull Specifying an index to an element outside the bounds of the mxArray For examplegiven a structure mxArray that contains ten elements you cannot specify an indexgreater than 9 in C (10 in Fortran)

bull Specifying a nonexistent field number Call mxGetFieldNumber to determine thefield number that corresponds to a given field name

DescriptionCall mxGetFieldByNumber to get the value held in the specified fieldnumber at theindexed element

Do not call mxDestroyArray on an mxArray returned by the mxGetFieldByNumberfunction

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

In C calling

1 API Reference

1-452

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran calling

mxGetField(pm index fieldname)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxGetFieldNameByNumber mxGetFieldNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldByNumber (C and Fortran)

1-453

mxGetFieldNameByNumber (C and Fortran)Pointer to field name from structure array given field number

C Syntaxinclude matrixhconst char mxGetFieldNameByNumber(const mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhcharacter() mxGetFieldNameByNumber(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Position of the desired field For instance in C to get the name of the first field setfieldnumber to 0 to get the name of the second field set fieldnumber to 1 and soon In Fortran to get the name of the first field set fieldnumber to 1 to get thename of the second field set fieldnumber to 2 and so on

ReturnsPointer to the nth field name on success Returns NULL in C (0 in Fortran) on failureCommon causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

1 API Reference

1-454

bull Specifying a value of fieldnumber outside the bounds of the number of fields in thestructure mxArray In C fieldnumber 0 represents the first field andfieldnumber N-1 represents the last field where N is the number of fields in thestructure mxArray In Fortran fieldnumber 1 represents the first field andfieldnumber N represents the last field

DescriptionCall mxGetFieldNameByNumber to get the name of a field in the given structuremxArray A typical use of mxGetFieldNameByNumber is to call it inside a loop to get thenames of all the fields in a given mxArray

Consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test A field number other than 0 1 or 2causes mxGetFieldNameByNumber to return NULL

In Fortran the field number 1 represents the field name field number 2 represents fieldbilling field number 3 represents field test A field number other than 1 2 or 3causes mxGetFieldNameByNumber to return 0

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

mxGetFieldNameByNumber (C and Fortran)

1-455

bull explorec

See AlsomxGetField mxGetFieldByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

1 API Reference

1-456

mxGetFieldNumber (C and Fortran)Field number from structure array given field name

C Syntaxinclude matrixhint mxGetFieldNumber(const mxArray pm const char fieldname)

Fortran Syntaxinclude fintrfhinteger4 mxGetFieldNumber(pm fieldname)mwPointer pmcharacter() fieldname

Argumentspm

Pointer to a structure mxArrayfieldname

Name of a field in the structure mxArray

ReturnsField number of the specified fieldname on success In C the first field has a fieldnumber of 0 the second field has a field number of 1 and so on In Fortran the first fieldhas a field number of 1 the second field has a field number of 2 and so on Returns -1 inC (0 in Fortran) on failure Common causes of failure include

bull Specifying an array pointer pm that does not point to a structure mxArray CallmxIsStruct to determine whether pm points to a structure mxArray

mxGetFieldNumber (C and Fortran)

1-457

bull 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 do not know its fieldname call mxGetFieldNameByNumber

For example consider a MATLAB structure initialized to

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field name has a field number of 0 the field billing has a field number of 1and the field test has a field number of 2 If you call mxGetFieldNumber and specify afield name of anything other than name billing or test mxGetFieldNumber returns-1

Calling

mxGetField(pa index field_name)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxGetFieldByNumber(pa index field_num)

where index is 0 if you have a 1-by-1 structure

In Fortran the field name has a field number of 1 the field billing has a field numberof 2 and the field test has a field number of 3 If you call mxGetFieldNumber andspecify a field name of anything other than name billing or testmxGetFieldNumber returns 0

Calling

mxGetField(pm index fieldname)

is equivalent to calling

1 API Reference

1-458

fieldnum = mxGetFieldNumber(pm fieldname)mxGetFieldByNumber(pm index fieldnum)

where index is 1 if you have a 1-by-1 structure

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxGetField mxGetFieldByNumber mxGetFieldNameByNumbermxGetNumberOfFields mxIsStruct mxSetField mxSetFieldByNumber

Introduced before R2006a

mxGetFieldNumber (C and Fortran)

1-459

mxGetImagData (C and Fortran)Pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxGetImagData(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetImagData(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsPointer to the first element of the imaginary data Returns NULL in C (0 in Fortran) ifthere is no imaginary data or if there is an error

DescriptionThis function is like mxGetPi except that in C it returns a void For moreinformation see the description for the mxGetData function

1 API Reference

1-460

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxGetData mxGetPi

Introduced before R2006a

mxGetImagData (C and Fortran)

1-461

mxGetInf (C and Fortran)Value of infinity

C Syntaxinclude matrixhdouble mxGetInf(void)

Fortran Syntaxreal8 mxGetInf

ReturnsValue of infinity on your system

DescriptionCall mxGetInf to return the value of the MATLAB internal inf variable inf is apermanent variable representing IEEEreg arithmetic positive infinity Your systemspecifies the value of inf you cannot modify it

Operations that return infinity include

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-462

bull mxgetinfc

See AlsomxGetEps mxGetNaN

Introduced before R2006a

mxGetInf (C and Fortran)

1-463

mxGetIr (C and Fortran)Sparse matrix IR array

C Syntaxinclude matrixhmwIndex mxGetIr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetIr(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the ir array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetIr to obtain the starting address of the ir array The ir array is an array ofintegers The length of ir is nzmax the storage allocated for the sparse array or nnz

1 API Reference

1-464

the number of nonzero matrix elements For example if nzmax equals 100 the ir arraycontains 100 integers

Each value in an ir array indicates a row (offset by 1) at which a nonzero element can befound (The jc array is an index that indirectly specifies a column where nonzeroelements can be found)

For details on the ir and jc arrays see mxSetIr and mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetJc mxGetNzmax mxSetIr mxSetJc mxSetNzmax nzmax nnz

Introduced before R2006a

mxGetIr (C and Fortran)

1-465

mxGetJc (C and Fortran)Sparse matrix JC array

C Syntaxinclude matrixhmwIndex mxGetJc(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetJc(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsPointer to the first element in the jc array if successful and NULL in C (0 in Fortran)otherwise Possible causes of failure include

bull Specifying a full (nonsparse) mxArraybull Specifying a value for pm that is NULL in C (0 in Fortran) This failure usually means

that an earlier call to mxCreateSparse failed

DescriptionUse mxGetJc to obtain the starting address of the jc array The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

1 API Reference

1-466

The values in the jc array indirectly indicate columns containing nonzero elements Fora detailed explanation of the jc array see mxSetJc

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetIr mxGetNzmax mxSetIr mxSetJc mxSetNzmax

Introduced before R2006a

mxGetJc (C and Fortran)

1-467

mxGetLogicals (C)Pointer to logical array data

C Syntaxinclude matrixhmxLogical mxGetLogicals(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsPointer to the first logical element in the mxArray The result is unspecified if themxArray is not a logical array

DescriptionCall mxGetLogicals to access the first logical element in the mxArray that array_ptrpoints to Once you have the starting address you can access any other element in themxArray

See AlsomxCreateLogicalArray mxCreateLogicalMatrix mxCreateLogicalScalarmxIsLogical mxIsLogicalScalar mxIsLogicalScalarTrue

Introduced before R2006a

1 API Reference

1-468

mxGetM (C and Fortran)Number of rows in array

C Syntaxinclude matrixhsize_t mxGetM(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetM(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of rows in the mxArray to which pm points

DescriptionmxGetM returns the number of rows in the specified array The term rows always meansthe first dimension of the array no matter how many dimensions the array has Forexample if pm points to a four-dimensional array having dimensions 8-by-9-by-5-by-3mxGetM returns 8

mxGetM (C and Fortran)

1-469

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull matrixDividecbull matrixDivideComplexcbull revordcbull timestwocbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull timestwoFbull xtimesyF

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-470

bull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

See AlsomxGetN mxSetM mxSetN

Introduced before R2006a

mxGetM (C and Fortran)

1-471

mxGetN (C and Fortran)Number of columns in array

C Syntaxinclude matrixhsize_t mxGetN(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetN(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of columns in the mxArray

DescriptionCall mxGetN to determine the number of columns in the specified mxArray

If pm is an N-dimensional mxArray mxGetN is the product of dimensions 2 through NFor example if pm points to a four-dimensional mxArray having dimensions 13-by-5-by-4-by-6 mxGetN returns the value 120 (5 times 4 times 6) If the specified mxArray has morethan two dimensions and you need to know exactly how many elements are in eachdimension call mxGetDimensions

1 API Reference

1-472

If pm points to a sparse mxArray mxGetN still returns the number of columns not thenumber of occupied columns

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull fulltosparsecbull revordcbull timestwocbull xtimesyc

See the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionscbull mxgetnzmaxcbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexlockcbull yprimec

See the following examples in matlabrootexternexampleseng_mat

bull matdemo2F

mxGetN (C and Fortran)

1-473

See AlsomxGetM mxGetDimensions mxSetM mxSetN

Introduced before R2006a

1 API Reference

1-474

mxGetNaN (C and Fortran)Value of NaN (Not-a-Number)

C Syntaxinclude matrixhdouble mxGetNaN(void)

Fortran Syntaxreal8 mxGetNaN

ReturnsValue of NaN (Not-a-Number) on your system

DescriptionCall mxGetNaN to return the value of NaN for your system NaN is the IEEE arithmeticrepresentation for Not-a-Number Certain mathematical operations return NaN as aresult for example

bull 0000bull Inf-Inf

Your system specifies the value of Not-a-Number You cannot modify it

C ExamplesSee the following examples in matlabrootexternexamplesmx

mxGetNaN (C and Fortran)

1-475

bull mxgetinfc

See AlsomxGetEps mxGetInf

Introduced before R2006a

1 API Reference

1-476

mxGetNumberOfDimensions (C and Fortran)Number of dimensions in array

C Syntaxinclude matrixhmwSize mxGetNumberOfDimensions(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNumberOfDimensions(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of dimensions in the specified mxArray The returned value is always 2 orgreater

DescriptionUse mxGetNumberOfDimensions to determine how many dimensions are in thespecified array To determine how many elements are in each dimension callmxGetDimensions

mxGetNumberOfDimensions (C and Fortran)

1-477

ExamplesSee the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsecbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxisfinitec

See AlsomxSetM mxSetN mxGetDimensions

Introduced before R2006a

1 API Reference

1-478

mxGetNumberOfElements (C and Fortran)Number of elements in array

C Syntaxinclude matrixhsize_t mxGetNumberOfElements(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetNumberOfElements(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsNumber of elements in the specified mxArray

DescriptionmxGetNumberOfElements tells you how many elements an array has For example ifthe dimensions of an array are 3-by-5-by-10 mxGetNumberOfElements returns thenumber 150

mxGetNumberOfElements (C and Fortran)

1-479

Note Fortran does not have an equivalent of size_t mwPointer is a preprocessormacro that provides the appropriate Fortran type The value returned by this functionhowever is not a pointer

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull findnzcbull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetepscbull mxgetepsfFbull mxgetinfcbull mxisfinitecbull mxsetdimensionscbull mxsetdimensionsfF

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetDimensions mxGetM mxGetN mxGetClassID mxGetClassName

Introduced before R2006a

1 API Reference

1-480

mxGetNumberOfFields (C and Fortran)Number of fields in structure array

C Syntaxinclude matrixhint mxGetNumberOfFields(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxGetNumberOfFields(pm)mwPointer pm

Argumentspm

Pointer to a structure mxArray

ReturnsNumber of fields on success Returns 0 on failure The most common cause of failure isthat pm is not a structure mxArray Call mxIsStruct to determine whether pm is astructure

DescriptionCall mxGetNumberOfFields to determine how many fields are in the specified structuremxArray

Once you know the number of fields in a structure you can loop through every field to setor to get field values

mxGetNumberOfFields (C and Fortran)

1-481

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxisclassc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxGetField mxIsStruct mxSetField

Introduced before R2006a

1 API Reference

1-482

mxGetNzmax (C and Fortran)Number of elements in IR PR and PI arrays

C Syntaxinclude matrixhmwSize mxGetNzmax(const mxArray pm)

Fortran Syntaxinclude fintrfhmwSize mxGetNzmax(pm)mwPointer pm

Argumentspm

Pointer to a sparse mxArray

ReturnsNumber of elements allocated to hold nonzero entries in the specified sparse mxArray onsuccess Returns an indeterminate value on error The most likely cause of failure is thatpm points to a full (nonsparse) mxArray

DescriptionUse mxGetNzmax to get the value of the nzmax field The nzmax field holds an integervalue that signifies the number of elements in the ir pr and if it exists the pi arraysThe value of nzmax is always greater than or equal to the number of nonzero elements ina sparse mxArray In addition the value of nzmax is always less than or equal to thenumber of rows times the number of columns

mxGetNzmax (C and Fortran)

1-483

As you adjust the number of nonzero elements in a sparse mxArray MATLAB softwareoften adjusts the value of the nzmax field MATLAB adjusts nzmax to reduce the numberof costly reallocations and to optimize its use of heap space

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetnzmaxc

See AlsomxSetNzmax

Introduced before R2006a

1 API Reference

1-484

mxGetPi (C and Fortran)Imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPi(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPi(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the imaginary data elements of the specified mxArray on success ReturnsNULL in C (0 in Fortran) if there is no imaginary data or if there is an error

DescriptionUse mxGetPi on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetImagData

The pi field points to an array containing the imaginary data of the mxArray CallmxGetPi to get the contents of the pi field that is to get the starting address of thisimaginary data

mxGetPi (C and Fortran)

1-485

The best way to determine whether an mxArray is purely real is to call mxIsComplex

If any of the input matrices to a function are complex MATLAB allocates the imaginaryparts of all input matrices

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull conveccbull findnzcbull fulltosparsec

For Fortran examples see

bull convecF

See the following examples in matlabrootexternexamplesmx

bull mxcalcsinglesubscriptcbull mxgetinfcbull mxisfinitecbull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorecbull mexcallmatlabc

See AlsomxGetPr mxSetPi mxSetPr mxGetImagData mxIsDouble

Introduced before R2006a

1 API Reference

1-486

mxGetPr (C and Fortran)Real data elements in array of type DOUBLE

C Syntaxinclude matrixhdouble mxGetPr(const mxArray pm)

Fortran Syntaxinclude fintrfhmwPointer mxGetPr(pm)mwPointer pm

Argumentspm

Pointer to an mxArray of type double

ReturnsPointer to the first element of the real data Returns NULL in C (0 in Fortran) if there isno real data

DescriptionUse mxGetPr on arrays of type double only Use mxIsDouble to validate the mxArraytype For other mxArray types use mxGetData

Call mxGetPr to access the real data in the mxArray that pm points to Once you havethe starting address you can access any other element in the mxArray

mxGetPr (C and Fortran)

1-487

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillGetPrDynamicDatacbull arrayFillGetPrcbull conveccbull doubleelementcbull findnzcbull fulltosparsecbull matrixDividecbull matrixMultiplycbull sincallcbull timestwocbull timestwoaltcbull xtimesyc

For Fortran examples see

bull convecFbull dblmatFbull fulltosparseFbull matsqFbull sincallFbull timestwoFbull xtimesyF

See AlsomxGetPi mxSetPi mxSetPr mxGetData mxIsDouble

Introduced before R2006a

1 API Reference

1-488

mxGetProperty (C and Fortran)Value of public property of MATLAB object

C Syntaxinclude matrixhmxArray mxGetProperty(const mxArray pa mwIndex index const char propname)

Fortran Syntaxinclude fintrfhmwPointer mxGetProperty(pa index propname)mwPointer pamwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you want to extract

mxGetProperty (C and Fortran)

1-489

ReturnsPointer to the mxArray of the specified propname on success Returns NULL in C (0 inFortran) if unsuccessful Common causes of failure include

bull Specifying a nonexistent propnamebull Specifying a nonpublic propnamebull Specifying an index to an element outside the bounds of the mxArray To test the

index value use mxGetNumberOfElements or mxGetM and mxGetNbull Insufficient heap space

DescriptionCall mxGetProperty to get the value held in the specified element In pseudo-Cterminology mxGetProperty returns the value at

pa[index]propname

mxGetProperty makes a copy of the value If the property uses a large amount ofmemory creating a copy might be a concern There must be sufficient memory (in theheap) to hold the copy of the value

Examples

Display Name Property of timeseries Object

Create a MEX file disppropertyc in a folder on your MATLAB path================================================================= disppropertyc - Display timeseries Name property This is a MEX file for MATLAB Copyright 2013 The MathWorks Inc All rights reserved ================================================================= include mexh

void mexFunction(int nlhs mxArray plhs[] int nrhs const mxArray prhs[])

1 API Reference

1-490

Check for proper number of arguments if(nrhs=1) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidNumInputs One input required) else if(nlhsgt1) mexErrMsgIdAndTxt( MATLABdisppropertymaxlhs Too many output arguments) Check for timeseries object if (mxIsClass(prhs[0] timeseries)) mexErrMsgIdAndTxt( MATLABdisppropertyinvalidClass Input must be timeseries object) plhs[0] = mxGetProperty(prhs[0]0Name)

Build the MEX file

mex(-vdisppropertyc)

Create a timeseries object

ts = timeseries(rand(5 4)NameLaunchData)

Display name

tsname = dispproperty(ts)

tsname =LaunchData

Change Object Color

Open and build the mexgetpropertyc MEX file in the matlabrootexternexamplesmex folder

Limitationsbull mxGetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

mxGetProperty (C and Fortran)

1-491

See AlsomxSetProperty mxGetNumberOfElements mxGetM mxGetN

Introduced in R2008a

1 API Reference

1-492

mxGetScalar (C and Fortran)Real component of first data element in array

C Syntaxinclude matrixhdouble mxGetScalar(const mxArray pm)

Fortran Syntaxinclude fintrfhreal8 mxGetScalar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray cannot be a cell mxArray a structure mxArray or an emptymxArray

ReturnsThe value of the first real (nonimaginary) element of the mxArray

In C mxGetScalar returns a double If real elements in the mxArray are of a typeother than double then mxGetScalar automatically converts the scalar value into adouble To preserve the original data representation of the scalar cast the return valueto the desired data type

If pm points to a sparse mxArray then mxGetScalar returns the value of the firstnonzero real element in the mxArray If there are no nonzero elements then the functionreturns 0

mxGetScalar (C and Fortran)

1-493

DescriptionCall mxGetScalar to get the value of the first real (nonimaginary) element of themxArray

Usually you call mxGetScalar when pm points to an mxArray containing only oneelement (a scalar) However pm can point to an mxArray containing many elements Ifpm points to an mxArray containing multiple elements then the function returns thevalue of the first real element For example if pm points to a two-dimensional mxArraythen mxGetScalar returns the value of the (11) element If pm points to a three-dimensional mxArray then the function returns the value of the (111) element andso on

Use mxGetScalar on a nonempty mxArray of type numeric logical or char only To testfor these conditions use Matrix Library functions such as mxIsEmpty mxIsLogicalmxIsNumeric or mxIsChar

If the input value to mxGetScalar is type int64 or uint64 then the value might loseprecision if it is greater than flintmax

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull timestwoaltcbull xtimesyc

See the following examples in matlabrootexternexamplesmex

bull mexlockcbull mexlockfF

See the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

1 API Reference

1-494

See AlsomxGetM mxGetN mxIsScalar

mxGetScalar (C and Fortran)

1-495

mxGetString (C and Fortran)mxChar array to C-style string or Fortran character array

C Syntaxinclude matrixhint mxGetString(const mxArray pm char str mwSize strlen)

Fortran Syntaxinclude fintrfhinteger4 mxGetString(pm str strlen)mwPointer pmcharacter() strmwSize strlen

Argumentspm

Pointer to an mxChar arraystr

Starting location mxGetString writes the character data into str and then in Cterminates the string with a NULL character (in the manner of C strings) str canpoint to either dynamic or static memory

strlenSize in bytes of destination buffer pointed to by str Typically in C you set strlento 1 plus the number of elements in the mxArray to which pm points To get thenumber of elements use mxGetM or mxGetN

Do not use with ldquoMultibyte Encoded Charactersrdquo on page 1-497

1 API Reference

1-496

Returns0 on success or if strlen == 0 and 1 on failure Possible reasons for failure include

bull mxArray is not an mxChar arraybull strlen is not large enough to store the entire mxArray If so the function returns 1

and truncates the string

DescriptionCall mxGetString to copy the character data of an mxArray into a C-style string in C ora character array in Fortran The copied data starts at str and contains no more thanstrlen-1 characters in C (no more than strlen characters in Fortran) In C the C-style string is always terminated with a NULL character

If the array contains multiple rows the function copies them into a single array onecolumn at a time

Multibyte Encoded Characters

Use this function only with characters represented in single-byte encoding schemes Forcharacters represented in multibyte encoding schemes use the C functionmxArrayToString Fortran users must allocate sufficient space for the return string toavoid possible truncation

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmallocc

See the following examples in matlabrootexternexamplesmex

bull explorec

See the following examples in matlabrootexternexamplesrefbook

mxGetString (C and Fortran)

1-497

bull revordF

See AlsomxArrayToString mxCreateCharArray mxCreateCharMatrixFromStringsmxCreateString mxGetChars

Introduced before R2006a

1 API Reference

1-498

mxIsCell (C and Fortran)Determine whether input is cell array

C Syntaxinclude matrixhbool mxIsCell(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsCell(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCELL_CLASS and logical 0(false) otherwise

DescriptionUse mxIsCell to determine whether the specified array is a cell array

In C calling mxIsCell is equivalent to calling

mxGetClassID(pm) == mxCELL_CLASS

mxIsCell (C and Fortran)

1-499

In Fortran calling mxIsCell is equivalent to calling

mxGetClassName(pm) eq cell

Note mxIsCell does not answer the question ldquoIs this mxArray a cell of a cell arrayrdquo Anindividual cell of a cell array can be of any type

See AlsomxIsClass

Introduced before R2006a

1 API Reference

1-500

mxIsChar (C and Fortran)Determine whether input is mxChar array

C Syntaxinclude matrixhbool mxIsChar(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsChar(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to an array having the class mxCHAR_CLASS and logical 0(false) otherwise

DescriptionUse mxIsChar to determine whether pm points to an mxChar array

In C calling mxIsChar is equivalent to calling

mxGetClassID(pm) == mxCHAR_CLASS

mxIsChar (C and Fortran)

1-501

In Fortran calling mxIsChar is equivalent to calling

mxGetClassName(pm) eq char

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookcbull revordc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecharmatrixfromstrcbull mxmallocc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxIsClass mxGetClassID

Introduced before R2006a

1 API Reference

1-502

mxIsClass (C and Fortran)Determine whether array is object of specified class

C Syntaxinclude matrixhbool mxIsClass(const mxArray pm const char classname)

Fortran Syntaxinclude fintrfhinteger4 mxIsClass(pm classname)mwPointer pmcharacter() classname

Argumentspm

Pointer to an mxArrayclassname

Array category to test Specify classname as a string (not as an integer identifier)You can specify any one of the following predefined constants

Value of classname Corresponding Classcell mxCELL_CLASSchar mxCHAR_CLASSdouble mxDOUBLE_CLASSfunction_handle mxFUNCTION_CLASSint8 mxINT8_CLASSint16 mxINT16_CLASS

mxIsClass (C and Fortran)

1-503

Value of classname Corresponding Classint32 mxINT32_CLASSint64 mxINT64_CLASSlogical mxLOGICAL_CLASSsingle mxSINGLE_CLASSstruct mxSTRUCT_CLASSuint8 mxUINT8_CLASSuint16 mxUINT16_CLASSuint32 mxUINT32_CLASSuint64 mxUINT64_CLASSltclass_namegt ltclass_idgt

unknown mxUNKNOWN_CLASS

In the table ltclass_namegt represents the name of a specific MATLAB custom objectYou can also specify one of your own class names

ReturnsLogical 1 (true) if pm points to an array having category classname and logical 0(false) otherwise

DescriptionEach mxArray is tagged as being a certain type Call mxIsClass to determine whetherthe specified mxArray has this type MATLAB does not check if the class is derived froma base class

In C

mxIsClass(pm double)

is equivalent to calling either of these forms

1 API Reference

1-504

mxIsDouble(pm)

strcmp(mxGetClassName(pm) double)

In Fortran

mxIsClass(pm double)

is equivalent to calling either one of the following

mxIsDouble(pm)

mxGetClassName(pm) eq double

It is most efficient to use the mxIsDouble form

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisclassc

See AlsomxClassID mxGetClassID mxIsEmpty mxGetClassName

Introduced before R2006a

mxIsClass (C and Fortran)

1-505

mxIsComplex (C and Fortran)Determine whether data is complex

C Syntaxinclude matrixhbool mxIsComplex(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsComplex(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm is a numeric array containing complex data and logical 0 (false)otherwise If pm points to a cell array or a structure array mxIsComplex returns false

DescriptionUse mxIsComplex to determine whether an imaginary part is allocated for an mxArrayIf an mxArray is purely real and does not have any imaginary data the imaginarypointer pi is NULL in C (0 in Fortran) If an mxArray is complex pi points to an array ofnumbers

1 API Reference

1-506

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxgetinfc

See the following examples in matlabrootexternexamplesrefbook

bull conveccbull convecFbull fulltosparseFbull phonebookc

See the following examples in matlabrootexternexamplesmex

bull explorecbull yprimecbull mexlockc

See AlsomxIsNumeric

Introduced before R2006a

mxIsComplex (C and Fortran)

1-507

mxIsDouble (C and Fortran)Determine whether mxArray represents data as double-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsDouble(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsDouble(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as double-precision floating-pointnumbers and logical 0 (false) otherwise

DescriptionCall mxIsDouble to determine whether the specified mxArray represents its real andimaginary data as double-precision floating-point numbers

Older versions of MATLAB software store all mxArray data as double-precision floating-point numbers However starting with MATLAB Version 5 software MATLAB can storereal and imaginary data in various numerical formats

1 API Reference

1-508

In C calling mxIsDouble is equivalent to calling

mxGetClassID(pm) == mxDOUBLE_CLASS

In Fortran calling mxIsDouble is equivalent to calling

mxGetClassName(pm) eq double

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull fulltosparsecbull fulltosparseF

See the following examples in matlabrootexternexamplesmx

bull mxgetepscbull mxgetepsfF

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsDouble (C and Fortran)

1-509

mxIsEmpty (C and Fortran)Determine whether array is empty

C Syntaxinclude matrixhbool mxIsEmpty(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsEmpty(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is empty and logical 0 (false) otherwise

DescriptionUse mxIsEmpty to determine whether an mxArray contains no data An mxArray isempty if the size of any of its dimensions is 0

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-510

bull mxisfinitec

See AlsomxIsClass

Introduced before R2006a

mxIsEmpty (C and Fortran)

1-511

mxIsFinite (C and Fortran)Determine whether input is finite

C Syntaxinclude matrixhbool mxIsFinite(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsFinite(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is finite and logical 0 (false) otherwise

DescriptionCall mxIsFinite to determine whether value is finite A number is finite if it is greaterthan -Inf and less than Inf

ExamplesSee the following examples in matlabrootexternexamplesmx

1 API Reference

1-512

bull mxisfinitec

See AlsomxIsInf mxIsNan

Introduced before R2006a

mxIsFinite (C and Fortran)

1-513

mxIsFromGlobalWS (C and Fortran)Determine whether array was copied from MATLAB global workspace

C Syntaxinclude matrixhbool mxIsFromGlobalWS(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsFromGlobalWS(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array was copied out of the global workspace and logical 0(false) otherwise

DescriptionmxIsFromGlobalWS is useful for standalone MAT-file programs

1 API Reference

1-514

ExamplesSee the following examples in matlabrootexternexampleseng_mat

bull matcreatcbull matdgnsc

Introduced before R2006a

mxIsFromGlobalWS (C and Fortran)

1-515

mxIsInf (C and Fortran)Determine whether input is infinite

C Syntaxinclude matrixhbool mxIsInf(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsInf(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is infinite and logical 0 (false) otherwise

DescriptionCall mxIsInf to determine whether value is equal to infinity or minus infinityMATLAB software stores the value of infinity in a permanent variable named Inf whichrepresents IEEE arithmetic positive infinity The value of the variable Inf is built intothe system you cannot modify it

Operations that return infinity include

1 API Reference

1-516

bull Division by 0 For example 50 returns infinitybull Operations resulting in overflow For example exp(10000) returns infinity because

the result is too large to be represented on your machine

If value equals NaN (Not-a-Number) mxIsInf returns false In other words NaN is notequal to infinity

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxIsFinite mxIsNaN

Introduced before R2006a

mxIsInf (C and Fortran)

1-517

mxIsInt16 (C and Fortran)Determine whether array represents data as signed 16-bit integers

C Syntaxinclude matrixhbool mxIsInt16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt16 to determine whether the specified array represents its real andimaginary data as 16-bit signed integers

In C calling mxIsInt16 is equivalent to calling

mxGetClassID(pm) == mxINT16_CLASS

1 API Reference

1-518

In Fortran calling mxIsInt16 is equivalent to calling

mxGetClassName(pm) == int16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt16 (C and Fortran)

1-519

mxIsInt32 (C and Fortran)Determine whether array represents data as signed 32-bit integers

C Syntaxinclude matrixhbool mxIsInt32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt32 to determine whether the specified array represents its real andimaginary data as 32-bit signed integers

In C calling mxIsInt32 is equivalent to calling

mxGetClassID(pm) == mxINT32_CLASS

1 API Reference

1-520

In Fortran calling mxIsInt32 is equivalent to calling

mxGetClassName(pm) == int32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt32 (C and Fortran)

1-521

mxIsInt64 (C and Fortran)Determine whether array represents data as signed 64-bit integers

C Syntaxinclude matrixhbool mxIsInt64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsInt64 to determine whether the specified array represents its real andimaginary data as 64-bit signed integers

In C calling mxIsInt64 is equivalent to calling

mxGetClassID(pm) == mxINT64_CLASS

1 API Reference

1-522

In Fortran calling mxIsInt64 is equivalent to calling

mxGetClassName(pm) == int64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt64 (C and Fortran)

1-523

mxIsInt8 (C and Fortran)Determine whether array represents data as signed 8-bit integers

C Syntaxinclude matrixhbool mxIsInt8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsInt8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as signed 8-bit integers and logical 0 (false)otherwise

DescriptionUse mxIsInt8 to determine whether the specified array represents its real andimaginary data as 8-bit signed integers

In C calling mxIsInt8 is equivalent to calling

mxGetClassID(pm) == mxINT8_CLASS

1 API Reference

1-524

In Fortran calling mxIsInt8 is equivalent to calling

mxGetClassName(pm) eq int8

See AlsomxIsClass mxGetClassID mxIsInt16 mxIsInt32 mxIsInt64 mxIsUint8mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsInt8 (C and Fortran)

1-525

mxIsLogical (C and Fortran)Determine whether array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogical(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsLogical(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a logical mxArray Otherwise it returns logical 0(false)

DescriptionUse mxIsLogical to determine whether MATLAB software treats the data in themxArray as Boolean (logical) If an mxArray is logical MATLAB treats all zeros asmeaning false and all nonzero values as meaning true

1 API Reference

1-526

See AlsomxIsClass

TopicsldquoLogical Operationsrdquo

Introduced before R2006a

mxIsLogical (C and Fortran)

1-527

mxIsLogicalScalar (C)Determine whether scalar array is of type mxLogical

C Syntaxinclude matrixhbool mxIsLogicalScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray is of class mxLogical and has 1-by-1 dimensionsOtherwise it returns logical 0 (false)

DescriptionUse mxIsLogicalScalar to determine whether MATLAB treats the scalar data in themxArray as logical or numerical

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalarTrue

TopicsldquoLogical Operationsrdquo

1 API Reference

1-528

Introduced before R2006a

mxIsLogicalScalar (C)

1-529

mxIsLogicalScalarTrue (C)Determine whether scalar array of type mxLogical is true

C Syntaxinclude matrixhbool mxIsLogicalScalarTrue(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the value of the mxArray logical scalar element is true Otherwise itreturns logical 0 (false)

DescriptionUse mxIsLogicalScalarTrue to determine whether the value of a scalar mxArray istrue or false

See AlsomxGetLogicals | mxGetScalar | mxIsLogical | mxIsLogicalScalar

TopicsldquoLogical Operationsrdquo

1 API Reference

1-530

Introduced before R2006a

mxIsLogicalScalarTrue (C)

1-531

mxIsNaN (C and Fortran)Determine whether input is NaN (Not-a-Number)

C Syntaxinclude matrixhbool mxIsNaN(double value)

Fortran Syntaxinclude fintrfhinteger4 mxIsNaN(value)real8 value

Argumentsvalue

Double-precision floating-point number to test

ReturnsLogical 1 (true) if value is NaN (Not-a-Number) and logical 0 (false) otherwise

DescriptionCall mxIsNaN to determine whether value is NaN NaN is the IEEE arithmeticrepresentation for Not-a-Number A NaN is obtained as a result of mathematicallyundefined operations such as

bull 0000bull Inf-Inf

1 API Reference

1-532

The system understands a family of bit patterns as representing NaN NaN is not a singlevalue it is a family of numbers that MATLAB software (and other IEEE-compliantapplications) uses to represent an error condition or missing data

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See the following examples in matlabrootexternexamplesrefbook

bull findnzcbull fulltosparsec

See AlsomxIsFinite mxIsInf

Introduced before R2006a

mxIsNaN (C and Fortran)

1-533

mxIsNumeric (C and Fortran)Determine whether array is numeric

C Syntaxinclude matrixhbool mxIsNumeric(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsNumeric(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array can contain numeric data The following class IDs representstorage types for arrays that can contain numeric data

bull mxDOUBLE_CLASSbull mxSINGLE_CLASSbull mxINT8_CLASSbull mxUINT8_CLASSbull mxINT16_CLASSbull mxUINT16_CLASS

1 API Reference

1-534

bull mxINT32_CLASSbull mxUINT32_CLASSbull mxINT64_CLASSbull mxUINT64_CLASS

Logical 0 (false) if the array cannot contain numeric data

DescriptionCall mxIsNumeric to determine whether the specified array contains numeric data Ifthe specified array has a storage type that represents numeric data mxIsNumericreturns logical 1 (true) Otherwise mxIsNumeric returns logical 0 (false)

Call mxGetClassID to determine the exact storage type

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexampleseng_mat

bull matdemo1F

See AlsomxGetClassID

Introduced before R2006a

mxIsNumeric (C and Fortran)

1-535

mxIsScalar (C)Determine whether array is scalar array

C Syntaxinclude matrixhbool mxIsScalar(const mxArray array_ptr)

Argumentsarray_ptr

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray has 1-by-1 dimensions Otherwise it returns logical 0(false)

Note Only use mxIsScalar for mxArray classes with IDs documented by mxClassID

ExampleSee the following examples in matlabrootexternexamplesmx

bull mxisscalarc

See AlsomxClassID | mxGetScalar

1 API Reference

1-536

Introduced in R2015a

mxIsScalar (C)

1-537

mxIsSingle (C and Fortran)Determine whether array represents data as single-precision floating-point numbers

C Syntaxinclude matrixhbool mxIsSingle(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSingle(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the array stores its data as single-precision floating-point numbersand logical 0 (false) otherwise

DescriptionUse mxIsSingle to determine whether the specified array represents its real andimaginary data as single-precision floating-point numbers

In C calling mxIsSingle is equivalent to calling

mxGetClassID(pm) == mxSINGLE_CLASS

1 API Reference

1-538

In Fortran calling mxIsSingle is equivalent to calling

mxGetClassName(pm) eq single

See AlsomxIsClass mxGetClassID

Introduced before R2006a

mxIsSingle (C and Fortran)

1-539

mxIsSparse (C and Fortran)Determine whether input is sparse array

C Syntaxinclude matrixhbool mxIsSparse(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsSparse(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a sparse mxArray and logical 0 (false) otherwise Afalse return value means that pm points to a full mxArray or that pm does not point to avalid mxArray

DescriptionUse mxIsSparse to determine whether pm points to a sparse mxArray Many routines(for example mxGetIr and mxGetJc) require a sparse mxArray as input

1 API Reference

1-540

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxgetnzmaxcbull mxsetdimensionscbull mxsetdimensionsfFbull mxsetnzmaxc

See Alsosparse mxGetIr mxGetJc mxCreateSparse

Introduced before R2006a

mxIsSparse (C and Fortran)

1-541

mxIsStruct (C and Fortran)Determine whether input is structure array

C Syntaxinclude matrixhbool mxIsStruct(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsStruct(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if pm points to a structure mxArray and logical 0 (false) otherwise

DescriptionUse mxIsStruct to determine whether pm points to a structure mxArray Many routines(for example mxGetFieldNameByNumber and mxSetField) require a structuremxArray as an argument

1 API Reference

1-542

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldNameByNumbermxGetField mxSetField

Introduced before R2006a

mxIsStruct (C and Fortran)

1-543

mxIsUint16 (C and Fortran)Determine whether array represents data as unsigned 16-bit integers

C Syntaxinclude matrixhbool mxIsUint16(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint16(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 16-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint16 to determine whether the specified mxArray represents its real andimaginary data as 16-bit unsigned integers

In C calling mxIsUint16 is equivalent to calling

mxGetClassID(pm) == mxUINT16_CLASS

1 API Reference

1-544

In Fortran calling mxIsUint16 is equivalent to calling

mxGetClassName(pm) eq uint16

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint16 (C and Fortran)

1-545

mxIsUint32 (C and Fortran)Determine whether array represents data as unsigned 32-bit integers

C Syntaxinclude matrixhbool mxIsUint32(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint32(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 32-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint32 to determine whether the specified mxArray represents its real andimaginary data as 32-bit unsigned integers

In C calling mxIsUint32 is equivalent to calling

mxGetClassID(pm) == mxUINT32_CLASS

1 API Reference

1-546

In Fortran calling mxIsUint32 is equivalent to calling

mxGetClassName(pm) eq uint32

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint64

Introduced before R2006a

mxIsUint32 (C and Fortran)

1-547

mxIsUint64 (C and Fortran)Determine whether array represents data as unsigned 64-bit integers

C Syntaxinclude matrixhbool mxIsUint64(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint64(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 64-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint64 to determine whether the specified mxArray represents its real andimaginary data as 64-bit unsigned integers

In C calling mxIsUint64 is equivalent to calling

mxGetClassID(pm) == mxUINT64_CLASS

1 API Reference

1-548

In Fortran calling mxIsUint64 is equivalent to calling

mxGetClassName(pm) eq uint64

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint8 mxIsUint16 mxIsUint32

Introduced before R2006a

mxIsUint64 (C and Fortran)

1-549

mxIsUint8 (C and Fortran)Determine whether array represents data as unsigned 8-bit integers

C Syntaxinclude matrixhbool mxIsUint8(const mxArray pm)

Fortran Syntaxinclude fintrfhinteger4 mxIsUint8(pm)mwPointer pm

Argumentspm

Pointer to an mxArray

ReturnsLogical 1 (true) if the mxArray stores its data as unsigned 8-bit integers and logical 0(false) otherwise

DescriptionUse mxIsUint8 to determine whether the specified mxArray represents its real andimaginary data as 8-bit unsigned integers

In C calling mxIsUint8 is equivalent to calling

mxGetClassID(pm) == mxUINT8_CLASS

1 API Reference

1-550

In Fortran calling mxIsUint8 is equivalent to calling

mxGetClassName(pm) eq uint8

See AlsomxIsClass mxGetClassID mxIsInt8 mxIsInt16 mxIsInt32 mxIsInt64mxIsUint16 mxIsUint32 mxIsUint64

Introduced before R2006a

mxIsUint8 (C and Fortran)

1-551

mxLogical (C)Type for logical array

DescriptionAll logical mxArrays store their data elements as mxLogical rather than as bool

The header file containing this type is

include matrixh

See AlsomxCreateLogicalArray

Tipsbull For information about data in MATLAB language scripts and functions see ldquoData

Typesrdquo

Introduced before R2006a

1 API Reference

1-552

mxMalloc (C and Fortran)Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxMalloc(mwSize n)

Fortran Syntaxinclude fintrfhmwPointer mxMalloc(n)mwSize n

Argumentsn

Number of bytes to allocate for n greater than 0

ReturnsPointer to the start of the allocated dynamic memory if successful If unsuccessful in aMAT or engine standalone application mxMalloc returns NULL in C (0 in Fortran) Ifunsuccessful in a MEX file the MEX file terminates and control returns to the MATLABprompt

mxMalloc is unsuccessful when there is insufficient free heap space

If you call mxMalloc in C with value n = 0 MATLAB returns either NULL or a validpointer

mxMalloc (C and Fortran)

1-553

DescriptionmxMalloc allocates contiguous heap space sufficient to hold n bytes To allocate memoryin MATLAB applications use mxMalloc instead of the ANSI C malloc function

In MEX files but not MAT or engine applications mxMalloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxmalloccbull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

1 API Reference

1-554

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxRealloc

Introduced before R2006a

mxMalloc (C and Fortran)

1-555

mxRealloc (C and Fortran)Reallocate dynamic memory using MATLAB memory manager

C Syntaxinclude matrixhinclude ltstdlibhgtvoid mxRealloc(void ptr mwSize size)

Fortran Syntaxinclude fintrfhmwPointer mxRealloc(ptr size)mwPointer ptrmwSize size

Argumentsptr

Pointer to a block of memory allocated by mxCalloc mxMalloc or mxReallocsize

New size of allocated memory in bytes

ReturnsPointer to the start of the reallocated block of memory if successful If unsuccessful in aMAT or engine standalone application mxRealloc returns NULL in C (0 in Fortran) andleaves the original memory block unchanged (Use mxFree to free the original memoryblock) If unsuccessful in a MEX file the MEX file terminates and control returns to theMATLAB prompt

mxRealloc is unsuccessful when there is insufficient free heap space

1 API Reference

1-556

DescriptionmxRealloc changes the size of a memory block that has been allocated with mxCallocmxMalloc or mxRealloc To allocate memory in MATLAB applications use mxReallocinstead of the ANSI C realloc function

mxRealloc changes the size of the memory block pointed to by ptr to size bytes Thecontents of the reallocated memory are unchanged up to the smaller of the new and oldsizes The reallocated memory might be in a different location from the original memoryso the returned pointer can be different from ptr If the memory location changesmxRealloc frees the original memory block pointed to by ptr

If size is greater than 0 and ptr is NULL in C (0 in Fortran) mxRealloc behaves likemxMalloc mxRealloc allocates a new block of memory of size bytes and returns apointer to the new block

If size is 0 and ptr is not NULL in C (0 in Fortran) mxRealloc frees the memorypointed to by ptr and returns NULL in C (0 in Fortran)

In MEX files but not MAT or engine applications mxRealloc registers the allocatedmemory with the MATLAB memory manager When control returns to the MATLABprompt the memory manager then automatically frees or deallocates this memory

How you manage the memory created by this function depends on the purpose of thedata assigned to it If you assign it to an output argument in plhs[] using the mxSetPrfunction MATLAB is responsible for freeing the memory

If you use the data internally the MATLAB memory manager maintains a list of allmemory allocated by the function and automatically frees (deallocates) the memory whencontrol returns to the MATLAB prompt In general we recommend that MEX filefunctions destroy their own temporary arrays and free their own dynamically allocatedmemory It is more efficient to perform this cleanup in the source MEX file than to relyon the automatic mechanism Therefore when you finish using the memory allocated bythis function call mxFree to deallocate the memory

If you do not assign this data to an output argument and you want it to persist after theMEX file completes call mexMakeMemoryPersistent after calling this function If youwrite a MEX file with persistent memory be sure to register a mexAtExit function tofree allocated memory in the event your MEX file is cleared

mxRealloc (C and Fortran)

1-557

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomexAtExit mexMakeArrayPersistent mexMakeMemoryPersistent mxCallocmxDestroyArray mxFree mxMalloc

Introduced before R2006a

1 API Reference

1-558

mxRemoveField (C and Fortran)Remove field from structure array

C Syntaxinclude matrixhvoid mxRemoveField(mxArray pm int fieldnumber)

Fortran Syntaxinclude fintrfhsubroutine mxRemoveField(pm fieldnumber)mwPointer pminteger4 fieldnumber

Argumentspm

Pointer to a structure mxArrayfieldnumber

Number of the field you want to remove In C to remove the first field setfieldnumber to 0 to remove the second field set fieldnumber to 1 and so on InFortran to remove the first field set fieldnumber to 1 to remove the second fieldset fieldnumber to 2 and so on

DescriptionCall mxRemoveField to remove a field from a structure array If the field does not existnothing happens This function does not destroy the field values To destroy the actualfield values call mxRemoveField and then call mxDestroyArray

Consider a MATLAB structure initialized to

mxRemoveField (C and Fortran)

1-559

patientname = John Doepatientbilling = 12700patienttest = [79 75 73 180 178 1775 220 210 205]

In C the field number 0 represents the field name field number 1 represents fieldbilling field number 2 represents field test In Fortran the field number 1represents the field name field number 2 represents field billing field number 3represents field test

See AlsomxAddField mxDestroyArray mxGetFieldByNumber

Introduced before R2006a

1 API Reference

1-560

mxSetCell (C and Fortran)Set contents of cell array

C Syntaxinclude matrixhvoid mxSetCell(mxArray pm mwIndex index mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetCell(pm index value)mwPointer pm valuemwIndex index

Argumentspm

Pointer to a cell mxArrayindex

Index from the beginning of the mxArray Specify the number of elements betweenthe first cell of the mxArray and the cell you want to set The easiest way to calculateindex in a multidimensional cell array is to call mxCalcSingleSubscript

valuePointer to new value for the cell You can put an mxArray of any type into a cell Youcan even put another cell mxArray into a cell

DescriptionCall mxSetCell to put the designated value into a particular cell of a cell mxArray

mxSetCell (C and Fortran)

1-561

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxDestroyArray on the pointer returned by mxGetCellbefore you call mxSetCell

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull phonebookc

See the following examples in matlabrootexternexamplesmx

bull mxcreatecellmatrixcbull mxcreatecellmatrixfF

See AlsomxCreateCellArray mxCreateCellMatrix mxGetCell mxIsCellmxDestroyArray

Introduced before R2006a

1 API Reference

1-562

mxSetClassName (C)Structure array to MATLAB object array

Note Use mxSetClassName for classes defined without a classdef statement

C Syntaxinclude matrixhint mxSetClassName(mxArray array_ptr const char classname)

Argumentsarray_ptr

Pointer to an mxArray of class mxSTRUCT_CLASSclassname

Object class to which to convert array_ptr

Returns0 if successful and nonzero otherwise One cause of failure is that array_ptr is not astructure mxArray Call mxIsStruct to determine whether array_ptr is a structure

DescriptionmxSetClassName converts a structure array to an object array to be saved later to aMAT-file MATLAB does not register or validate the object until it is loaded by the LOADcommand If the specified classname is an undefined class within MATLAB LOADconverts the object back to a simple structure array

mxSetClassName (C)

1-563

See AlsomxIsClass mxGetClassID mxIsStruct

Introduced before R2006a

1 API Reference

1-564

mxSetData (C and Fortran)Set pointer to real numeric data elements in array

C Syntaxinclude matrixhvoid mxSetData(mxArray pm void pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetData(pm pr)mwPointer pm pr

Argumentspm

Pointer to an mxArraypr

Pointer to an array Each element in the array contains the real component of avalue The array must be in dynamic memory call mxCalloc to allocate thismemory Do not use the ANSI C calloc function which can cause memoryalignment issues leading to program termination

DescriptionmxSetData is like mxSetPr except that in C its second argument is a void Use thisfunction on numeric arrays with contents other than double

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetData before you callmxSetData

mxSetData (C and Fortran)

1-565

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetDatac

See AlsomxCalloc mxFree mxGetData mxSetPr

Introduced before R2006a

1 API Reference

1-566

mxSetDimensions (C and Fortran)Modify number of dimensions and size of each dimension

C Syntaxinclude matrixhint mxSetDimensions(mxArray pm const mwSize dims mwSize ndim)

Fortran Syntaxinclude fintrfhinteger4 mxSetDimensions(pm dims ndim)mwPointer pmmwSize ndimmwSize dims(ndim)

Argumentspm

Pointer to an mxArraydims

Dimensions array Each element in the dimensions array contains the size of thearray in that dimension For example in C setting dims[0] to 5 and dims[1] to 7establishes a 5-by-7 mxArray In Fortran setting dims(1) to 5 and dims(2) to 7establishes a 5-by-7 mxArray In most cases there are ndim elements in the dimsarray

ndimNumber of dimensions

mxSetDimensions (C and Fortran)

1-567

Returns0 on success and 1 on failure mxSetDimensions allocates heap space to hold the inputsize array So it is possible (though unlikely) that increasing the number of dimensionscan cause the system to run out of heap space

DescriptionCall mxSetDimensions to reshape an existing mxArray mxSetDimensions is likemxSetM and mxSetN however mxSetDimensions provides greater control for reshapingan mxArray that has more than two dimensions

mxSetDimensions does not allocate or deallocate any space for the pr or pi arrays Soif your call to mxSetDimensions increases the number of elements in the mxArrayenlarge the pr (and pi if it exists) arrays accordingly

If your call to mxSetDimensions reduces the number of elements in the mxArray youcan optionally reduce the size of the pr and pi arrays using mxRealloc

MATLAB automatically removes any trailing singleton dimensions specified in the dimsargument For example if ndim equals 5 and dims equals [4 1 7 1 1] the resultingarray has the dimensions 4-by-1-by-7

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionscbull mxsetdimensionsfF

See AlsomxGetNumberOfDimensions mxSetM mxSetN mxRealloc

Introduced before R2006a

1 API Reference

1-568

mxSetField (C and Fortran)Set field value in structure array given index and field name

C Syntaxinclude matrixhvoid mxSetField(mxArray pm mwIndex index const char fieldname mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetField(pm index fieldname pvalue)mwPointer pm pvaluemwIndex indexcharacter() fieldname

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of an element in the array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an index

mxSetField (C and Fortran)

1-569

fieldnameName of a field in the structure The field must exist in the structure CallmxGetFieldNameByNumber or mxGetFieldNumber to determine existing fieldnames

pvaluePointer to an mxArray containing the data you want to assign to fieldname

DescriptionUse mxSetField to assign the contents of pvalue to the field fieldname of elementindex

If you want to replace the contents of fieldname first free the memory of the existingdata Use the mxGetField function to get a pointer to the field call mxDestroyArray onthe pointer then call mxSetField to assign the new value

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then call mxSetFieldon each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

1 API Reference

1-570

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldmxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetFieldByNumber mxDestroyArray mxCalcSingleSubscript

Alternatives

C Language

In C you can replace the statements

field_num = mxGetFieldNumber(pa fieldname)mxSetFieldByNumber(pa index field_num new_value_pa)

with a call to mxSetField

mxSetField(pa index fieldname new_value_pa)

Fortran Language

In Fortran you can replace the statements

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

with a call to mxSetField

mxSetField(pm index fieldname newvalue)

Introduced before R2006a

mxSetField (C and Fortran)

1-571

mxSetFieldByNumber (C and Fortran)Set field value in structure array given index and field number

C Syntaxinclude matrixhvoid mxSetFieldByNumber(mxArray pm mwIndex index int fieldnumber mxArray pvalue)

Fortran Syntaxinclude fintrfhsubroutine mxSetFieldByNumber(pm index fieldnumber pvalue)mwPointer pm pvaluemwIndex indexinteger4 fieldnumber

Argumentspm

Pointer to a structure mxArray Call mxIsStruct to determine whether pm points toa structure mxArray

indexIndex of the desired element

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

See mxCalcSingleSubscript for details on calculating an indexfieldnumber

Position of the field in the structure The field must exist in the structure

1 API Reference

1-572

In C the first field within each element has a fieldnumber of 0 The fieldnumberof the last is N-1 where N is the number of fields

In Fortran the first field within each element has a fieldnumber of 1 Thefieldnumber of the last is N where N is the number of fields

pvaluePointer to the mxArray containing the data you want to assign

DescriptionUse mxSetFieldByNumber to assign the contents of pvalue to the field specified byfieldnumber of element index mxSetFieldByNumber is like mxSetField howeverthe function identifies the field by position number not by name

If you want to replace the contents at fieldnumber first free the memory of the existingdata Use the mxGetFieldByNumber function to get a pointer to the field callmxDestroyArray on the pointer then call mxSetFieldByNumber to assign the newvalue

You cannot assign pvalue to more than one field in a structure or to more than oneelement in the mxArray If you want to assign the contents of pvalue to multiple fieldsuse the mxDuplicateArray function to make copies of the data then callmxSetFieldByNumber on each copy

To free memory for structures created using this function call mxDestroyArray only onthe structure array Do not call mxDestroyArray on the array pvalue points to If youdo MATLAB attempts to free the same memory twice which can corrupt memory

Note Inputs to a MEX-file are constant read-only mxArrays Do not modify the inputsUsing mxSetCell or mxSetField functions to modify the cells or fields of a MATLABargument causes unpredictable results

mxSetFieldByNumber (C and Fortran)

1-573

Alternatives

C Language

In C calling

mxSetField(pa index field_name new_value_pa)

is equivalent to calling

field_num = mxGetFieldNumber(pa field_name)mxSetFieldByNumber(pa index field_num new_value_pa)

Fortran Language

In Fortran calling

mxSetField(pm index fieldname newvalue)

is equivalent to calling

fieldnum = mxGetFieldNumber(pm fieldname)mxSetFieldByNumber(pm index fieldnum newvalue)

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxcreatestructarrayc

See AlsomxCreateStructArray mxCreateStructMatrix mxGetFieldByNumbermxGetFieldNameByNumber mxGetFieldNumber mxGetNumberOfFieldsmxIsStruct mxSetField mxDestroyArray mxCalcSingleSubscript

Introduced before R2006a

1 API Reference

1-574

mxSetImagData (C and Fortran)Set pointer to imaginary data elements in array

C Syntaxinclude matrixhvoid mxSetImagData(mxArray pm void pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetImagData(pm pi)mwPointer pm pi

Argumentspm

Pointer to an mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory errors will result when the array is destroyed

DescriptionmxSetImagData is like mxSetPi except that in C its pi argument is a void Usethis function on numeric arrays with contents other than double

mxSetImagData (C and Fortran)

1-575

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetImagData beforeyou call mxSetImagData

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitec

See AlsomxCalloc mxFree mxGetImagData mxSetPi

Introduced before R2006a

1 API Reference

1-576

mxSetIr (C and Fortran)IR array of sparse array

C Syntaxinclude matrixhvoid mxSetIr(mxArray pm mwIndex ir)

Fortran Syntaxinclude fintrfhsubroutine mxSetIr(pm ir)mwPointer pm ir

Argumentspm

Pointer to a sparse mxArrayir

Pointer to the ir array The ir array must be sorted in column-major order

DescriptionUse mxSetIr to specify the ir array of a sparse mxArray The ir array is an array ofintegers the length of the ir array equals the value of nzmax the storage allocated forthe sparse array or nnz the number of nonzero matrix elements

Each element in the ir array indicates a row (offset by 1) at which a nonzero elementcan be found (The jc array is an index that indirectly specifies a column where nonzeroelements can be found See mxSetJc for more details on jc)

mxSetIr (C and Fortran)

1-577

For example suppose that you create a 7-by-3 sparse mxArray named Sparrowcontaining six nonzero elements by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The pr array holds the real data for the sparse matrix which in Sparrow is the five 1sand the one 2 If there is any nonzero imaginary data it is in a pi arraySubscript ir pr jc Comments(21) 1 1 0 Column 1 ir is 1 because row is 2(51) 4 1 2 Column 1 ir is 4 because row is 5(32) 2 1 3 Column 2 ir is 2 because row is 3(23) 1 2 6 Column 3 ir is 1 because row is 2(53) 4 1 Column 3 ir is 4 because row is 5(63) 5 1 Column 3 ir is 5 because row is 6

Notice how each element of the ir array is always 1 less than the row of thecorresponding nonzero element For instance the first nonzero element is in row 2therefore the first element in ir is 1 (that is 2 ndash 1) The second nonzero element is inrow 5 therefore the second element in ir is 4 (5 ndash 1)

The ir array must be in column-major order The ir array must define the row positionsin column 1 (if any) first then the row positions in column 2 (if any) second and so onthrough column N Within each column row position 1 must appear before row position2 and so on

mxSetIr does not sort the ir array for you you must specify an ir array that is alreadysorted

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetIr before you callmxSetIr

1 API Reference

1-578

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See the following examples in matlabrootexternexamplesmex

bull explorec

See AlsomxCreateSparse mxGetIr mxGetJc mxSetJc mxFree nzmax nnz

Introduced before R2006a

mxSetIr (C and Fortran)

1-579

mxSetJc (C and Fortran)JC array of sparse array

C Syntaxinclude matrixhvoid mxSetJc(mxArray pm mwIndex jc)

Fortran Syntaxinclude fintrfhsubroutine mxSetJc(pm jc)mwPointer pm jc

Argumentspm

Pointer to a sparse mxArrayjc

Pointer to the jc array

DescriptionUse mxSetJc to specify a new jc array for a sparse mxArray The jc array is an integerarray having n+1 elements where n is the number of columns in the sparse mxArray

If the jth column of the sparse mxArray has any nonzero elements

bull jc[j] is the index in ir pr and pi (if it exists) of the first nonzero element in thejth column

bull jc[j+1]-1 is the index of the last nonzero element in the jth column

1 API Reference

1-580

bull For the jth column of the sparse matrix jc[j] is the total number of nonzeroelements in all preceding columns

The number of nonzero elements in the jth column of the sparse mxArray is

jc[j+1] - jc[j]

For the jth column of the sparse mxArray jc[j] is the total number of nonzeroelements in all preceding columns The last element of the jc array jc[number ofcolumns] is equal to nnz which is the number of nonzero elements in the entire sparsemxArray

For example consider a 7-by-3 sparse mxArray named Sparrow containing six nonzeroelements created by typing

Sparrow = zeros(73)Sparrow(21) = 1Sparrow(51) = 1Sparrow(32) = 1Sparrow(23) = 2Sparrow(53) = 1Sparrow(63) = 1Sparrow = sparse(Sparrow)

The following table lists the contents of the ir jc and pr arraysSubscript ir pr jc Comment(21) 1 1 0 Column 1 contains two nonzero

elements with rows designated byir[0] and ir[1]

(51) 4 1 2 Column 2 contains one nonzeroelement with row designated by ir[2]

(32) 2 1 3 Column 3 contains three nonzeroelements with rows designated byir[3]ir[4] and ir[5]

(23) 1 2 6 There are six nonzero elements in all(53) 4 1 (63) 5 1

mxSetJc (C and Fortran)

1-581

As an example of a much sparser mxArray consider a 1000-by-8 sparse mxArray namedSpacious containing only three nonzero elements The ir pr and jc arrays containthe values listed in this tableSubscript ir pr jc Comment(732) 72 1 0 Column 1 contains no nonzero

elements(503) 49 1 0 Column 2 contains one nonzero

element with row designated by ir[0](645) 63 1 1 Column 3 contains one nonzero

element with row designated by ir[1] 2 Column 4 contains no nonzero

elements 2 Column 5 contains one nonzero

element with row designated by ir[2] 3 Column 6 contains no nonzero

elements 3 Column 7 contains no nonzero

elements 3 Column 8 contains no nonzero

elements 3 There are three nonzero elements in all

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetJc before you callmxSetJc

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesmex

bull explorec

1 API Reference

1-582

See AlsomxCreateSparse mxGetIr mxGetJc mxSetIr mxFree

Introduced before R2006a

mxSetJc (C and Fortran)

1-583

mxSetM (C and Fortran)Set number of rows in array

C Syntaxinclude matrixhvoid mxSetM(mxArray pm mwSize m)

Fortran Syntaxinclude fintrfhsubroutine mxSetM(pm m)mwPointer pmmwSize m

Argumentspm

Pointer to an mxArraym

Number of rows

DescriptionCall mxSetM to set the number of rows in the specified mxArray The term rows meansthe first dimension of an mxArray regardless of the number of dimensions Call mxSetNto set the number of columns

You typically use mxSetM to change the shape of an existing mxArray The mxSetMfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So ifyour calls to mxSetM and mxSetN increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays Call mxRealloc to enlarge them

1 API Reference

1-584

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetN mxRealloc

Introduced before R2006a

mxSetM (C and Fortran)

1-585

mxSetN (C and Fortran)Set number of columns in array

C Syntaxinclude matrixhvoid mxSetN(mxArray pm mwSize n)

Fortran Syntaxinclude fintrfhsubroutine mxSetN(pm n)mwPointer pmmwSize n

Argumentspm

Pointer to an mxArrayn

Number of columns

DescriptionCall mxSetN to set the number of columns in the specified mxArray The term columnsalways means the second dimension of a matrix Calling mxSetN forces an mxArray tohave two dimensions For example if pm points to an mxArray having three dimensionscalling mxSetN reduces the mxArray to two dimensions

You typically use mxSetN to change the shape of an existing mxArray The mxSetNfunction does not allocate or deallocate any space for the pr pi ir or jc arrays So if

1 API Reference

1-586

your calls to mxSetN and mxSetM increase the number of elements in the mxArrayenlarge the pr pi ir andor jc arrays

If calling mxSetM and mxSetN reduces the number of elements in the mxArray youmight want to reduce the sizes of the pr pi ir andor jc arrays to use heap space moreefficiently However reducing the size is not mandatory

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetdimensionsc

See the following examples in matlabrootexternexamplesrefbook

bull sincallcbull sincallF

See AlsomxGetM mxGetN mxSetM

Introduced before R2006a

mxSetN (C and Fortran)

1-587

mxSetNzmax (C and Fortran)Set storage space for nonzero elements

C Syntaxinclude matrixhvoid mxSetNzmax(mxArray pm mwSize nzmax)

Fortran Syntaxinclude fintrfhsubroutine mxSetNzmax(pm nzmax)mwPointer pmmwSize nzmax

Argumentspm

Pointer to a sparse mxArraynzmax

Number of elements mxCreateSparse should allocate to hold the arrays pointed toby ir pr and pi (if it exists) Set nzmax greater than or equal to the number ofnonzero elements in the mxArray but set it to be less than or equal to the number ofrows times the number of columns If you specify an nzmax value of 0 mxSetNzmaxsets the value of nzmax to 1

DescriptionUse mxSetNzmax to assign a new value to the nzmax field of the specified sparsemxArray The nzmax field holds the maximum number of nonzero elements in the sparsemxArray

1 API Reference

1-588

The number of elements in the ir pr and pi (if it exists) arrays must be equal tonzmax Therefore after calling mxSetNzmax you must change the size of the ir pr andpi arrays To change the size of one of these arrays

1 Call mxRealloc with a pointer to the array setting the size to the new value ofnzmax

2 Call the appropriate mxSet routine (mxSetIr mxSetPr or mxSetPi) to establishthe new memory area as the current one

Ways to determine how large to make nzmax are

bull Set nzmax equal to or slightly greater than the number of nonzero elements in asparse mxArray This approach conserves precious heap space

bull Make nzmax equal to the total number of elements in an mxArray This approacheliminates (or at least reduces) expensive reallocations

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetNzmax mxRealloc

Introduced before R2006a

mxSetNzmax (C and Fortran)

1-589

mxSetPi (C and Fortran)Set new imaginary data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPi(mxArray pm double pi)

Fortran Syntaxinclude fintrfhsubroutine mxSetPi(pm pi)mwPointer pm pi

Argumentspm

Pointer to a full (nonsparse) mxArraypi

Pointer to the first element of an array Each element in the array contains theimaginary component of a value The array must be in dynamic memory callmxCalloc to allocate this memory Do not use the ANSI C calloc function whichcan cause memory alignment issues leading to program termination If pi points tostatic memory memory leaks and other memory errors might result

DescriptionUse mxSetPi to set the imaginary data of the specified mxArray

Most mxCreate functions optionally allocate heap space to hold imaginary data If youtell an mxCreate function to allocate heap spacemdashfor example by setting theComplexFlag to mxCOMPLEX in C (1 in Fortran) or by setting pi to a non-NULL value in

1 API Reference

1-590

C (a nonzero value in Fortran)mdashyou do not ordinarily use mxSetPi to initialize thecreated mxArrays imaginary elements Rather you call mxSetPi to replace the initialimaginary values with new ones

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPi before you callmxSetPi

ExamplesSee the following examples in matlabrootexternexamplesmx

bull mxisfinitecbull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetImagData mxSetPr mxFree

Introduced before R2006a

mxSetPi (C and Fortran)

1-591

mxSetPr (C and Fortran)Set new real data elements in array of type DOUBLE

C Syntaxinclude matrixhvoid mxSetPr(mxArray pm double pr)

Fortran Syntaxinclude fintrfhsubroutine mxSetPr(pm pr)mwPointer pm pr

Argumentspm

Pointer to a full (nonsparse) mxArraypr

Pointer to the first element of an array Each element in the array contains the realcomponent of a value The array must be in dynamic memory call mxCalloc toallocate this memory Do not use the ANSI C calloc function which can causememory alignment issues leading to program termination If pr points to staticmemory memory leaks and other memory errors can result

DescriptionUse mxSetPr to set the real data of the specified mxArray

All mxCreate calls allocate heap space to hold real data Therefore you do notordinarily use mxSetPr to initialize the real elements of a freshly created mxArrayRather you call mxSetPr to replace the initial real values with new ones

1 API Reference

1-592

This function does not free any memory allocated for existing data that it displaces Tofree existing memory call mxFree on the pointer returned by mxGetPr before you callmxSetPr

ExamplesSee the following examples in matlabrootexternexamplesrefbook

bull arrayFillSetPrc

See the following examples in matlabrootexternexamplesmx

bull mxsetnzmaxc

See AlsomxGetPi mxGetPr mxSetData mxSetPi mxFree

Introduced before R2006a

mxSetPr (C and Fortran)

1-593

mxSetProperty (C and Fortran)Set value of public property of MATLAB object

C Syntaxinclude matrixhvoid mxSetProperty(mxArray pa mwIndex index const char propname const mxArray value)

Fortran Syntaxinclude fintrfhsubroutine mxSetProperty(pa index propname value)mwPointer pa valuemwIndex indexcharacter() propname

Argumentspa

Pointer to an mxArray which is an objectindex

Index of the desired element of the object array

In C the first element of an mxArray has an index of 0 The index of the lastelement is N-1 where N is the number of elements in the array In Fortran the firstelement of an mxArray has an index of 1 The index of the last element is N whereN is the number of elements in the array

propnameName of the property whose value you are assigning

valuePointer to the mxArray you are assigning

1 API Reference

1-594

DescriptionUse mxSetProperty to assign a value to the specified property In pseudo-Cterminology mxSetProperty performs the assignment

pa[index]propname = value

Property propname must be an existing public property and index must be within thebounds of the mxArray To test the index value use mxGetNumberOfElements ormxGetM and mxGetN functions

mxSetProperty makes a copy of the value before assigning it as the new property valueMaking a copy might be a concern if the property uses a large amount of memory Theremust be sufficient memory (in the heap) to hold the copy of the value

Limitationsbull mxSetProperty is not supported for standalone applications such as applications

built with the MATLAB engine API

See AlsomxGetProperty

Introduced in R2008a

mxSetProperty (C and Fortran)

1-595

Page 6: C and Fortran API Reference
Page 7: C and Fortran API Reference
Page 8: C and Fortran API Reference
Page 9: C and Fortran API Reference
Page 10: C and Fortran API Reference
Page 11: C and Fortran API Reference
Page 12: C and Fortran API Reference
Page 13: C and Fortran API Reference
Page 14: C and Fortran API Reference
Page 15: C and Fortran API Reference
Page 16: C and Fortran API Reference
Page 17: C and Fortran API Reference
Page 18: C and Fortran API Reference
Page 19: C and Fortran API Reference
Page 20: C and Fortran API Reference
Page 21: C and Fortran API Reference
Page 22: C and Fortran API Reference
Page 23: C and Fortran API Reference
Page 24: C and Fortran API Reference
Page 25: C and Fortran API Reference
Page 26: C and Fortran API Reference
Page 27: C and Fortran API Reference
Page 28: C and Fortran API Reference
Page 29: C and Fortran API Reference
Page 30: C and Fortran API Reference
Page 31: C and Fortran API Reference
Page 32: C and Fortran API Reference
Page 33: C and Fortran API Reference
Page 34: C and Fortran API Reference
Page 35: C and Fortran API Reference
Page 36: C and Fortran API Reference
Page 37: C and Fortran API Reference
Page 38: C and Fortran API Reference
Page 39: C and Fortran API Reference
Page 40: C and Fortran API Reference
Page 41: C and Fortran API Reference
Page 42: C and Fortran API Reference
Page 43: C and Fortran API Reference
Page 44: C and Fortran API Reference
Page 45: C and Fortran API Reference
Page 46: C and Fortran API Reference
Page 47: C and Fortran API Reference
Page 48: C and Fortran API Reference
Page 49: C and Fortran API Reference
Page 50: C and Fortran API Reference
Page 51: C and Fortran API Reference
Page 52: C and Fortran API Reference
Page 53: C and Fortran API Reference
Page 54: C and Fortran API Reference
Page 55: C and Fortran API Reference
Page 56: C and Fortran API Reference
Page 57: C and Fortran API Reference
Page 58: C and Fortran API Reference
Page 59: C and Fortran API Reference
Page 60: C and Fortran API Reference
Page 61: C and Fortran API Reference
Page 62: C and Fortran API Reference
Page 63: C and Fortran API Reference
Page 64: C and Fortran API Reference
Page 65: C and Fortran API Reference
Page 66: C and Fortran API Reference
Page 67: C and Fortran API Reference
Page 68: C and Fortran API Reference
Page 69: C and Fortran API Reference
Page 70: C and Fortran API Reference
Page 71: C and Fortran API Reference
Page 72: C and Fortran API Reference
Page 73: C and Fortran API Reference
Page 74: C and Fortran API Reference
Page 75: C and Fortran API Reference
Page 76: C and Fortran API Reference
Page 77: C and Fortran API Reference
Page 78: C and Fortran API Reference
Page 79: C and Fortran API Reference
Page 80: C and Fortran API Reference
Page 81: C and Fortran API Reference
Page 82: C and Fortran API Reference
Page 83: C and Fortran API Reference
Page 84: C and Fortran API Reference
Page 85: C and Fortran API Reference
Page 86: C and Fortran API Reference
Page 87: C and Fortran API Reference
Page 88: C and Fortran API Reference
Page 89: C and Fortran API Reference
Page 90: C and Fortran API Reference
Page 91: C and Fortran API Reference
Page 92: C and Fortran API Reference
Page 93: C and Fortran API Reference
Page 94: C and Fortran API Reference
Page 95: C and Fortran API Reference
Page 96: C and Fortran API Reference
Page 97: C and Fortran API Reference
Page 98: C and Fortran API Reference
Page 99: C and Fortran API Reference
Page 100: C and Fortran API Reference
Page 101: C and Fortran API Reference
Page 102: C and Fortran API Reference
Page 103: C and Fortran API Reference
Page 104: C and Fortran API Reference
Page 105: C and Fortran API Reference
Page 106: C and Fortran API Reference
Page 107: C and Fortran API Reference
Page 108: C and Fortran API Reference
Page 109: C and Fortran API Reference
Page 110: C and Fortran API Reference
Page 111: C and Fortran API Reference
Page 112: C and Fortran API Reference
Page 113: C and Fortran API Reference
Page 114: C and Fortran API Reference
Page 115: C and Fortran API Reference
Page 116: C and Fortran API Reference
Page 117: C and Fortran API Reference
Page 118: C and Fortran API Reference
Page 119: C and Fortran API Reference
Page 120: C and Fortran API Reference
Page 121: C and Fortran API Reference
Page 122: C and Fortran API Reference
Page 123: C and Fortran API Reference
Page 124: C and Fortran API Reference
Page 125: C and Fortran API Reference
Page 126: C and Fortran API Reference
Page 127: C and Fortran API Reference
Page 128: C and Fortran API Reference
Page 129: C and Fortran API Reference
Page 130: C and Fortran API Reference
Page 131: C and Fortran API Reference
Page 132: C and Fortran API Reference
Page 133: C and Fortran API Reference
Page 134: C and Fortran API Reference
Page 135: C and Fortran API Reference
Page 136: C and Fortran API Reference
Page 137: C and Fortran API Reference
Page 138: C and Fortran API Reference
Page 139: C and Fortran API Reference
Page 140: C and Fortran API Reference
Page 141: C and Fortran API Reference
Page 142: C and Fortran API Reference
Page 143: C and Fortran API Reference
Page 144: C and Fortran API Reference
Page 145: C and Fortran API Reference
Page 146: C and Fortran API Reference
Page 147: C and Fortran API Reference
Page 148: C and Fortran API Reference
Page 149: C and Fortran API Reference
Page 150: C and Fortran API Reference
Page 151: C and Fortran API Reference
Page 152: C and Fortran API Reference
Page 153: C and Fortran API Reference
Page 154: C and Fortran API Reference
Page 155: C and Fortran API Reference
Page 156: C and Fortran API Reference
Page 157: C and Fortran API Reference
Page 158: C and Fortran API Reference
Page 159: C and Fortran API Reference
Page 160: C and Fortran API Reference
Page 161: C and Fortran API Reference
Page 162: C and Fortran API Reference
Page 163: C and Fortran API Reference
Page 164: C and Fortran API Reference
Page 165: C and Fortran API Reference
Page 166: C and Fortran API Reference
Page 167: C and Fortran API Reference
Page 168: C and Fortran API Reference
Page 169: C and Fortran API Reference
Page 170: C and Fortran API Reference
Page 171: C and Fortran API Reference
Page 172: C and Fortran API Reference
Page 173: C and Fortran API Reference
Page 174: C and Fortran API Reference
Page 175: C and Fortran API Reference
Page 176: C and Fortran API Reference
Page 177: C and Fortran API Reference
Page 178: C and Fortran API Reference
Page 179: C and Fortran API Reference
Page 180: C and Fortran API Reference
Page 181: C and Fortran API Reference
Page 182: C and Fortran API Reference
Page 183: C and Fortran API Reference
Page 184: C and Fortran API Reference
Page 185: C and Fortran API Reference
Page 186: C and Fortran API Reference
Page 187: C and Fortran API Reference
Page 188: C and Fortran API Reference
Page 189: C and Fortran API Reference
Page 190: C and Fortran API Reference
Page 191: C and Fortran API Reference
Page 192: C and Fortran API Reference
Page 193: C and Fortran API Reference
Page 194: C and Fortran API Reference
Page 195: C and Fortran API Reference
Page 196: C and Fortran API Reference
Page 197: C and Fortran API Reference
Page 198: C and Fortran API Reference
Page 199: C and Fortran API Reference
Page 200: C and Fortran API Reference
Page 201: C and Fortran API Reference
Page 202: C and Fortran API Reference
Page 203: C and Fortran API Reference
Page 204: C and Fortran API Reference
Page 205: C and Fortran API Reference
Page 206: C and Fortran API Reference
Page 207: C and Fortran API Reference
Page 208: C and Fortran API Reference
Page 209: C and Fortran API Reference
Page 210: C and Fortran API Reference
Page 211: C and Fortran API Reference
Page 212: C and Fortran API Reference
Page 213: C and Fortran API Reference
Page 214: C and Fortran API Reference
Page 215: C and Fortran API Reference
Page 216: C and Fortran API Reference
Page 217: C and Fortran API Reference
Page 218: C and Fortran API Reference
Page 219: C and Fortran API Reference
Page 220: C and Fortran API Reference
Page 221: C and Fortran API Reference
Page 222: C and Fortran API Reference
Page 223: C and Fortran API Reference
Page 224: C and Fortran API Reference
Page 225: C and Fortran API Reference
Page 226: C and Fortran API Reference
Page 227: C and Fortran API Reference
Page 228: C and Fortran API Reference
Page 229: C and Fortran API Reference
Page 230: C and Fortran API Reference
Page 231: C and Fortran API Reference
Page 232: C and Fortran API Reference
Page 233: C and Fortran API Reference
Page 234: C and Fortran API Reference
Page 235: C and Fortran API Reference
Page 236: C and Fortran API Reference
Page 237: C and Fortran API Reference
Page 238: C and Fortran API Reference
Page 239: C and Fortran API Reference
Page 240: C and Fortran API Reference
Page 241: C and Fortran API Reference
Page 242: C and Fortran API Reference
Page 243: C and Fortran API Reference
Page 244: C and Fortran API Reference
Page 245: C and Fortran API Reference
Page 246: C and Fortran API Reference
Page 247: C and Fortran API Reference
Page 248: C and Fortran API Reference
Page 249: C and Fortran API Reference
Page 250: C and Fortran API Reference
Page 251: C and Fortran API Reference
Page 252: C and Fortran API Reference
Page 253: C and Fortran API Reference
Page 254: C and Fortran API Reference
Page 255: C and Fortran API Reference
Page 256: C and Fortran API Reference
Page 257: C and Fortran API Reference
Page 258: C and Fortran API Reference
Page 259: C and Fortran API Reference
Page 260: C and Fortran API Reference
Page 261: C and Fortran API Reference
Page 262: C and Fortran API Reference
Page 263: C and Fortran API Reference
Page 264: C and Fortran API Reference
Page 265: C and Fortran API Reference
Page 266: C and Fortran API Reference
Page 267: C and Fortran API Reference
Page 268: C and Fortran API Reference
Page 269: C and Fortran API Reference
Page 270: C and Fortran API Reference
Page 271: C and Fortran API Reference
Page 272: C and Fortran API Reference
Page 273: C and Fortran API Reference
Page 274: C and Fortran API Reference
Page 275: C and Fortran API Reference
Page 276: C and Fortran API Reference
Page 277: C and Fortran API Reference
Page 278: C and Fortran API Reference
Page 279: C and Fortran API Reference
Page 280: C and Fortran API Reference
Page 281: C and Fortran API Reference
Page 282: C and Fortran API Reference
Page 283: C and Fortran API Reference
Page 284: C and Fortran API Reference
Page 285: C and Fortran API Reference
Page 286: C and Fortran API Reference
Page 287: C and Fortran API Reference
Page 288: C and Fortran API Reference
Page 289: C and Fortran API Reference
Page 290: C and Fortran API Reference
Page 291: C and Fortran API Reference
Page 292: C and Fortran API Reference
Page 293: C and Fortran API Reference
Page 294: C and Fortran API Reference
Page 295: C and Fortran API Reference
Page 296: C and Fortran API Reference
Page 297: C and Fortran API Reference
Page 298: C and Fortran API Reference
Page 299: C and Fortran API Reference
Page 300: C and Fortran API Reference
Page 301: C and Fortran API Reference
Page 302: C and Fortran API Reference
Page 303: C and Fortran API Reference
Page 304: C and Fortran API Reference
Page 305: C and Fortran API Reference
Page 306: C and Fortran API Reference
Page 307: C and Fortran API Reference
Page 308: C and Fortran API Reference
Page 309: C and Fortran API Reference
Page 310: C and Fortran API Reference
Page 311: C and Fortran API Reference
Page 312: C and Fortran API Reference
Page 313: C and Fortran API Reference
Page 314: C and Fortran API Reference
Page 315: C and Fortran API Reference
Page 316: C and Fortran API Reference
Page 317: C and Fortran API Reference
Page 318: C and Fortran API Reference
Page 319: C and Fortran API Reference
Page 320: C and Fortran API Reference
Page 321: C and Fortran API Reference
Page 322: C and Fortran API Reference
Page 323: C and Fortran API Reference
Page 324: C and Fortran API Reference
Page 325: C and Fortran API Reference
Page 326: C and Fortran API Reference
Page 327: C and Fortran API Reference
Page 328: C and Fortran API Reference
Page 329: C and Fortran API Reference
Page 330: C and Fortran API Reference
Page 331: C and Fortran API Reference
Page 332: C and Fortran API Reference
Page 333: C and Fortran API Reference
Page 334: C and Fortran API Reference
Page 335: C and Fortran API Reference
Page 336: C and Fortran API Reference
Page 337: C and Fortran API Reference
Page 338: C and Fortran API Reference
Page 339: C and Fortran API Reference
Page 340: C and Fortran API Reference
Page 341: C and Fortran API Reference
Page 342: C and Fortran API Reference
Page 343: C and Fortran API Reference
Page 344: C and Fortran API Reference
Page 345: C and Fortran API Reference
Page 346: C and Fortran API Reference
Page 347: C and Fortran API Reference
Page 348: C and Fortran API Reference
Page 349: C and Fortran API Reference
Page 350: C and Fortran API Reference
Page 351: C and Fortran API Reference
Page 352: C and Fortran API Reference
Page 353: C and Fortran API Reference
Page 354: C and Fortran API Reference
Page 355: C and Fortran API Reference
Page 356: C and Fortran API Reference
Page 357: C and Fortran API Reference
Page 358: C and Fortran API Reference
Page 359: C and Fortran API Reference
Page 360: C and Fortran API Reference
Page 361: C and Fortran API Reference
Page 362: C and Fortran API Reference
Page 363: C and Fortran API Reference
Page 364: C and Fortran API Reference
Page 365: C and Fortran API Reference
Page 366: C and Fortran API Reference
Page 367: C and Fortran API Reference
Page 368: C and Fortran API Reference
Page 369: C and Fortran API Reference
Page 370: C and Fortran API Reference
Page 371: C and Fortran API Reference
Page 372: C and Fortran API Reference
Page 373: C and Fortran API Reference
Page 374: C and Fortran API Reference
Page 375: C and Fortran API Reference
Page 376: C and Fortran API Reference
Page 377: C and Fortran API Reference
Page 378: C and Fortran API Reference
Page 379: C and Fortran API Reference
Page 380: C and Fortran API Reference
Page 381: C and Fortran API Reference
Page 382: C and Fortran API Reference
Page 383: C and Fortran API Reference
Page 384: C and Fortran API Reference
Page 385: C and Fortran API Reference
Page 386: C and Fortran API Reference
Page 387: C and Fortran API Reference
Page 388: C and Fortran API Reference
Page 389: C and Fortran API Reference
Page 390: C and Fortran API Reference
Page 391: C and Fortran API Reference
Page 392: C and Fortran API Reference
Page 393: C and Fortran API Reference
Page 394: C and Fortran API Reference
Page 395: C and Fortran API Reference
Page 396: C and Fortran API Reference
Page 397: C and Fortran API Reference
Page 398: C and Fortran API Reference
Page 399: C and Fortran API Reference
Page 400: C and Fortran API Reference
Page 401: C and Fortran API Reference
Page 402: C and Fortran API Reference
Page 403: C and Fortran API Reference
Page 404: C and Fortran API Reference
Page 405: C and Fortran API Reference
Page 406: C and Fortran API Reference
Page 407: C and Fortran API Reference
Page 408: C and Fortran API Reference
Page 409: C and Fortran API Reference
Page 410: C and Fortran API Reference
Page 411: C and Fortran API Reference
Page 412: C and Fortran API Reference
Page 413: C and Fortran API Reference
Page 414: C and Fortran API Reference
Page 415: C and Fortran API Reference
Page 416: C and Fortran API Reference
Page 417: C and Fortran API Reference
Page 418: C and Fortran API Reference
Page 419: C and Fortran API Reference
Page 420: C and Fortran API Reference
Page 421: C and Fortran API Reference
Page 422: C and Fortran API Reference
Page 423: C and Fortran API Reference
Page 424: C and Fortran API Reference
Page 425: C and Fortran API Reference
Page 426: C and Fortran API Reference
Page 427: C and Fortran API Reference
Page 428: C and Fortran API Reference
Page 429: C and Fortran API Reference
Page 430: C and Fortran API Reference
Page 431: C and Fortran API Reference
Page 432: C and Fortran API Reference
Page 433: C and Fortran API Reference
Page 434: C and Fortran API Reference
Page 435: C and Fortran API Reference
Page 436: C and Fortran API Reference
Page 437: C and Fortran API Reference
Page 438: C and Fortran API Reference
Page 439: C and Fortran API Reference
Page 440: C and Fortran API Reference
Page 441: C and Fortran API Reference
Page 442: C and Fortran API Reference
Page 443: C and Fortran API Reference
Page 444: C and Fortran API Reference
Page 445: C and Fortran API Reference
Page 446: C and Fortran API Reference
Page 447: C and Fortran API Reference
Page 448: C and Fortran API Reference
Page 449: C and Fortran API Reference
Page 450: C and Fortran API Reference
Page 451: C and Fortran API Reference
Page 452: C and Fortran API Reference
Page 453: C and Fortran API Reference
Page 454: C and Fortran API Reference
Page 455: C and Fortran API Reference
Page 456: C and Fortran API Reference
Page 457: C and Fortran API Reference
Page 458: C and Fortran API Reference
Page 459: C and Fortran API Reference
Page 460: C and Fortran API Reference
Page 461: C and Fortran API Reference
Page 462: C and Fortran API Reference
Page 463: C and Fortran API Reference
Page 464: C and Fortran API Reference
Page 465: C and Fortran API Reference
Page 466: C and Fortran API Reference
Page 467: C and Fortran API Reference
Page 468: C and Fortran API Reference
Page 469: C and Fortran API Reference
Page 470: C and Fortran API Reference
Page 471: C and Fortran API Reference
Page 472: C and Fortran API Reference
Page 473: C and Fortran API Reference
Page 474: C and Fortran API Reference
Page 475: C and Fortran API Reference
Page 476: C and Fortran API Reference
Page 477: C and Fortran API Reference
Page 478: C and Fortran API Reference
Page 479: C and Fortran API Reference
Page 480: C and Fortran API Reference
Page 481: C and Fortran API Reference
Page 482: C and Fortran API Reference
Page 483: C and Fortran API Reference
Page 484: C and Fortran API Reference
Page 485: C and Fortran API Reference
Page 486: C and Fortran API Reference
Page 487: C and Fortran API Reference
Page 488: C and Fortran API Reference
Page 489: C and Fortran API Reference
Page 490: C and Fortran API Reference
Page 491: C and Fortran API Reference
Page 492: C and Fortran API Reference
Page 493: C and Fortran API Reference
Page 494: C and Fortran API Reference
Page 495: C and Fortran API Reference
Page 496: C and Fortran API Reference
Page 497: C and Fortran API Reference
Page 498: C and Fortran API Reference
Page 499: C and Fortran API Reference
Page 500: C and Fortran API Reference
Page 501: C and Fortran API Reference
Page 502: C and Fortran API Reference
Page 503: C and Fortran API Reference
Page 504: C and Fortran API Reference
Page 505: C and Fortran API Reference
Page 506: C and Fortran API Reference
Page 507: C and Fortran API Reference
Page 508: C and Fortran API Reference
Page 509: C and Fortran API Reference
Page 510: C and Fortran API Reference
Page 511: C and Fortran API Reference
Page 512: C and Fortran API Reference
Page 513: C and Fortran API Reference
Page 514: C and Fortran API Reference
Page 515: C and Fortran API Reference
Page 516: C and Fortran API Reference
Page 517: C and Fortran API Reference
Page 518: C and Fortran API Reference
Page 519: C and Fortran API Reference
Page 520: C and Fortran API Reference
Page 521: C and Fortran API Reference
Page 522: C and Fortran API Reference
Page 523: C and Fortran API Reference
Page 524: C and Fortran API Reference
Page 525: C and Fortran API Reference
Page 526: C and Fortran API Reference
Page 527: C and Fortran API Reference
Page 528: C and Fortran API Reference
Page 529: C and Fortran API Reference
Page 530: C and Fortran API Reference
Page 531: C and Fortran API Reference
Page 532: C and Fortran API Reference
Page 533: C and Fortran API Reference
Page 534: C and Fortran API Reference
Page 535: C and Fortran API Reference
Page 536: C and Fortran API Reference
Page 537: C and Fortran API Reference
Page 538: C and Fortran API Reference
Page 539: C and Fortran API Reference
Page 540: C and Fortran API Reference
Page 541: C and Fortran API Reference
Page 542: C and Fortran API Reference
Page 543: C and Fortran API Reference
Page 544: C and Fortran API Reference
Page 545: C and Fortran API Reference
Page 546: C and Fortran API Reference
Page 547: C and Fortran API Reference
Page 548: C and Fortran API Reference
Page 549: C and Fortran API Reference
Page 550: C and Fortran API Reference
Page 551: C and Fortran API Reference
Page 552: C and Fortran API Reference
Page 553: C and Fortran API Reference
Page 554: C and Fortran API Reference
Page 555: C and Fortran API Reference
Page 556: C and Fortran API Reference
Page 557: C and Fortran API Reference
Page 558: C and Fortran API Reference
Page 559: C and Fortran API Reference
Page 560: C and Fortran API Reference
Page 561: C and Fortran API Reference
Page 562: C and Fortran API Reference
Page 563: C and Fortran API Reference
Page 564: C and Fortran API Reference
Page 565: C and Fortran API Reference
Page 566: C and Fortran API Reference
Page 567: C and Fortran API Reference
Page 568: C and Fortran API Reference
Page 569: C and Fortran API Reference
Page 570: C and Fortran API Reference
Page 571: C and Fortran API Reference
Page 572: C and Fortran API Reference
Page 573: C and Fortran API Reference
Page 574: C and Fortran API Reference
Page 575: C and Fortran API Reference
Page 576: C and Fortran API Reference
Page 577: C and Fortran API Reference
Page 578: C and Fortran API Reference
Page 579: C and Fortran API Reference
Page 580: C and Fortran API Reference
Page 581: C and Fortran API Reference
Page 582: C and Fortran API Reference
Page 583: C and Fortran API Reference
Page 584: C and Fortran API Reference
Page 585: C and Fortran API Reference
Page 586: C and Fortran API Reference
Page 587: C and Fortran API Reference
Page 588: C and Fortran API Reference
Page 589: C and Fortran API Reference
Page 590: C and Fortran API Reference
Page 591: C and Fortran API Reference
Page 592: C and Fortran API Reference
Page 593: C and Fortran API Reference
Page 594: C and Fortran API Reference
Page 595: C and Fortran API Reference
Page 596: C and Fortran API Reference
Page 597: C and Fortran API Reference
Page 598: C and Fortran API Reference
Page 599: C and Fortran API Reference
Page 600: C and Fortran API Reference