How to output a 2D integer array using Matlab mex?

7 ビュー (過去 30 日間)
Aaronne
Aaronne 2014 年 2 月 14 日
回答済み: Aaronne 2014 年 2 月 15 日
I got a follow up question about Matlab mex function input/output 2D array format. For example, I have a variable '`outputBuff`' defined as C++ 2D integer array. After processing it, I want to output it as a 'plhs' (parameter at left hand side). Not sure how to do this.
int** outputBuff;
size_t col_outputBuff = mxGetN(prhs[4]);
size_t row_outputBuff = mxGetM(prhs[4]);
// Allocate the memory for 2D array
outputBuff = (int **)mxCalloc(col_outputBuff, sizeof(int*));
for(int x = 0; x < col_outputBuff; x++) {
outputBuff[x] = (int *) mxCalloc(row_outputBuff, sizeof(int));
}
// Read in the data
for (int col=0; col < col_outputBuff; col++) {
for (int row=0; row < row_outputBuff; row++) {
outputBuff[col][row] = ((int *)mxGetPr(prhs[4]))[row+col*row_outputBuff];
}
}
Then output it as `plhs`
const mwSize dims[] = {col_outputBuff, row_outputBuff};
plhs[0] = mxCreateNumericArray(2, dims, mxINT32_CLASS, mxREAL);
mxArray *outputMatrix;
outputMatrix = mxCreateNumericMatrix(col_outputBuff, row_outputBuff, mxINT32_CLASS, mxREAL);
outputBuff[0] = (int *)mxGetPr(outputMatrix);
outputMatrix = (mxArray *)mxGetData(plhs[0]);
The codes can be compiled but output all zeros not as expected. Could you give me some hints? Thanks a lot.

採用された回答

Aaronne
Aaronne 2014 年 2 月 15 日
I got the answer with the help from someone. I put it here for others' reference.
// Output the results
plhs[0] = mxCreateNumericMatrix(col_outputBuff, row_outputBuff, mxINT32_CLASS, mxREAL);
int* outputMatrix = (int *)mxGetData(plhs[0]);
// Read in the data
for (int col=0; col < col_outputBuff; col++) {
for (int row=0; row < row_outputBuff; row++) {
outputMatrix[row + col*row_outputBuff] = outputBuff[col][row];
}
}

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWrite C Functions Callable from MATLAB (MEX Files) についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by