MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting...

21
MatLab API in C++ MatLab API in C++ Christopher Dabney Christopher Dabney

Transcript of MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting...

Page 1: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

MatLab API in C++MatLab API in C++

Christopher DabneyChristopher Dabney

Page 2: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

PurposePurpose

MatLab …MatLab … is an interpreted scripting languageis an interpreted scripting language

conversion to object code is at runtime; conversion to object code is at runtime; computation time can be a little slowcomputation time can be a little slow

has excellent prototyping and plotting has excellent prototyping and plotting functionalityfunctionality

contains convenient and very robust contains convenient and very robust matrix operation packagesmatrix operation packages

Page 3: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Purpose (cont)Purpose (cont)

C++C++ is a programming language, optimal and is a programming language, optimal and

with high speed floating point with high speed floating point computationcomputation

is non-trivial to produce visual effects inis non-trivial to produce visual effects in eg. plotting, GUIs, nice tableseg. plotting, GUIs, nice tables

can be difficult to secure a robust vector can be difficult to secure a robust vector algebra package foralgebra package for

Page 4: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Purpose (cont)Purpose (cont)

Solution: C++ invoking MatLab Solution: C++ invoking MatLab commandscommands number crunching in C++number crunching in C++ matrix operations in MatLabmatrix operations in MatLab plotting, graphing, tables in MatLabplotting, graphing, tables in MatLab

For programmers with a robust & For programmers with a robust & complex C++ program intending to plot complex C++ program intending to plot results they are already obtainingresults they are already obtaining

For MatLab programming with scripts For MatLab programming with scripts which frequently lagwhich frequently lag

Page 5: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Interacting with MatLabInteracting with MatLab

Not restricted to C++; Java, Perl, Fortran, Not restricted to C++; Java, Perl, Fortran, and other languages can do it alsoand other languages can do it also

Not restricted to the MS Visual Studio Not restricted to the MS Visual Studio environment the demos are written inenvironment the demos are written in

Also possible to invoke a C++ routine from Also possible to invoke a C++ routine from MatLab’s environmentMatLab’s environment

Three ways to interactThree ways to interact Send Data from C++ to MatLabSend Data from C++ to MatLab Call a MatLab function from C++Call a MatLab function from C++ Generate a Dynamic Link Library (dll) file from Generate a Dynamic Link Library (dll) file from

a .m filea .m file We will use the first oneWe will use the first one

Page 6: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Demo RequirementsDemo Requirements

A C++ Compiler A C++ Compiler the demo uses MS Visual C++ v.6.0the demo uses MS Visual C++ v.6.0

MatLab MatLab the demo uses MatLab v.7.0.1the demo uses MatLab v.7.0.1

Assume’s prior programming Assume’s prior programming experience in both MatLab and C++experience in both MatLab and C++ no explanations are given for the no explanations are given for the

commandscommands Following slides explain setting up the Following slides explain setting up the

demonstration program environmentdemonstration program environment

Page 7: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Setting up the EnvironmentSetting up the Environment Creating paths to MatLab:Creating paths to MatLab:

- Tools -> Options- Tools -> Options

- Directories Tab- Directories Tab

- Select "Include files" from the drop-down list- Select "Include files" from the drop-down list

- Add - Add "C:\MATLAB701\EXTERN\INCLUDE""C:\MATLAB701\EXTERN\INCLUDE" to the list to the list

- Select "Library Files" from the drop-down list- Select "Library Files" from the drop-down list - Add - Add ”C:\MATLAB701\EXTERN\LIB\WIN32\MICROSOFT\MSVC60“”C:\MATLAB701\EXTERN\LIB\WIN32\MICROSOFT\MSVC60“

Library paths vary depending on the language and Library paths vary depending on the language and compilercompiler

Page 8: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

ScreenshotScreenshot

Page 9: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Setting up the Environment Setting up the Environment (cont)(cont)

Two ways to include the appropriate library Two ways to include the appropriate library files:files:

Method 1)Method 1) - Project -> Settings - Project -> Settings - Links Tab- Links Tab

Under "Object/Library Module:", add three file Under "Object/Library Module:", add three file names:names:

- Libmx.lib- Libmx.lib- libmex.lib- libmex.lib- libeng.lib- libeng.lib

Method 2)Method 2) Add the following lines of code just under the Add the following lines of code just under the includes in the source code:includes in the source code:

