外部インタフェース/API | ![]() ![]() |
行列を渡す
MATLABでは、Fortranで書かれたMEX-ファイルとの行列のやりとりができます。mxGetPr
およびmxGetPi
を使ってMATLAB配列を操作し、MATLAB配列に格納されたデータの実部と虚部にポインタを割り当てます。mxCreateFull
を使ってMEX-ファイル内から新規のMATLAB配列を作成することができます。
C-------------------------------------------------------------- C C matsq.f C C Squares the input matrix C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C $ Revision: 1.12 $ C-------------------------------------------------------------- subroutine matsq(y, x, m, n) real*8 x(m,n), y(m,n) integer m, n C do 20 i=1,m do 10 j=1,n y(i,j)= x(i,j)**2 10 continue 20 continue return end
下記は、計算サブルーチンを呼び出すゲートウェイルーチンです。
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, mxGetPr integer x_pr, y_pr C-------------------------------------------------------------- C integer nlhs, nrhs integer mxGetM, mxGetN, mxIsNumeric integer m, n, size real*8 x(1000), y(1000) C Check for proper number of arguments. if(nrhs .ne. 1) then call mexErrMsgTxt('One input required.') elseif(nlhs .ne. 1) then call mexErrMsgTxt('One output required.') endif C Get the size of the input array. m = mxGetM(prhs(1)) n = mxGetN(prhs(1)) size = m*n C Column * row should be smaller than 1000. if(size.gt.1000) then call mexErrMsgTxt('Row * column must be <= 1000.') endif C Check to ensure the array is numeric (not strings). if(mxIsNumeric(prhs(1)) .eq. 0) then call mexErrMsgTxt('Input must be a numeric array.') endif C Create matrix for the return argument. plhs(1) = mxCreateFull(m, n, 0) x_pr = mxGetPr(prhs(1)) y_pr = mxGetPr(plhs(1)) call mxCopyPtrToReal8(x_pr, x, size) C Call the computational subroutine. call matsq(y, x, m, n) C Load the data into y_pr, which is the output to MATLAB. call mxCopyReal8ToPtr(y, y_pr, size) return end
正しい入出力引数がゲートウェイサブルーチンに割り当てられたことを保証し、入力が数値行列であったことを確認するエラーチェックを実行した後に、matsq.f
は計算サブルーチンから出力される引数に対する行列を作成します。入力行列データは、その後mxCopyPtrToReal8
を使ってFortran行列にコピーされます。計算サブルーチンが呼び出され、mxCopyReal8ToPtr
を使って出力引数が出力のポインタy_pr
に置かれます。
x = [1 2 3; 4 5 6];
y = matsq(x)
y = 1 4 9 16 25 36
![]() | 文字列配列を渡す | 複数の入出力を渡す | ![]() |