| 外部インタフェース/API | ![]() |
複数の入出力を渡す
パラメータplhsとprhsは、各左辺(出力)変数と右辺(入力)変数へのポインタを含むベクトルです。plhs(1)は1番目の左辺引数へのポインタを含み、plhs(2)は2番目の左辺引数へのポインタを含みます。同様に、prhs(1)は1番目の右辺入力引数へのポインタを含み、prhs(2)は2番目を意味します。
たとえば、以下のルーチンは、入力スカラまたは行列を入力スカラ回乗算します。以下は、計算サブルーチンのFortranのコードです。
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
下記は、スカラまたは行列とスカラを乗算する計算サブルーチンxtimesyを呼び出すゲートウェイルーチンです。
C--------------------------------------------------------------
C
C xtimesy.f
C
C Multiply the first input by the second input.
C This is a MEX file for MATLAB.
C Copyright (c) 1984-2000 The MathWorks, Inc.
C $ Revision: 1.11 $
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (pointer) Replace integer by integer*8 on the DEC Alpha
C platform.
C
integer plhs(*), prhs(*)
integer mxCreateFull
integer x_pr, y_pr, z_pr
C--------------------------------------------------------------
C
integer nlhs, nrhs
integer m, n, size
integer mxGetM, mxGetN, mxIsNumeric
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) = mxCreateFull(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
この例が示すように、複数の入出力を扱うMEX-ファイルゲートウェイの作成は簡単です。ベクトルprhsとplhsのどのインデックスが関数の入出力引数に対応するかを見るだけでいいのです。この例では、入力変数xはprhs(1)に対応し、入力変数yはprhs(2)に対応します。
x = 3; y = ones(3);
z = xtimesy(x, y)
z =
3 3 3
3 3 3
3 3 3
| 行列を渡す | 複素データの操作 | ![]() |