Engine (C)
Type for MATLAB engine
Description
Engine is a handle to a MATLAB® engine object. Engine is a C language opaque
type.
You can call MATLAB as a computational engine by writing C programs that use the MATLAB engine library. Engine is the link between your program
and the separate MATLAB engine process.
The header file containing this type is:
#include "engine.h"
Note
matlab::engine::MATLABEngine in the
MATLAB Engine API for C++ is recommended over Engine. The
MATLAB Engine API for C++ includes modern C++ features for writing engine
applications. For more information, see Call MATLAB from C++. There
are no plans to remove Engine or the Engine API for C.
Examples
Start MATLAB Engine from C on Windows
This C code shows how to start a MATLAB process on the current host from a C MATLAB function on a Windows® system.
/*
* engwindemo.c
*
* This program illustrates how to call MATLAB
* Engine functions from a C program on Windows.
*
* Copyright 1984-2017 The MathWorks, Inc.
*/
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#include <matrix.h>
#define BUFSIZE 256
static double Areal[6] = { 1, 2, 3, 4, 5, 6 };
int PASCAL WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow)
{
Engine *ep;
mxArray *T = NULL, *a = NULL, *d = NULL;
char buffer[BUFSIZE+1];
double *Dreal, *Dimag;
double time[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
/*
* Start MATLAB engine
*/
if (!(ep = engOpen(NULL))) {
MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine",
(LPSTR) "Engwindemo.c", MB_OK);
exit(-1);
}
/*
* PART I
*
* For the first half of this demonstration, we will send data
* to MATLAB, analyze the data, and plot the result.
*/
/*
* Create a variable from our data
*/
T = mxCreateDoubleMatrix(1, 10, mxREAL);
/*
* Copy data from time to matrix T
*/
#if MX_HAS_INTERLEAVED_COMPLEX
memcpy(mxGetDoubles(T), time, 10*sizeof(double));
#else
memcpy(mxGetPr(T), time, 10*sizeof(double));
#endif
/*
* Place the variable T into the MATLAB workspace
*/
engPutVariable(ep, "T", T);
/*
* Evaluate a function of time, distance = (1/2)g.*t.^2
* (g is the acceleration due to gravity)
*/
engEvalString(ep, "D = .5.*(-9.8).*T.^2;");
/*
* Plot the result
*/
engEvalString(ep, "plot(T,D);");
engEvalString(ep, "title('Position vs. Time for a falling object');");
engEvalString(ep, "xlabel('Time (seconds)');");
engEvalString(ep, "ylabel('Position (meters)');");
/*
* PART II
*
* Create another mxArray, put it into MATLAB,
* and calculate its eigen values.
*
*/
a = mxCreateDoubleMatrix(3, 2, mxREAL);
/*
* Copy data from Areal to matrix a
*/
#if MX_HAS_INTERLEAVED_COMPLEX
memcpy(mxGetDoubles(a), Areal, 6*sizeof(double));
#else
memcpy(mxGetPr(a), Areal, 6*sizeof(double));
#endif
engPutVariable(ep, "A", a);
/*
* Calculate the eigen value
*/
engEvalString(ep, "d = eig(A*A')");
/*
* Use engOutputBuffer to capture MATLAB output. Ensure first that
* the buffer is always NULL terminated.
*/
buffer[BUFSIZE] = '\0';
engOutputBuffer(ep, buffer, BUFSIZE);
/*
* the evaluate string returns the result into the
* output buffer.
*/
engEvalString(ep, "whos");
MessageBox ((HWND)NULL, (LPSTR)buffer, (LPSTR) "MATLAB - whos", MB_OK);
/*
* Get the eigen value mxArray
*/
d = engGetVariable(ep, "d");
engClose(ep);
if (d == NULL) {
MessageBox ((HWND)NULL, (LPSTR)"Get Array Failed", (LPSTR)"Engwindemo.c", MB_OK);
}
else {
/*
* Using interleaved complex representation we can access complex number
* with a single pointer instead of using two separate pointers.
*/
#if MX_HAS_INTERLEAVED_COMPLEX
if (mxIsComplex(d)) {
sprintf(buffer,"Eigenval 2: %g+%gi",mxGetComplexDoubles(d)[1].real,mxGetComplexDoubles(d)[1].imag);
}
else {
sprintf(buffer,"Eigenval 2: %g",mxGetDoubles(d)[1]);
}
#else
Dreal = mxGetPr(d);
Dimag = mxGetPi(d);
if (Dimag) {
sprintf(buffer,"Eigenval 2: %g+%gi",Dreal[1],Dimag[1]);
}
else {
sprintf(buffer,"Eigenval 2: %g",Dreal[1]);
}
#endif
MessageBox ((HWND)NULL, (LPSTR)buffer, (LPSTR)"Engwindemo.c", MB_OK);
mxDestroyArray(d);
}
/*
* We're done! Free memory, close MATLAB engine and exit.
*/
mxDestroyArray(T);
mxDestroyArray(a);
return(0);
}
/* LocalWords: eigen eng Eigenval gi
*/
Start MATLAB Engine from C on Linux or macOS
This C code shows how to start a MATLAB process on the current host from a C MATLAB function on a Linux® or macOS system.
/*
* engdemo.c
*
* A simple program to illustrate how to call MATLAB
* Engine functions from a C program.
*
* Copyright 1984-2016 The MathWorks, Inc.
* All rights reserved
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define BUFSIZE 256
int main()
{
Engine *ep;
mxArray *T = NULL, *result = NULL;
char buffer[BUFSIZE+1];
double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };
/*
* Call engOpen with a NULL string. This starts a MATLAB process
* on the current host using the command "matlab".
*/
if (!(ep = engOpen(""))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
/*
* PART I
*
* For the first half of this demonstration, send data
* to MATLAB, analyze the data, and plot the result.
*/
/*
* Create a variable for the data
*/
T = mxCreateDoubleMatrix(1, 10, mxREAL);
memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
/*
* Place the variable T into the MATLAB workspace
*/
engPutVariable(ep, "T", T);
/*
* Evaluate a function of time, distance = (1/2)g.*t.^2
* (g is the acceleration due to gravity)
*/
engEvalString(ep, "D = .5.*(-9.8).*T.^2;");
/*
* Plot the result
*/
engEvalString(ep, "plot(T,D);");
engEvalString(ep, "title('Position vs. Time for a falling object');");
engEvalString(ep, "xlabel('Time (seconds)');");
engEvalString(ep, "ylabel('Position (meters)');");
/*
* use fgetc() to pause long enough to be
* able to see the plot
*/
printf("Hit return to continue\n\n");
fgetc(stdin);
/*
* We're done for Part I! Free memory, close MATLAB figure.
*/
printf("Done for Part I.\n");
mxDestroyArray(T);
engEvalString(ep, "close;");
/*
* PART II
*
* For the second half of this demonstration, we will request
* a MATLAB string, which should define a variable X. MATLAB
* will evaluate the string and create the variable. We
* will then recover the variable, and determine its type.
*/
/*
* Use engOutputBuffer to capture MATLAB output, so we can
* echo it back. Ensure first that the buffer is always NULL
* terminated.
*/
buffer[BUFSIZE] = '\0';
engOutputBuffer(ep, buffer, BUFSIZE);
while (result == NULL) {
char str[BUFSIZE+1];
char *input = NULL;
/*
* Get a string input from the user
*/
printf("Enter a MATLAB command to evaluate. This command should\n");
printf("create a variable X. This program will then determine\n");
printf("what kind of variable you created.\n");
printf("For example: X = 1:5\n");
printf(">> ");
input = fgets(str, BUFSIZE, stdin);
/*
* Evaluate input with engEvalString
*/
engEvalString(ep, str);
/*
* Echo the output from the command.
*/
printf("%s", buffer);
/*
* Get result of computation
*/
printf("\nRetrieving X...\n");
if ((result = engGetVariable(ep,"X")) == NULL)
printf("Oops! You didn't create a variable X.\n\n");
else {
printf("X is class %s\t\n", mxGetClassName(result));
}
}
/*
* We're done! Free memory, close MATLAB engine and exit.
*/
printf("Done!\n");
mxDestroyArray(result);
engClose(ep);
return EXIT_SUCCESS;
}
Call MATLAB Engine Functions from Fortran
This code shows how to call MATLAB engine functions from a Fortran program.
#include "fintrf.h"
C
#if 0
C
C fengdemo.F
C .F file need to be preprocessed to generate .for equivalent
C
#endif
C
C fengdemo.f
C
C This is a simple program that illustrates how to call the MATLAB
C Engine functions from a FORTRAN program.
C
C Copyright 1984-2018 The MathWorks, Inc.
C======================================================================
C
program main
C Declarations
implicit none
mwPointer engOpen, engGetVariable, mxCreateDoubleMatrix
#if MX_HAS_INTERLEAVED_COMPLEX
mwPointer mxGetDoubles
#else
mwPointer mxGetPr
#endif
mwPointer ep, T, D
double precision time(10), dist(10)
integer engPutVariable, engEvalString, engClose
integer temp, status
mwSize i
data time / 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 /
mwSize M, N
parameter(M=1)
parameter(N=10)
C
ep = engOpen('matlab ')
C
if (ep .eq. 0) then
write(6,*) 'Can''t start MATLAB engine'
stop
endif
C
T = mxCreateDoubleMatrix(M, N, 0)
#if MX_HAS_INTERLEAVED_COMPLEX
call mxCopyReal8ToPtr(time, mxGetDoubles(T), N)
#else
call mxCopyReal8ToPtr(time, mxGetPr(T), N)
#endif
C
C
C Place the variable T into the MATLAB workspace
C
status = engPutVariable(ep, 'T', T)
C
if (status .ne. 0) then
write(6,*) 'engPutVariable failed'
stop
endif
C
C
C Evaluate a function of time, distance = (1/2)g.*t.^2
C (g is the acceleration due to gravity)
C
if (engEvalString(ep, 'D = .5.*(-9.8).*T.^2;') .ne. 0) then
write(6,*) 'engEvalString failed'
stop
endif
C
C
C Plot the result
C
if (engEvalString(ep, 'plot(T,D);') .ne. 0) then
write(6,*) 'engEvalString failed'
stop
endif
if (engEvalString(ep, 'title(''Position vs. Time'')') .ne. 0) then
write(6,*) 'engEvalString failed'
stop
endif
if (engEvalString(ep, 'xlabel(''Time (seconds)'')') .ne. 0) then
write(6,*) 'engEvalString failed'
stop
endif
if (engEvalString(ep, 'ylabel(''Position (meters)'')') .ne. 0)then
write(6,*) 'engEvalString failed'
stop
endif
C
C
C read from console to make sure that we pause long enough to be
C able to see the plot
C
print *, 'Type 0 <return> to Exit'
print *, 'Type 1 <return> to continue'
read(*,*) temp
C
if (temp.eq.0) then
print *, 'EXIT!'
status = engClose(ep)
if (status .ne. 0) then
write(6,*) 'engClose failed'
endif
stop
end if
C
if (engEvalString(ep, 'close;') .ne. 0) then
write(6,*) 'engEvalString failed'
stop
endif
C
D = engGetVariable(ep, 'D')
#if MX_HAS_INTERLEAVED_COMPLEX
call mxCopyPtrToReal8(mxGetDoubles(D), dist, N)
#else
call mxCopyPtrToReal8(mxGetPr(D), dist, N)
#endif
print *, 'MATLAB computed the following distances:'
print *, ' time(s) distance(m)'
do 10 i=1,10
print 20, time(i), dist(i)
20 format(' ', G10.3, G10.3)
10 continue
C
C
call mxDestroyArray(T)
call mxDestroyArray(D)
status = engClose(ep)
C
if (status .ne. 0) then
write(6,*) 'engClose failed'
stop
endif
C
stop
end
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
