I am trying to follow the example from: https://www.mathworks.com/help/matlab/calling-matlab-engine-from-cpp-programs.html to call MATLAB code from a C++ application I have built in Visual Studio.
I've made some modifications to the example. I am using an h and cpp file as well as using cmake for the build.
I have testFeval.h
#include "MatlabEngine.hpp"#include "MatlabDataArray.hpp"#include <iostream>void callSQRT();
testFeval.cpp
#include "testFeval.h"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; }}
I am using CMake to try and run the MATLAB engine from Visual Studio.
My top level CMake file is:
# CMakeList.txt : Top-level CMake project file, do global configuration# and include sub-projects here.#cmake_minimum_required (VERSION 3.8)project ("CMakeProject1" C CXX)# Find MatlabFIND_PACKAGE(Matlab REQUIRED)# Include sub-projects.INCLUDE_DIRECTORIES("${Matlab_ROOT_DIR}/extern/include")add_subdirectory ("src") #Main Project
The project CMake is:
cmake_minimum_required (VERSION 3.8)# Add source to this project's executable.set(HDR MATLABExampleCall/testFeval.h CMakeProject1.h) #List all header files. This way project is rebuilt if a header file is modified.set(SRC MATLABExampleCall/testFeval.cpp CMakeProject1.cpp) #List all source filesadd_executable (CMakeProject1 ${SRC} ${HDR}) #Executable uses all source and header files
I'm not sure what I'm doing wrong with my structure/usage of the MATLAB Engine? I am able to include hpp files, yet I'm getting Linker errors when I try to build. Is there something I'm missing? Ideally when this is working I want to use the same engine to instantiate MATLAB objects and call their methods.
Best Answer