Pass a 2d array from c++ to MATLAB and back
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!