Reputation: 303
I'm trying to pass a variable z = 100
from C++ to Matlab for further processing (this is just a very simplified example). I basically want this to be passed as a global variable such that I can access this variable from any Matlab function, (perhaps sent to the Matlab Workspace).
Here is my C++ code (I'm using the Matlab engine from within C++):
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <math.h>
#include <fstream>
#include <stdio.h>
#include <Windows.h>
#include "engine.h"
#include <engine.h>
//#include <cmath>
#define _USE_MATH_DEFINES
#pragma comment ( lib, "libmat.lib" )
#pragma comment ( lib, "libmx.lib" )
#pragma comment ( lib, "libmex.lib" )
#pragma comment ( lib, "libeng.lib" )
using namespace cv;
using namespace std;
int main (int argc, char* argv[])
{
Engine *ep = engOpen(NULL);
int z;
mxArray *z_array = mxCreateDoubleMatrix(1,1,mxREAL);
double *pz = mxGetPr(z_array);
z = 100;
engPutVariable(ep, "z", z_array);
engClose(ep);
return 0;
}
When this code has finished executing, I open Matlab and try to access the variable z
but it doesn't exist. Is there something I'm missing here? (I've also tried inserted engEvalString(ep, "global z; disp(z);");
after engPutVariable
but this doesn't help.
I'd appreciate any insight you might be able to give me. Thanks!
Upvotes: 0
Views: 932
Reputation: 1110
Your code looks good to me. By writng engClose(ep); you close the Matlab Engine so the variable z will disappear with the Matlab session.
EDIT : By reviewing your code, I noticed that z has not been affected to z_array. So try the following code
mxArray *z_array = NULL;
double z[1] = {100};
z_array = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy((char *) mxGetPr(z_array), (char*) z, sizeof(double));
engPutVariable(ep, "z", z_array);
mxDestroyArray(z_array);
Upvotes: 1