Pass Multiple Inputs or Outputs

This example shows how to call a MEX-file with multiple inputs. The function, xtimesy, multiplies an input scalar by a scalar or matrix and outputs a matrix.

The plhs[] and prhs[] parameters are vectors that contain pointers to each left-side (output) variable and each right-side (input) variable, respectively. plhs[0] contains a pointer to the first left-side argument, plhs[1] contains a pointer to the second left-side argument, and so on. Likewise, prhs[0] contains a pointer to the first right-side argument, prhs[1] points to the second, and so on.

C Code Analysis

To see the code, open the fileopen the file, xtimesy.c, in the MATLAB® Editor.

Get the scalar input value, x.

x = mxGetScalar(prhs[0]);

Get the second input, y, which can be either a scalar or a matrix.

y = mxGetPr(prhs[1]);

Create the output argument, plhs[0], which is the same size as argument y.

  /*  get the dimensions of the matrix input y */
  mrows = mxGetM(prhs[1]);
  ncols = mxGetN(prhs[1]);
  
  /*  set the output pointer to the output matrix */
  plhs[0] = mxCreateDoubleMatrix( (mwSize)mrows, (mwSize)ncols, mxREAL);

Build and Test Example

Run the following commands from the MATLAB command line.

Build the example.

mex -v xtimesy.c

Call the function with scalar values.

x = 7;
y = 7;
z = xtimesy(x,y)
z = 
     49

Call the function with a matrix.

x = 9;
y = ones(3);
z = xtimesy(x,y)
z = 
     9      9      9
     9      9      9
     9      9      9
Was this topic helpful?