Main Content

matlab::engine::MATLABEngine

EvaluateMATLABfunctions from C++ program

Description

Thematlab::engine::MATLABEngineclass uses a MATLAB®process as a computational engine for C++. This class provides an interface between the C++ language and MATLAB, enabling you to evaluate MATLAB functions and expressions from C++ programs.

Class Details

Namespace:

matlab::engine
Include: MatlabEngine.hpp

Factory Methods

Thematlab::engine::MATLABEngineclass provides methods to start MATLAB and to connect to a shared MATLAB session synchronously or asynchronously.

Unsupported Startup Options

The engine does not support these MATLAB startup options:

  • -h

  • -help

  • -?

  • -n

  • -e

  • -softwareopengl

  • -logfile

For information on MATLAB startup options, seeCommonly Used Startup Options. For an example of how to use MATLAB startup options when starting engine applications, seeStart MATLAB with Startup Options.

Method Summary

Member Functions

feval

Evaluate MATLAB function with arguments synchronously

fevalAsync

Evaluate MATLAB function with arguments asynchronously

eval

评估MATLAB语句作为一个字符串synchronously

evalAsync

Evaluate MATLAB statement as a string asynchronously

getVariable

Get variable from the MATLAB base workspace synchronously

getVariableAsync

Get variable from the MATLAB base workspace asynchronously

setVariable

Put variable into the MATLAB base workspace synchronously

setVariableAsync

Put variable into the MATLAB base workspace asynchronously

getProperty

Get object property value

getPropertyAsync

Get object property value asynchronously

setProperty

Set object property value

setPropertyAsync

Set object property value asynchronously

Member Function Details

feval

std::vector feval(const matlab::engine::String &function, const size_t numReturned, const std::vector &args, const std::shared_ptr &output = std::shared_ptr(), const std::shared_ptr &error = std::shared_ptr())
matlab::data::Array feval(const matlab::engine::String &function, const std::vector &args, const std::shared_ptr &output = std::shared_ptr(), const std::shared_ptr &error = std::shared_ptr())
matlab::data::Array feval(const matlab::engine::String &function, const matlab::data::Array &arg, const std::shared_ptr &output = std::shared_ptr(), const std::shared_ptr &error = std::shared_ptr())
ResultType feval(const matlab::engine::String &function, const std::shared_ptr &output, const std::shared_ptr &error, RhsArgs&&... rhsArgs )
ResultType feval(const matlab::engine::String &function, RhsArgs&&... rhsArgs)
Description

评估与输入参数syn MATLAB函数chronously. Use feval when you want to pass arguments from C++ to MATLAB and when you want to return a result from MATLAB to C++.

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

Parameters

const matlab::engine::String &function

Name of the MATLAB function or script to evaluate. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const size_t numReturned

Number of returned values

const std::vector &args

Multiple input arguments to pass to the MATLAB function in anstd::vector. The vector is converted to a column array in MATLAB.

const matlab::data::Array arg

Single input argument to pass to the MATLAB function.

const std::shared_ptr &output = std::shared_ptr()

Stream buffer used to store the standard output from the MATLAB function.

const std::shared_ptr &error = std::shared_ptr()

Stream buffer used to store the error message from the MATLAB function.

RhsArgs&&... rhsArgs

Native C++ data types used for function inputs.fevalaccepts scalar inputs of these C++ data types:bool,int8_t,int16_t,int32_t,int64_t,uint8_t,uint16_t,uint32_t,uint64_t,float,double.

Return Value

std::vector

Outputs returned from MATLAB function.

matlab::data::Array

Single output returned from MATLAB function.

ResultType

Output returned from MATLAB function as a user-specified type. Can be anstd::tupleif returning multiple arguments.

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

matlab::engine::MATLABExecutionException

There is a MATLAB runtime error in the function.

matlab::engine::TypeConversionException

The result of a MATLAB function cannot be converted to the specified type.

matlab::engine::MATLABSyntaxException

There is a syntax error in the MATLAB function.

Examples

This example passes an array of numeric values to a MATLAB function. The code performs these steps:

  • Creates amatlab::data::Arraywith the dimensions 2-by-3 from a vector of numeric values of type double.

  • Starts a shared MATLAB session.

  • Passes the data array to the MATLABsqrtfunction and returns the result to C++.

