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

烂漫一生 提交于 2019-12-06 05:03:06

问题


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.


回答1:


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.




回答2:


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);



回答3:


Maybe you can use vector<mxArray> from stdlib.



来源:https://stackoverflow.com/questions/8847504/sending-a-matrix-with-each-iteration-matlab-engine-h-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!