Pass a 2d array from c++ to MATLAB and back

조회 수: 5 (최근 30일)
maxwell0312
maxwell0312 2017년 5월 5일
I am trying to pass a 2D array, created in C++ of type int, to MATLAB and back using the included "engine.h" header. So far, I have been looking at different solutions around and none of them worked. I followed this one: https://www.mathworks.com/matlabcentral/newsreader/view_thread/309933 and am still unable to pass the 2D array.
Here is my code:
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "engine.h"
#include "matrix.h"
int main(){
//C++
int numRows = 3;
int numCols = 2;
int M[numRows][numCols] = {{1,2},{4,5},{6,7}};
//MATLAB
Engine *ep;
mxArray *T = NULL;
void *result = NULL;
int *ans = NULL;
T = mxCreateNumericMatrix(numCols, numRows, mxINT32_CLASS, mxREAL);
if (T == NULL){
printf("Something is wrong with T.\n");
return 1;
}
memcpy(mxGetData(T),M,sizeof(M));
engPutVariable(ep,"T",T);
engEvalString(ep,"T=T';"); //gives the tranpose matrix
//Get T back from MATLAB
//test Matlab array
result = engGetVariable(ep,"T");
mwSize nRow= mxGetM(result);
mwSize nCol = mxGetN(result);
ans = mxGetData(result);
for (int j = 0; j<nCol; j++){
for (int i = 0; i<nRow; i++){
printf("%i\t",ans[nCol*i+j]);
}
printf("\n");
}
//engEvalString(ep,"f = plot(T);");
mxDestroyArray(T);
mxDestroyArray(result);
engClose(ep);
return 0;
}
The error that I got is: invalid conversion from ‘void*’ to ‘mxArray* {aka mxArray_tag*}’ [-fpermissive] mxDestroyArray(result). Actually, most of the errors seem to originate around this block of codes here:
result = engGetVariable(ep,"T");
mwSize nRow= mxGetM(result);
mwSize nCol = mxGetN(result);
ans = mxGetData(result);
I tried to do: mxArray *result. This doesn't help. Please let me know what can I do, and any help would be extremely appreciated.
Thanks.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by