#include "MatlabDataArray.hpp" #include "MatlabEngine.hpp" using namespace matlab::engine;
std::vector cppData{ 4, 8, 12, 16, 20, 24 }; // Create a 2-by-3 matlab data array matlab::data::ArrayFactory factory; auto inputArray = factory.createArray({ 2, 3 }, cppData.cbegin(), cppData.cend()); // Start MATLAB engine std::unique_ptr matlabPtr = startMATLAB(); // Pass data array to MATLAB sqrt function // And return results. auto result = matlabPtr->feval(u"sqrt", inputArray);

When callingfevalusing native C++ types, the input arguments are restricted to scalar values. For example, this code returns the square root of a scalar value.

#include "MatlabEngine.hpp" using namespace matlab::engine;
// Start MATLAB engine synchronously std::unique_ptr matlabPtr = startMATLAB(); // Call sqrt function double result = matlabPtr->feval(u"sqrt", double(27));

For functions that return multiple output arguments, you can use the MATLAB data API or, if using C++ types, anstd::tuple. For an example, seeCall Function with Native C++ Types.

fevalAsync

FutureResult> fevalAsync(const matlab::engine::String &function, const size_t numReturned, const std::vector &args, const std::shared_ptr &output = std::shared_ptr(), const std::shared_ptr &error = std::shared_ptr())
FutureResult < matlab::数据::数组> fevalAsync (constmatlab::engine::String &function, const std::vector &args, const std::shared_ptr &output = std::shared_ptr(), const std::shared_ptr &error = std::shared_ptr())
FutureResult < matlab::数据::数组> fevalAsync (constmatlab::engine::String &function, const matlab::data::Array &arg, const std::shared_ptr & output = std::shared_ptr(), const std::shared_ptr & error = std::shared_ptr())
FutureResult fevalAsync(const matlab::engine::String &function, const std::shared_ptr &output, const std::shared_ptr &error, RhsArgs&&... rhsArgs)
FutureResult fevalAsync(const matlab::engine::String &function, RhsArgs&&... rhsArgs)
Description

Evaluate MATLAB function with input arguments and returned values asynchronously.

Parameters

const matlab::engine::String &function

Name of the MATLAB function or script to evaluate. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const size_t numReturned

Number of returned values

const std::vector &args

Multiple input arguments to pass to the MATLAB function in anstd::vector. The vector is converted to a column array in MATLAB.

const matlab::data::Array arg

Single input argument to pass to the MATLAB function.

const std::shared_ptr &output = std::shared_ptr()

Stream buffer used to store the standard output from the MATLAB function.

const std::shared_ptr &error = std::shared_ptr()

Stream buffer used to store the error message from the MATLAB function.

RhsArgs&&... rhsArgs

Native C++ data types used for function inputs.fevalaccepts scalar inputs of these C++ data types:bool,int8_t,int16_t,int32_t,int64_t,uint8_t,uint16_t,uint32_t,uint64_t,float,double.

Return Value

FutureResult

AFutureResultobject used to get the result of calling the MATLAB function.

Exceptions

None

Examples

This example passes the scalar double 12.7 to the MATLABsqrtfunction asynchronously. TheFutureResultis then used to get the result.

#include "MatlabDataArray.hpp" #include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::ArrayFactory factory; matlab::data::Array argument = factory.createScalar(12.7); FutureResult future = matlabPtr->fevalAsync(u"sqrt", std::move(argument)); ... matlab::data::TypedArray result = future.get();

eval

void eval(const matlab::engine::String &statement, const std::shared_ptr &output = std::shared_ptr (), const std::shared_ptr &error = std::shared_ptr ())
Description

Evaluate a MATLAB statement as a string synchronously.

Parameters

const matlab::engine::String &statement

MATLAB statement to evaluate

const std::shared_ptr &output

Stream buffer used to store the standard output from the MATLAB statement.

const std::shared_ptr &error

Stream buffer used to store the error message from the MATLAB command.

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

matlab::engine::MATLABExecutionException

There is a runtime error in the MATLAB statement.

matlab::engine::MATLABSyntaxException

There is a syntax error in the MATLAB statement.

Examples

This example evaluates the following MATLAB statement.

a = sqrt(12.7);

The statement creates the variableain the MATLAB base workspace.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlabPtr->eval(u"a = sqrt(12.7);");

evalAsync

FutureResult evalAsync(const matlab::engine::String &str, const std::shared_ptr &output = std::shared_ptr (), const std::shared_ptr &error = std::shared_ptr ())
Description

Evaluate a MATLAB statement as a string asynchronously.

Parameters

const matlab::engine::String& str

MATLAB statement to evaluate

const std::shared_ptr & output

Stream buffer used to store the standard output from the MATLAB statement.

const std::shared_ptr & error

Stream buffer used to store the error message from the MATLAB command.

Return Value

FutureResult

