Sending a matrix with each iteration: Matlab "engine.h" c++

1.1k views Asked by At

This question comes after solving the problem I got in this question. I have a c++ code that processes frames from a camera and generates a matrix for each processed frame. I want to send to matlab engine each matrix, so at the end of the execution I have in stored all the matrices. I am conffused about how to do this, I send a matrix in each iteration but it is overwritting it all the time, so at the end I only have one. Here is a code example:

matrix.cpp

#include helper.h

mxArray *mat;   
mat = mxCreateDoubleMatrix(13, 13, mxREAL);     
memcpy(mxGetPr(mat),matrix.data, 13*13*sizeof(double));
engPutVariable(engine, "mat", mat);

I also tried to use a counter to dinamically name the different matrices, but it didn't work as matlab engine requires the variables to be defined first. Any help will be appreciated. Thanks.

3

There are 3 answers

2
Jonathan On BEST ANSWER

If you don't know the number of frames a priori, don't try to expand the mxArray in C. It is not convenient. You were already close to start. All your problems can be solved with:

engEvalString(engine, "your command here")

Read more here.

The simplest approach is something like:

engPutVariable(engine, "mat", mat);
engEvalString("frames{length(frames)+1} = mat;");

Don't do it exactly that, it is an illustration and will be very slow. Much better to preallocate, say 1000 frames then expand it another 1000 (or a more appropriate number) when needed. Even better is to not use cell arrays which are slow. Instead you could use a 3D array, such as:

frames = zeros(13,13,1000);
frames(:,:,i) = mat;
i = i + 1;

Again, preallocate in blocks. You get the idea. If you really need to be fast, you could build the 3D arrays in C and ship them to MATLAB when they fill.

1
Oli On

Maybe you can use vector<mxArray> from stdlib.

3
Philipp On

You can create a cell array in matlab workspace like this:

    mwSize size = 10;
    mxArray* cell = mxCreateCellArray(1, &size);

    for(size_t i=0;i<10;i++)
    {
        mxArray *mat;   
        mat = mxCreateDoubleMatrix(13, 13, mxREAL);     
        memcpy(mxGetPr(mat),matrix.data, 13*13*sizeof(double));

        mwIndex subscript = i;
        int index = mxCalcSingleSubscript(cell , 1,&subscript); 
        mxSetCell(m_cell , index, mat);
   }

   engPutVariable(engine, "myCell", cell);