[Fortran] 纯文本查看 复制代码
MODULE MATLAB
IMPLICIT NONE
INTEGER(8)::EP !//kind=8
integer :: STATUS
INTEGER(8),EXTERNAL:: engOpen ,engPutVariable , engGetVariable ,engEvalString,engClose!//kind=8
INTEGER(8),EXTERNAL:: mxCreateDoubleMatrix, mxGetPr!//kind=8
CONTAINS
SUBROUTINE STARTMATLAB()
WRITE(*,*) '正在打开matlab程序,请稍后...'
EP = engOpen('matlab')
IF(EP == 0) THEN
WRITE(*,*) '无法打开matlab'
STOP
ELSE
WRITE(*,*) '成功打开matlab'
ENDIF
END SUBROUTINE STARTMATLAB
SUBROUTINE CLOSEMATLAB()
WRITE(*,*) '正在关闭matlab程序,请稍后...'
STATUS = engClose(EP)
IF(STATUS /= 0) THEN
WRITE(*,*) '无法关闭matlab'
STOP
ELSE
WRITE(*,*) '成功关闭matlab'
ENDIF
END SUBROUTINE CLOSEMATLAB
SUBROUTINE MC(STRING)
CHARACTER(LEN=*)::STRING
PRINT * , '正在matlab中计算语句: ', STRING
IF(engEvalString(EP,STRING) /= 0) THEN
WRITE(*,*) 'engEvalString failed'
STOP
ENDIF
END SUBROUTINE MC
SUBROUTINE F2M(FDATA,MSTRING,ROW,COL)
INTEGER :: ROW,COL
REAL(8),DIMENSION(ROW,COL) :: FDATA!//kind=8
CHARACTER(LEN=*) :: MSTRING
INTEGER(8) :: PTEMP!//kind=8
PTEMP = mxCreateDoubleMatrix(ROW,COL,0)
IF (PTEMP == 0) THEN
WRITE(*,*) '无法申请到内存'
STOP
ENDIF
CALL mxCopyReal8ToPtr(fdata,mxGetPr(ptemp),ROW*COL)
STATUS = engPutVariable(EP, MSTRING,PTEMP)
CALL mxDestroyArray(PTEMP)
PRINT * , '正在matlab中生成矩阵: ', MSTRING
IF(STATUS /= 0) THEN
WRITE(*,*) 'engPutVariable failed'
STOP
END IF
END SUBROUTINE F2M
SUBROUTINE M2F(MSTRING,DDATA,ROW,COL)
INTEGER :: ROW,COL
REAL(8),DIMENSION(ROW,COL) :: DDATA!//kind=8
CHARACTER(LEN=*) :: MSTRING
INTEGER(8) :: PTEMP!//kind=8
PTEMP = engGetVariable(EP,MSTRING)
CALL mxCopyPtrToReal8( mxGetPr(ptemp),DDATA,ROW*COL)
END SUBROUTINE M2F
END MODULE MATLAB
PROGRAM MAIN
USE MATLAB
IMPLICIT NONE
INTEGER,PARAMETER::NDATA = 10
REAL(8),DIMENSION(NDATA)::X,Y,Z
INTEGER::M
DO M = 1,NDATA
X(M) = 3.14159*(M-1)/(NDATA-1)
Y(M) = SIN(X(M))
ENDDO
CALL STARTMATLAB()
CALL F2M(X,'X',1,NDATA)
CALL F2M(Y,'Y',1,NDATA)
CALL MC("plot(X,Y);title('y=sin(x)');xlabel('x');ylabel('y')")
CALL MC('Z=2*Y;')!//matlab区分大小写
CALL M2F('Z',z,1,NDATA)!//matlab区分大小写
PRINT * ,' X ' ,' Y ',' Z ',' 2*Y'
DO M = 1,NDATA
WRITE(*,'(G15.6,G15.6,G15.6,G15.6)') X(M),Y(M),Z(M),2*Y(M)
ENDDO
END PROGRAM MAIN