External Interfaces |
Passing Two or More Inputs or Outputs
The plhs
and prhs
parameters are vectors that contain pointers to each left-hand side (output) variable and right-hand side (input) variable. Accordingly, plhs(1)
contains a pointer to the first left-hand side argument, plhs(2)
contains a pointer to the second left-hand side argument, and so on. Likewise, prhs(1)
contains a pointer to the first right-hand side argument, prhs(2)
points to the second, and so on.
This routine multiplies an input scalar times an input scalar or matrix.
C============================================================== = C xtimesy.f C C Multiply the first input by the second input. C C This is a MEX file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C $Revision: 1.12 $ C============================================================== = C Computational subroutine subroutine xtimesy(x, y, z, m, n) real*8 x, y(3,3), z(3,3) integer m, n do 20 i=1,m do 10 j=1,n z(i,j) = x*y(i,j) 10 continue 20 continue return end C The gateway routine subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer mxGetM, mxGetN, mxIsNumeric integer mxCreateDoubleMatrix integer plhs(*), prhs(*) integer x_pr, y_pr, z_pr integer nlhs, nrhs integer m, n, size real*8 x, y(3,3), z(3,3) C Check for proper number of arguments. if (nrhs .ne. 2) then call mexErrMsgTxt('Two inputs required.') elseif (nlhs .ne. 1) then call mexErrMsgTxt('One output required.') endif C Check to see both inputs are numeric. if (mxIsNumeric(prhs(1)) .ne. 1) then call mexErrMsgTxt('Input #1 is not a numeric.') elseif (mxIsNumeric(prhs(2)) .ne. 1) then call mexErrMsgTxt('Input #2 is not a numeric array.') endif C Check that input #1 is a scalar. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) if(n .ne. 1 .or. m .ne. 1) then call mexErrMsgTxt('Input #1 is not a scalar.') endif C Get the size of the input matrix. m = mxGetM(prhs(2)) n = mxGetN(prhs(2)) size = m*n C Create matrix for the return argument. plhs(1) = mxCreateDoubleMatrix(m, n, 0) x_pr = mxGetPr(prhs(1)) y_pr = mxGetPr(prhs(2)) z_pr = mxGetPr(plhs(1)) C Load the data into Fortran arrays. call mxCopyPtrToReal8(x_pr, x, 1) call mxCopyPtrToReal8(y_pr, y, size) C Call the computational subroutine. call xtimesy(x, y, z, m, n) C Load the output into a MATLAB array. call mxCopyReal8ToPtr(z, z_pr, size) return end
As this example shows, creating MEX-file gateways that handle multiple inputs and outputs is straightforward. All you need to do is keep track of which indices of the vectors prhs
and plhs
correspond to which input and output arguments of your function. In this example, the input variable x
corresponds to prhs(1)
and the input variable y
to prhs(2)
.
For an input scalar x
and a real 3-by-3 matrix,
Passing Matrices | Handling Complex Data |
© 1994-2005 The MathWorks, Inc.