3D Matrix Transfer for Mixed Programming of Matlab and C

Since mexFunction is different from programming directly in C language, the use of pointers is very cumbersome, especially when faced with the problem of incoming and outgoing parameters. Here, I pass a three-dimensional matrix generated in matlab to mexFunction, and then pass it out to matlab. Of course, we can perform various operations and calculations of matrices in mexFunction according to our own needs.

First, the extraction of three-dimensional matrix dimension parameters

int M,N,K; //Define the number of elements in three dimensions

cons int *dim_array;

dim_array=mxGetDimensions(prhs[0]);

#include<stdio.h>
#include"mex.h"

void mexFunction (int nlhs, mxArray * plhs [], int nrhs, const mxArray * prhs [])
{
    double *p;
    double *page;
  // mwSize dims[3];
    int i,j,k,M,N,K;
    int ii = 0;
 const int *dim_array;
  int numberofdims;
  numberofdims=mxGetNumberOfDimensions(prhs[0]);
  dim_array=mxGetDimensions(prhs[0]);
   p=mxGetPr(prhs[0]);
   M=*dim_array;sanwei
   N=*(dim_array+1);
   K=*(dim_array+2);
   printf("%d %d %d \n",M,N,K);  
   // dims [3] = (M, N, K);
   plhs[0]=mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]),mxGetDimensions(prhs[0]),mxDOUBLE_CLASS,mxREAL);
   page=(double*)mxGetData(plhs[0]);
   
  for(k=0;k<K;k++)
  {
   // *page=*(page+M*N);
   for(i=0;i<M;i++)
     {
        for(j=0;j<N;j++)
        {
           page[(M*N)*k+i*N+j]=p[(M*N)*k+i*N+j];
        }
   }  
  }
  
}

M=*dim_array;

N=*( dim_array+1);

K=*( dim_array+2);

printf("%d%d %d \n",M,N,K); 

 

Second, the transfer of three-dimensional matrix

1. For the double-precision matrix commonly used in matlab, we use the mxCreateNumericArray function to generate an N-dimensional matrix, mxGetNumberOfDimensions(prhs[0]) to get the dimension of the current matrix, and the result is 3; mxGetDimensions(prhs[0]) is to get the matrix Each dimension value of (this item, can also define int dims[3], and then many methods can use dim={M,N,K} I use matlab2014b and VC2013 need to replace the curly brackets with parentheses so that they will not error, need to pay attention)

plhs[0]=mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]),mxGetDimensions(prhs[0]),mxDOUBLE_CLASS,mxREAL);

2. After obtaining the output matrix plhs[0], we can assign it. Here we define double *page to operate:

page=(double*)mxGetData(plhs[0]);//Note that mxGetData here is of void * type, which needs to be converted.

3. The assignment of the three-dimensional matrix is ​​done using our common three-layer loop, p is the input pointer:

  for(k=0;k<K;k++)

  {

   for(i=0;i<M;i++)

     {

        for(j=0;j<N;j++)

        {

          page[(M*N)*k+i*N+j]=p[(M*N)*k+i*N+j];

        }

  

  }

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324725231&siteId=291194637