MATLAB: How to create a matrix of type uint32 using mxCreateNumericMatrix and fill it using memcpy() in MATLAB 7.6 (R2008a)

alternativefloatint16int32int64int8MATLABothertypesuint16uint64uint8

I wasn't able to find any examples on how to create a non-double matrix. I would also like to fill it using the C function memcpy() to avoid a time consuming loop.

Best Answer

The following example demonstrates how to create an uint32 matrix and copy the data from a vector data structure (requires C++) using the memcpy() function.
// Name: uint32test.cpp
// Compile: mex uint32test.cpp
// Test: uint32test
#include "mex.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#define printf mexPrintf
/* Output Arguments */
#defineMY_OUTplhs[0]
#define MY_SIZE10
typedef unsigned int MY_TYPE; // Define data type (should match MATLAB type, e. g. mxUINT32_CLASS).
using std::vector; // C++.
// MEX-gateway routine.
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
vector<MY_TYPE> testVector;
testVector.reserve(MY_SIZE);
// Fill test vector with numbers.
MY_TYPE tempCounter = 0; // 0 to MY_SIZE.
for (tempCounter = 0; tempCounter < MY_SIZE; ++tempCounter) {
testVector.push_back(tempCounter);
}
// Create uint32 matrix of dimensions tempCounter * 4.
MY_OUT = mxCreateNumericMatrix((mwSize) tempCounter, (mwSize) 4, mxUINT32_CLASS, mxREAL);
// Use memcpy to fill the matrix instead of using a loop.
MY_TYPE * ptr_OUT = (MY_TYPE *) mxGetPr(MY_OUT);
// Each column is filled separately, but the whole matrix could also be filled at once,
// if the copied data has the same size as the matrix.
memcpy(&ptr_OUT[0], &testVector[0], tempCounter * sizeof(MY_TYPE)); // Column 1.
memcpy(&ptr_OUT[tempCounter], &testVector[0], tempCounter * sizeof(MY_TYPE)); // Column 2.
memcpy(&ptr_OUT[2 * tempCounter], &testVector[0], tempCounter * sizeof(MY_TYPE)); // Column 3.
memcpy(&ptr_OUT[3 * tempCounter], &testVector[0], tempCounter * sizeof(MY_TYPE)); // Column 4.
return;
}