Hi, I'm having trouble trying to assign values to a 2D array
after having called mxCreateNumericArray. I would normally
expect for the 2D array to be stored as a 1D array in column
order, but this doesn't seem to be what I'm seeing. I've
written this program to demonstrate:
#include "mex.h"
#define colLen 3
#define rowLen 2
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i, j, dim[] = {colLen, rowLen};
unsigned short int *test;
plhs[0] = mxCreateNumericArray(2, dim, mxUINT8_CLASS, mxREAL);
test = mxGetPr(plhs[0]);
test[0] = 1;
test[1] = 2;
test[2] = 3;
test[3] = 4;
test[4] = 5;
test[5] = 6;
return;
}
This compiles fine but when I call it from Matlab with
>> a = test
I get an answer similar to a = [1, 0; 0, 3; 2, 0] when I
would expect something like a = [1, 4; 2, 5; 3, 6]. I get
more wrong answers if I change colLen or rowLen. Can
somebody tell me what's wrong? Everything works fine if I
use mxCreateDoubleArray instead of mxCreateNumericArray but
I need to read in unsigned 8 bit integers from a file.
Peter Boettcher - 17 Jul 2008 21:57 GMT
> Hi, I'm having trouble trying to assign values to a 2D array
> after having called mxCreateNumericArray. I would normally
[quoted text clipped - 35 lines]
> use mxCreateDoubleArray instead of mxCreateNumericArray but
> I need to read in unsigned 8 bit integers from a file.
UINT8_CLASS does not correspond to the C type unsigned short int *
(C pedants can take a hike). Try UINT8_T in your C code. It is defined
by TMW to be the C type which on your platform is 8 bits. (It is almost
always unsigned char).
-Peter
James Tursa - 17 Jul 2008 22:08 GMT
"Louis T" <tanlouiss+matlab@gmail.com> wrote in message
<g5o9p1$50b$1@fred.mathworks.com>...
> Hi, I'm having trouble trying to assign values to a 2D array
> after having called mxCreateNumericArray. I would normally
[quoted text clipped - 35 lines]
> use mxCreateDoubleArray instead of mxCreateNumericArray but
> I need to read in unsigned 8 bit integers from a file.
unsigned short ints in C are at least 2 bytes, they are
never 1 byte. So this will never match up with the
mxUINT8_CLASS you are using. Change this:
unsigned short int *test;
to this:
unsigned char *test;
Also, I don't like implicit casting because they can tend to
hide potential errors. So I would also change this line:
test = mxGetPr(plhs[0]);
to this:
test = (unsigned char *) mxGetData(plhs[0]);
James Tursa
Louis T - 18 Jul 2008 16:01 GMT
Thanks for the help. Both solutions work fine.