外部インタフェース/API | ![]() ![]() |
複素データの操作
MATLABは、複素数倍精度データを2つの数値ベクトルとして格納します。1つは実数データを含み、もう1つは虚数データを含みます。APIは2つの関数、mxCopyPtrToComplex16
とmxCopyComplex16ToPtr
を提供し、MATLABデータをcomplex*16
Fortran配列にコピーします。
つぎの例は、2つの(長さ3の)複素ベクトルの畳込みを行います。
C $ Revision: 1.14 $ C============================================================== C C convec.f C Example for illustrating how to pass complex data from C MATLAB to FORTRAN (using COMPLEX data type) and back C again. C C Convolves two complex input vectors. C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C============================================================== C C Computational subroutine subroutine convec(x, y, z, nx, ny) complex*16 x(*), y(*), z(*) integer nx, ny C Initialize the output array. do 10 i=1,nx+ny-1 z(i) = (0.0,0.0) 10 continue do 30 i=1,nx do 20 j=1,ny z(i+j-1) = z(i+j-1) + x(i) * y(j) 20 continue 30 continue return end C The gateway routine. subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer nlhs, nrhs C-------------------------------------------------------------- C (pointer) Replace integer by integer*8 on the DEC Alpha C platform. C integer plhs(*), prhs(*) integer mxGetPr, mxGetPi, mxCreateFull C-------------------------------------------------------------- C integer mx, nx, my, ny, nz integer mxGetM, mxGetN, mxIsComplex complex*16 x(100), y(100), z(199) C Check for proper number of arguments. if (nrhs .ne. 2) then call mexErrMsgTxt('Two inputs required.') elseif (nlhs .gt. 1) then call mexErrMsgTxt('Too many output arguments.') endif C Check that inputs are both row vectors. mx = mxGetM(prhs(1)) nx = mxGetN(prhs(1)) my = mxGetM(prhs(2)) ny = mxGetN(prhs(2)) nz = nx+ny-1 C Only handle row vector input. if(mx .ne. 1 .or. my .ne. 1) then call mexErrMsgTxt('Both inputs must be row vector.') C Check sizes of the two input. elseif(nx .gt. 100 .or. ny .gt. 100) then call mexErrMsgTxt('Inputs must have less than 100 elements.') C Check to see both inputs are complex. elseif ((mxIsComplex(prhs(1)) .ne. 1) .or. + (mxIsComplex(prhs(2)) .ne. 1)) then call mexErrMsgTxt('Inputs must be complex.') endif C Create the output array. plhs(1) = mxCreateFull(1, nz, 1) C Load the data into Fortran arrays(native COMPLEX data). call mxCopyPtrToComplex16(mxGetPr(prhs(1)), mxGetPi(prhs(1)), x, nx) call mxCopyPtrToComplex16(mxGetPr(prhs(2)), mxGetPi(prhs(2)), y, ny) C Call the computational subroutine. call convec(x, y, z, nx, ny) C Load the output into a MATLAB array. call mxCopyComplex16ToPtr(z,mxGetPr(plhs(1)), mxGetPi(plhs(1)), nz) return end
x = [3 - 1i, 4 + 2i, 7 - 3i] x = 3.0000 - 1.0000i 4.0000 + 2.0000i 7.0000 - 3.0000i y = [8 - 6i, 12 + 16i, 40 - 42i] y = 8.0000 - 6.0000i 12.0000 +16.0000i 40.0000 -42.0000i
z = convec(x, y)
z = 1.0e+02 * Columns 1 through 4 0.1800 - 0.2600i 0.9600 + 0.2800i 1.3200 - 1.4400i 3.7600 - 0.1200i Column 5 1.5400 - 4.1400i
これは、MATLAB組込み関数conv.m
の結果と一致します。
![]() | 複数の入出力を渡す | メモリのダイナミックな割り当て | ![]() |