External Interfaces |
Handling 8-,16-, and 32-Bit Data
You can create and manipulate signed and unsigned 8-, 16-, and 32-bit data from within your MEX-files. The MATLAB API provides a set of functions that support these data types. The API function mxCreateNumericArray
constructs an unpopulated N-dimensional numeric array with a specified data size. Refer to the entry for mxClassID
in the online reference pages for a discussion of how the MATLAB API represents these data types.
Once you have created an unpopulated MATLAB array of a specified data type, you can access the data using mxGetData
and mxGetImagData
. These two functions return pointers to the real and imaginary data. You can perform arithmetic on data of 8-, 16- or 32-bit precision in MEX-files and return the result to MATLAB, which will recognize the correct data class.
This example constructs a 2-by-2 matrix with unsigned 16-bit integers, doubles each element, and returns the resulting matrix to MATLAB.
/* * ============================================================= * doubleelement.c - Example found in API Guide * * Constructs a 2-by-2 matrix with unsigned 16-bit integers, * doubles each element, and returns the matrix. * * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. * ============================================================= */ /* $Revision: 1.9 $ */ #include <string.h> /* Needed for memcpy() */ #include "mex.h" #define NDIMS 2 #define TOTAL_ELEMENTS 4 /* The computational subroutine */ void dbl_elem(unsigned short *x) { unsigned short scalar=2; int i; for (i=0; i<4; i++) *(x+i) *= scalar; } /* The gateway routine */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { const int dims[]={2,2}; unsigned char *start_of_pr; unsigned short data[]={1,2,3,4}; int bytes_to_copy; /* Call the computational subroutine. */ dbl_elem(data); /* Create a 2-by-2 array of unsigned 16-bit integers. */ plhs[0] = mxCreateNumericArray(NDIMS,dims,mxUINT16_CLASS, mxREAL); /* Populate the real part of the created array. */ start_of_pr = (unsigned char *)mxGetData(plhs[0]); bytes_to_copy = TOTAL_ELEMENTS * mxGetElementSize(plhs[0]); memcpy(start_of_pr, data, bytes_to_copy); }
At the MATLAB prompt, entering
The output of this function is a 2-by-2 matrix populated with unsigned 16-bit integers.
Handling Complex Data | Manipulating Multidimensional Numerical Arrays |
© 1994-2005 The MathWorks, Inc.