To test your installation and environment, save the following C++ code in a file named testFeval.cpp (you can use any name). To build the engine application, use these commands from your command window:
mex -setup -client engine C++
Select the installed compiler you want to use when prompted by the mex setup script. Then call the mex command to build your program. Ensure that the MATLAB® Engine API for C++ supports the compiler you select. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers website.
mex -v -client engine testFeval.cpp
The mex command saves the executable file in the same folder.
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void callSQRT() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
//Create MATLAB data array factory
matlab::data::ArrayFactory factory;
// Define a four-element typed array
matlab::data::TypedArray<double> const argArray =
factory.createArray({ 1,4 }, { -2.0, 2.0, 6.0, 8.0 });
// Call MATLAB sqrt function on the data array
matlab::data::Array const results = matlabPtr->feval(u"sqrt", argArray);
// Display results
for (int i = 0; i < results.getNumberOfElements(); i++) {
double a = argArray[i];
std::complex<double> v = results[i];
double realPart = v.real();
double imgPart = v.imag();
std::cout << "Square root of " << a << " is " <<
realPart << " + " << imgPart << "i" << std::endl;
}
}
int main() {
callSQRT();
return 0;
}Here is the output from this program. In this case, MATLAB returns a complex array because one of the numbers in the data array is negative.
Square root of -2 is 0 + 1.41421i Square root of 2 is 1.41421 + 0i Square root of 6 is 2.44949 + 0i Square root of 8 is 2.82843 + 0i
matlab::engine::MATLABEngine | mex