#pragma comment( lib, "Libmx.lib" )#pragma comment( lib, "Libmx.lib" ) #pragma comment( lib, "libmex.lib" )#pragma comment( lib, "libmex.lib" ) #pragma comment( lib, "libeng.lib" )#pragma comment( lib, "libeng.lib" )

Page 10: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

ScreenshotScreenshot

Page 11: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Connecting to MatLab Connecting to MatLab EngineEngine

Header:Header: #include <engine.h> #include <engine.h>, MatLab’s , MatLab’s EngineEngine

In the program, create a pointer to it:In the program, create a pointer to it:

Engine *m_pEngine;Engine *m_pEngine;m_pEngine = engOpen(NULL);m_pEngine = engOpen(NULL);if (m_pEngine == NULL)if (m_pEngine == NULL){{

cout << "Error: Not Found” cout << "Error: Not Found” << endl;<< endl; exit(1);exit(1);

}}

Page 12: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Invoking CommandsInvoking Commands

engEvalString(Engine* ptr, string cmd);engEvalString(Engine* ptr, string cmd);

engEvalString(m_pEngine, “x = 1:1:10);“ );engEvalString(m_pEngine, “x = 1:1:10);“ );engEvalString(m_pEngine, “y = x.^2;“ );engEvalString(m_pEngine, “y = x.^2;“ );engEvalString(m_pEngine, “plot(x,y);“ );engEvalString(m_pEngine, “plot(x,y);“ );

Enables programmer to invoke any Enables programmer to invoke any command in MatLab from the C++ command in MatLab from the C++ platform (convenient)platform (convenient)

Not special by itself - might as well Not special by itself - might as well work straight from MatLabwork straight from MatLab

Page 13: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

IO between C++ and IO between C++ and MatLabMatLab

Use the “matrix array” Use the “matrix array” mxArraymxArray data data typetype

Every variable in MatLab is a matrix – Every variable in MatLab is a matrix – for C++ to exchange data with it, a for C++ to exchange data with it, a data type that both C++ and MatLab data type that both C++ and MatLab recognize is neededrecognize is needed

mxArraymxArray can “bundle” C++ variables can “bundle” C++ variables as matrices, so both platforms as matrices, so both platforms recognize this data typerecognize this data type

Page 14: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Inserting Values (input)Inserting Values (input) To pass a variable, eg. x[0], into MatLab, create an To pass a variable, eg. x[0], into MatLab, create an mxArraymxArray for it for it

- Allocate the space (- Allocate the space (mxCreateDoubleMatrixmxCreateDoubleMatrix))- Copy the value (- Copy the value (memcpymemcpy))- Name the variable in the Engine - Name the variable in the Engine

((engPutVariableengPutVariable))

double x[0];double x[0];mxArray *m_X;mxArray *m_X;m_X=mxCreateDoubleMatrix(1, 1, mxREAL);m_X=mxCreateDoubleMatrix(1, 1, mxREAL);memcpy((void *)mxGetPr(m_X), (void *)x, memcpy((void *)mxGetPr(m_X), (void *)x, sizeof(double)*1);sizeof(double)*1);engPutVariable(m_pEngine, "x", m_X);engPutVariable(m_pEngine, "x", m_X);

Pointer Pointer m_pEnginem_pEngine is used to specify the engine is used to specify the engine Variable x in the MatLab Engine gets the value of Variable x in the MatLab Engine gets the value of

x[0] in C++x[0] in C++

Page 15: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Extracting Values (output)Extracting Values (output) To extract the MatLab Engine’s variable z, pull it To extract the MatLab Engine’s variable z, pull it

into C++ as a into C++ as a mxArraymxArray matrix, then extract the matrix, then extract the bundled value out of that bundled value out of that mxArraymxArray and into a C+ and into a C++ variable+ variable

double *cresult;double *cresult;mxArray *mresult;mxArray *mresult;mresult = engGetVariable(m_pEngine,"z");mresult = engGetVariable(m_pEngine,"z");cresult = mxGetPr(mresult);cresult = mxGetPr(mresult);cout << cresult[0];cout << cresult[0];

mxGetPrmxGetPr returns a pointer to a copy of the returns a pointer to a copy of the doubledouble value z stored in the MatLab Enginevalue z stored in the MatLab Engine

Warning: Unpredictable fatal errors occur if the Warning: Unpredictable fatal errors occur if the data type in MatLab doesn’t closely resemble the data type in MatLab doesn’t closely resemble the data type in C++ eg. Copying a 3x1 vector into a data type in C++ eg. Copying a 3x1 vector into a scalarscalar

