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

This question arises after solving the problem I received in this question . I have C ++ code that processes frames from a camera and generates a matrix for each processed frame. I want to send each matrix to the Matlab matrix, so at the end of the execution I saved all the matrices. I understand how to do this, I send a matrix at each iteration, but it overwrites it all the time, so in the end I have it. Here is a sample code:

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 using a counter to dynamically name different matrices, but it did not work, as the matlab engine requires variables to be defined first. Any help would be appreciated. Thanks.

+4
source share
3 answers

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

 engEvalString(engine, "your command here") 

More details here .

The simplest approach is something like:

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

Not doing it this way is an illustration and will be very slow. It is much better to preset, say, 1000 frames, and then expand it with another 1000 (or a more suitable number), when necessary. Even better, don't use arrays of cells that are slow. Instead, you can use a 3D array, for example:

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

Again, pre-select in blocks. You get the idea. If you really need to be fast, you can build 3D arrays in C and send them to MATLAB when they are full.

+4
source

You can create an array of cells in the Matlab workspace as follows:

  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); 
+5
source

Perhaps you can use vector<mxArray> from stdlib.

+3
source

Source: https://habr.com/ru/post/1390786/


All Articles