How can I place a matrix of unsigned characters into a field in a MATLAB structure?

1 view (last 30 days)
How can I place a matrix of unsigned characters into a field in a MATLAB structure?
I am having difficulty in using a MEX-file to receive a 20-by-2 matrix of unsigned character values in C++ and transfer them to the same size matrix that is part of a structure in MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
To receive a matrix of unsigned characters into a field in a MATLAB structure, you can use our C API routines. These routines will copy the unsigned character matrix into the field of the MATLAB structure. The logical structure of an MATLAB structure is illustrated below:
mxArray *(structure) #created using mxCreateStructureMatrix
|
|
-- mxArray *(field1) #created using mxCreate#####
|
|
-- mxArray *(field2) #created using mxCreate#####
|
|
-- mxArray *(field3) #created using mxCreate#####
An unsigned char is equivalent to an unsigned 8-bit integer, which you can create in your MEX-file using the mxCreateNumericArray routine:
field3 = mxCreateNumericMatrix(20, 2, mxUINT8_CLASS, mxREAL);
//The above says to create a real (as opposed to complex) 20 x 2 matrix of type "uint8".
You can now add this to the structure that was previously created with the mxCreateStructMatrix using the mxSetField routine.
mxArray *structure;
mxArray *field3;
unsigned char *pdata;
structure = mxCreateStructMatrix(1, 1, 3, {"field1", "field2","field3"});
mxSetField(structure, 0, "field1", mxCreateDoubleScalar(20));
mxSetField(structure, 0, "field2", mxCreateDoubleScalar(2));
field3 = mxCreateNumericMatrix(20, 2, mxUINT8_CLASS, mxREAL);
//returns the pointer to the data part of the MATLAB array
pdata = mxGetData(field3);
// Now copy actual data into the data part of field3
for (int j = 0 ; j < 2 ; j++) {
for (int i = 0 ; i < 20 ; i++) {
pdata[20*j + i] = CppMatrix[i][j];
}
}
mxSetField(structure, 0,"field3", field3);

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!