Main Content

Execute MATLAB Statements from MEX Function

MEX functions can execute MATLAB® statements in the calling function workspace. Evaluating statements in the workspace of the calling function enables MEX functions to create or modify variables in the workspace in which it executes. MEX functions can also modify the environment, for instance by changing the current folder.

The MATLAB statements can access any variables that are in scope in the calling function workspace. If the MEX function is called from the MATLAB base workspace, then the statements are evaluated in the context of that workspace.

To execute MATLAB statements from a MEX function, use the matlab::engine::MATLABEngine::eval function. Use eval when you do not need to pass arguments to a MATLAB function or return arguments to the MEX function.

Pass the MATLAB statement to eval as an std::u16string. Use the u"..." UTF-16 literal string encoding or the utility function matlab::engine::convertUTF8StringToUTF16String to convert an std::string to an std::u16string. The functions and input arguments named in the string must exist in the caller's workspace.

This code snippet shows how to use eval to execute MATLAB statements. These statements add the current folder to the MATLAB path and then change the MATLAB working folder to the one mapped to drive H on a Windows system. Note the escape ("\") character in front of the backslash character.

std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
matlabPtr->eval(u"currentFolder = pwd;");

Here is the equivalent MATLAB code.

currentFolder = pwd;

See Also

| | |

Related Topics