AFutureResultobject used to wait for the completion of the MATLAB statement.

Exceptions

None

Examples

This example evaluates the following MATLAB statement asynchronously.

a = sqrt(12.7);

The statement creates the variableain the MATLAB base workspace.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); FutureResult future = matlabPtr->evalAsync(u"a = sqrt(12.7);");

getVariable

matlab::data::Array getVariable(const matlab::engine::String &varName, matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE)
Description

Get a variable from the MATLAB base or global workspace.

Parameters

const matlab::engine::String& varName

Name of a variable in the MATLAB workspace. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE

MATLAB workspace (BASE or GLOBAL) to get the variable from. For more information, seeglobal.

Return Value

matlab::data::Array

Variable obtained from the MATLAB base or global workspace

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

matlab::engine::MATLABExecutionException

The requested variable does not exist in the specified MATLAB base or global workspace.

Examples

This example gets a variable namedvarNamefrom the MATLAB base workspace.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::Array varName = matlabPtr->getVariable(u"varName");

getVariableAsync

FutureResult getVariableAsync(const matlab::engine::String &varName, matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE)
Description

Get a variable from the MATLAB base or global workspace asynchronously.

Parameters

const matlab::engine::String& varName

Name of the variable in MATLAB workspace. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE

MATLAB workspace (BASE or GLOBAL) to get the variable from. For more information, seeglobal.

Return Value

FutureResult

AFutureResultobject that you can use to get the variable obtained from the MATLAB workspace as amatlab.data.Array.

Exceptions

None

Examples

This example gets a variable namedvarNamefrom the MATLAB base workspace asynchronously.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); FutureResult future = matlabPtr->getVariableAsync(u"varName"); ... matlab::data::Array varName = future.get();

setVariable

void setVariable(const matlab::engine::String &varName, const matlab::data::Array &var, matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE)
Description

Put a variable into the MATLAB base or global workspace. If a variable with the same name exists in the MATLAB workspace,setVariableoverwrites it.

Parameters

const matlab::engine::String& varName

Name of the variable to create in the MATLAB workspace. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const matlab::data::Array var

Value of the variable to create in the MATLAB workspace

matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE

Put the variable in the MATLAB BASE or GLOBAL workspace. For more information, seeglobal.

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

Examples

This example puts the variable nameddatain the MATLAB base workspace.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::Array data = factory.createArray({ 1, 3 }, { 4, 8, 6 }); matlabPtr->setVariable(u"data", data);

setVariableAsync

FutureResult setVariableAsync(const matlab::engine::String &varName, const matlab::data::Array var, matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE)
Description

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

Parameters

const matlab::engine::String& varName

Name of the variable to create in the MATLAB workspace. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const matlab::data::Array var

Value of the variable to create in the MATLAB workspace

matlab::engine::WorkspaceType workspaceType = matlab::engine::WorkspaceType::BASE

Put the variable in the MATLAB BASE or GLOBAL workspace. For more information, seeglobal.

Exceptions

None

Example

This example puts the variable nameddatain the MATLAB base workspace.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::Array data = factory.createArray({ 1, 3 }, { 4., 8., 6. }); FutureResult future = matlabPtr->setVariableAsync(u"data", data);

getProperty

matlab::data::Array getProperty(const matlab::data::Array &objectArray, size_t index, const matlab::engine::String &propertyName)
matlab::data::Array getProperty(const matlab::data::Array &object, const matlab::engine::String &propertyName)
Description

Get the value of an object property. If the object input argument is an array of objects, specify the index of the array element that corresponds to the object whose property value you want to get.

Parameters

const matlab::data::Array &objectArray

Array of MATLAB objects

const matlab::data::Array &object

Scalar MATLAB object

size_t index

Zero-based index into the object array, specifying the object in that array whose property value is returned

const String &propertyName

Name of the property. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

Return Value

matlab::data::Array

Value of the named property

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

matlab::engine::MATLABExecutionException

The property does not exist.

Examples

This example evaluates a MATLAB statement in a try/catch block usingMATLABEngine::eval. TheMATLABEngine::getVariablemember function returns the exception object.MATLABEngine::getPropertyreturns the exceptionmessageproperty value as amatlab::data::CharArray.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlabPtr->eval(u"try; surf(4); catch me; end"); matlab::data::Array mException = matlabPtr->getVariable(u"me"); matlab::data::CharArray message = matlabPtr->getProperty(mException, u"message"); std::cout << "messages is: " << message.toAscii() << std::endl;

getPropertyAsync

