# mexcuda how to declare a matrix with size N given in input

1 view (last 30 days)
Charlotte Constans on 28 Mar 2023
Answered: Joss Knight on 4 Apr 2023
I am trying to calculate some harmonic components of a function mua on a [Nx Ny ] domain. I want to give in input the desired number of harmonics N, so that my output is a matrix An of size [N Nx Ny].
I can retrieve Nx and Ny from mxGPUGetNumberOfElements and mxGPUGetDimensions, but I can't find a way to access the value of N in my MexFunction, all I can get is an adress.
Here is a very simplified version of the mexFunction to illustrate my problem, where I hard coded N=16 in my declaration of matrix (Nnyz=16*NyNz;) to avoid memory issues , and printed the values of N and d_N:
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, mxArray const *prhs[])
{
mxGPUArray const *mua;
mxGPUArray const *N;
float const *d_mua;
int const *d_N;
mxGPUArray *An;
float *d_An;
int Np;
int blocksPerGrid;
mxInitGPU();
mua = mxGPUCreateFromMxArray(prhs[0]);
N = mxGPUCreateFromMxArray(prhs[1]);
mwSize NyNz;
mwSize Nnyz;
mwSize Ny;
NyNz= int(mxGPUGetNumberOfElements(mua));
Ny=*mxGPUGetDimensions(mua);
int Nz=NyNz/Ny;
Nnyz=16*NyNz;
mexPrintf("\n %i %i %i %i \n",N,d_N);
An = mxGPUCreateGPUArray(1,
&Nnyz,
mxSINGLE_CLASS,
mxREAL,
MX_GPU_INITIALIZE_VALUES);
d_An = (float *)(mxGPUGetData(An));
Np = (int)(mxGPUGetNumberOfElements(mua));
plhs[0] = mxGPUCreateMxArrayOnGPU(An);
mxGPUDestroyGPUArray(mua);
mxGPUDestroyGPUArray(N);
mxGPUDestroyGPUArray(An);
}
The printed result for N,d_N is:
2063388544 18874880.
Printing Ny and NyNz gave me the right dimensions .

Joss Knight on 4 Apr 2023
Hi Charlotte. If you just want to pass an ordinary scalar value to a mex function then use the ordinary Mex API rather than the mxGPU API. Pass a non-gpuArray scalar N to your function and read it into a variable using simple syntax like mxGetScalar . By calling mxGPUCreateFromMxArray you are creating a new scalar on the GPU. Now when you get the pointer to the data it's on the GPU! So you would have to copy it back again using cudaMemcpy or equivalent.

### Categories

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

R2021a

### Community Treasure Hunt

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

Start Hunting!