matlab engine giving wrong result when called in a function in Cpp file
Show older comments
matlab engine call inside function: i try to sort an array of numbers & write the result to a file(using dlmwrite). also i display them on the screen. * when i sort { 0, 5, 2, 7, 3, 9, 1, 6, 8, 4 } i get an array of ten zeros(both at std::cout & using dlmwrite)*
my code for the function:
int call_matlab_processing(double double_array[], int size_double_array)
{
// its just a sorting algo, sorting being implemented by matlab
double * sorted;
Engine *ep;
mxArray *T = NULL, *result = NULL;
if (!(ep = engOpen(""))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return 1;
}
T = mxCreateDoubleMatrix(1,size_double_array, mxREAL);
memcpy((void *)mxGetPr(T), (void *)double_array, sizeof(double_array));
engPutVariable(ep, "T", T);
engEvalString(ep, "[D] = sort(T,'descend')");
engEvalString(ep, "dlmwrite('myFile.txt',D)"); * * *// writes 0 0 0 ... 0 to file***
result = engGetVariable(ep,"D");
sorted=(double *)mxGetData(result);
* *// i try to print the contents of the sorted array, but it gives 0 0 0 ...0**
for(int i = 0; i < size_double_array;i++)
{
std::cout<< "double_array at "<< i<< "="<< *sorted<< std::endl;
sorted++;
}
mxDestroyArray(T);
mxDestroyArray(result);
engEvalString(ep, "close;");
engClose(ep);
return 0;
}
Accepted Answer
More Answers (1)
Titus Edelhofer
on 18 Nov 2015
Hi,
first of all, your memcpy copies just 4 or 8 bytes but not the array:
memcpy((void *)mxGetPr(T), (void *)double_array, sizeof(double_array));
You need to replace by
memcpy((void *)mxGetPr(T), (void *)double_array, size_double_array * sizeof(double));
And for the result you would need to do:
double *sorted;
sorted = mxGetPr(result);
for (int i=0; i<size_double_array; i++) {
std::cout << sorted[i] << endl;
}
Titus
2 Comments
James Tursa
on 18 Nov 2015
He is printing out *sorted and doing sorted++ inside the loop, so he should get the same result as sorted[i].
Titus Edelhofer
on 18 Nov 2015
James, you are of course right...
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!