Page 16: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Passing Arrays & MatricesPassing Arrays & Matrices

To pass arrays (vector), adjust the size parameters To pass arrays (vector), adjust the size parameters of the memory allocation and copy routine to match of the memory allocation and copy routine to match the dimensions of the array being passedthe dimensions of the array being passed

Pass a vector a of dimensions: 1 x SIZEPass a vector a of dimensions: 1 x SIZE

double a[double a[SIZESIZE];];mxArray *A;mxArray *A;// assume a gets initialized, all values// assume a gets initialized, all valuesA=mxCreateDoubleMatrix(1, A=mxCreateDoubleMatrix(1, SIZESIZE, mxREAL);, mxREAL);memcpy((void *)mxGetPr(A), (void *)a, memcpy((void *)mxGetPr(A), (void *)a, sizeof(double)*sizeof(double)*SIZESIZE););engPutVariable(m_pEngine, "a", A);engPutVariable(m_pEngine, "a", A);

Copies entire C++ array a into the MatLab Engine’s Copies entire C++ array a into the MatLab Engine’s aa

Page 17: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Passing Arrays & Matrices Passing Arrays & Matrices (cont)(cont)

Pass a matrix of dimensions: SIZE x SIZEPass a matrix of dimensions: SIZE x SIZE

double c[double c[SIZESIZE][][SIZESIZE];];// assume c gets initialized, all of it // assume c gets initialized, all of it mxArray *mxc;mxArray *mxc;mxc = mxCreateDoubleMatrix(mxc = mxCreateDoubleMatrix(SIZESIZE, , SIZESIZE, mxREAL);, mxREAL);memcpy((void *) mxGetPr(mxc), (void *)c, memcpy((void *) mxGetPr(mxc), (void *)c, sizeof(double)*sizeof(double)*SIZE*SIZESIZE*SIZE););engPutVariable(m_pEngine, "c", mxc);engPutVariable(m_pEngine, "c", mxc);engEvalString(m_pEngine, "c = c';");engEvalString(m_pEngine, "c = c';");

Note: C++ has row-major storage, and MatLab Note: C++ has row-major storage, and MatLab has column-major storage. Thus a matrix being has column-major storage. Thus a matrix being exchanged must be transposed, either before or exchanged must be transposed, either before or after the exchange, to maintain the matrix’s after the exchange, to maintain the matrix’s semanticssemantics

Page 18: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

See the Demos ProgramSee the Demos Program

Demonstrates all of these features so Demonstrates all of these features so far in Microsoft Visual Development far in Microsoft Visual Development Studio C++ v.6.0Studio C++ v.6.0

Demonstrates graph plots, invoking Demonstrates graph plots, invoking commands, input, output, and commands, input, output, and passing vectors and matrices.passing vectors and matrices.

Page 19: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Internet ReferencesInternet References

Welcome to Zhenwang's Homepage (Q&A)Welcome to Zhenwang's Homepage (Q&A) http://www.sfu.ca/~zyao/teaching/ensc488faq.htmhttp://www.sfu.ca/~zyao/teaching/ensc488faq.htm

A Tutorial to Call MATLAB Functions from Within A Tutorial to Call MATLAB Functions from Within A  C/C++ ProgramA  C/C++ Program

http://prism.mem.drexel.edu/Shah/public_html/c2matlab.htmhttp://prism.mem.drexel.edu/Shah/public_html/c2matlab.htm

Microsoft Visual Studio C++ & Interfacing Matlab with C/C++, Java

http://www.qcf.gatech.edu/academic/LabDataAccess/C+http://www.qcf.gatech.edu/academic/LabDataAccess/C++IntroductionMatLab.Interfacings.doc+IntroductionMatLab.Interfacings.doc

MatLab – The Language of Technical Computing, MatLab – The Language of Technical Computing, External InterfacesExternal Interfaces

http://www.mathworks.com.au/access/helpdesk/help/pdf_doc/matlab/http://www.mathworks.com.au/access/helpdesk/help/pdf_doc/matlab/apiext.pdfapiext.pdf

Page 20: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Questions? …Questions? …

Page 21: MatLab API in C++ Christopher Dabney. Purpose MatLab … MatLab … is an interpreted scripting language is an interpreted scripting language conversion to.

Thank YouThank You

No MatLab matrices were harmed in the making of this presentation.