FutureResult getPropertyAsync(const matlab::data::Array &objectArray, size_t index, const matlab::engine::String &propertyName)
FutureResult getPropertyAsync(const matlab::data::Array &object, const matlab::engine::String &propertyName)
Description

异步获取一个对象属性的值. If the object input argument is an array of objects, specify the index of the array element that corresponds to the object whose property value you want to get.

Parameters

const matlab::data::Array &objectArray

Array of MATLAB objects

const matlab::data::Array &object

Scalar MATLAB object

size_t index

Zero-based index into the object array, specifying the object in that array whose property value is returned

const matlab::engine::String &propertyName

Name of the property. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

Return Value

FutureResult

FutureResultobject that is used to synchronize the operation.

Exceptions

None

Examples

This example evaluates a MATLAB statement in a try/catch block usingMATLABEngine::eval. TheMATLABEngine::getVariablemember function returns the exception object.MATLABEngine::getPropertyAsync返回一个FutureResultthat you use to get the exceptionmessageproperty value as amatlab::data::CharArray.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlabPtr->eval(u"try;surf(4);catch me;end"); matlab::data::Array mException = matlabPtr->getVariable(u"me"); FutureResult future = matlabPtr->getPropertyAsync(mException, u"message"); matlab::data::CharArray message = future.get(); std::cout << "messages is: " << message.toAscii() << std::endl;

setProperty

void setProperty(matlab::data::Array &objectArray, size_t index, const matlab::engine::String &propertyName, const matlab::data::Array &propertyValue)
void setProperty(matlab::data::Array &object, const matlab::engine::String &propertyName, const matlab::data::Array &propertyValue)
Description

Set the value of an object property. If the object input argument is an array of objects, specify the index of the array element that corresponds to the object whose property value you want to set.

Parameters

matlab::data::Array &objectArray

Array of MATLAB objects

matlab::data::Array &object

Scalar MATLAB object

size_t index

Zero-based index into the object array, specifying the object in that array whose property value is set

const matlab::engine::String &propertyName

Name of the property to set. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const matlab::data::Array &propertyValue

Value assigned to the property

Exceptions

matlab::engine::MATLABNotAvailableException

The MATLAB session is not available.

matlab::engine::MATLABExecutionException

The property does not exist.

Examples

This example shows how to set a MATLAB object property. It creates a MATLAB graph and returns the line handle object. Setting the value of the lineLineStyleproperty to the character:changes the property value of the line object in MATLAB and updates the line style of the graph.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::ArrayFactory factory; matlab::data::Array yData = factory.createArray({ 1, 5 }, { 4.0, 11.0, 4.7, 36.2, 72.3 }); matlab::data::Array lineHandle = matlabPtr->feval(u"plot", yData); matlab::data::CharArray lineStyle = factory.createCharArray(":"); matlabPtr->setProperty(lineHandle, u"LineStyle", lineStyle);

setPropertyAsync

FutureResult setPropertyAsync(matlab::data::Array &objectArray, size_t index, const matlab::engine::String &propertyName, const matlab::data::Array &propertyValue)
FutureResult setPropertyAsync(matlab::data::Array &object, const matlab::engine::String &propertyName, const matlab::data::Array &propertyValue)
Description

Set the value of an object property asynchronously. If the object input argument is an array of objects, specify the index of the array element that corresponds to the object whose property value you want to set.

Parameters

matlab::data::Array &objectArray

Array of MATLAB objects

matlab::data::Array &object

Scalar MATLAB object

size_t index

Zero-based index into the object array, specifying the object in that array whose property value is set

const matlab::engine::String &propertyName

Name of the property to set. Specify the name as anstd::u16string. Also, you can specify this parameter as anstd::string.

const matlab::data::Array &propertyValue

Value assigned to the property.

Exceptions

None

Examples

This example shows how to set a MATLAB object property asynchronously. It creates a MATLAB graph and returns the line handle object. Setting the lineLineStyleproperty to the character:changes the property value of the object in MATLAB and updates the line style of the graph.

#include "MatlabEngine.hpp" using namespace matlab::engine;
std:: unique_ptr < MATLABEngine > matlabPtr = startMATLAB(); matlab::data::ArrayFactory factory; matlab::data::Array yData = factory.createArray({ 1, 5 }, { 4.0, 11.0, 4.7, 36.2, 72.3 }); matlab::data::Array lineHandle = matlabPtr->feval(u"plot", yData); matlab::data::CharArray lineStyle = factory.createCharArray(":"); FutureResult future = matlabPtr->setPropertyAsync(lineHandle, u"LineStyle", lineStyle);
Introduced in R2017b