Scientific Computing & Visualization
Help Contact
About Accounts Computation Visualization Documentation Services

Introduction to MATLAB

How to embed your standalone fortran/c code into matlab

  • Change your main program into a subroutine, say, soussas_matlab.f
  • Create an interface "gateway" subroutine which calls the main-program-turned subroutine, soussas_matlab.f
    #include < fintrf.h>  
    C Gateway function  
    C 
          SUBROUTINE MEXFUNCTION(NLHS, PLHS, NRHS, PRHS)
          
          POINTER PLHS(*), PRHS(*)        
          INTEGER NLHS, NRHS  
    C        
          POINTER MXCREATEFULL, MXGETPR        
          INTEGER MXGETM, MXGETN  
    C  
    C This is required for interfacing a .MEX file to MATLAB.  
    C        
          integer np        
          pointer pnp        
          real*8 rnp  
    C  
    C CHECK FOR PROPER NUMBER OF ARGUMENTS  
    C        
          IF (NRHS .NE. 1) THEN          
            CALL MEXERRMSGTXT('SOUSSA requires ONE input arguments')        
          ELSEIF (NLHS .NE. 0) THEN          
            CALL MEXERRMSGTXT('LU requires NO output argument')        
          ENDIF  
    C  
    C ASSIGN POINTERS TO THE VARIOUS PARAMETERS  
    C        
          pnp  = mxGetPR(PRHS(1))    !! get input array pointer via MATLAB fct
          
          call mxCopyPtrToReal8(pnp, rnp, 1)          
          
          np = int(rnp)    
          
    C CREATE MATRICES FOR RETURN ARGUMENTS    
    C DO THE ACTUAL COMPUTATIONS IN A SUBROUTINE    
          call soussas_matlab(np)           
          
          RETURN        
          END  
  • Compile all subroutines, including the gateway routine, via the matlab "mex" compile script with appropriate switches
    # makefile for SOUSSA  
    SHELL=/bin/sh  
    .SUFFIXES:	.o .f .f90    
    
    FFLAGS = -64 -r10000 -mips4 -Ofast -OPT:roundoff=0    
    
    F77 = f77 $(FFLAGS)  
    F90 = f90 $(FFLAGS)  
    MEX = mex -I. FFLAGS='$$FFLAGS -64' LDFLAGS='$$LDFLAGS -64 -IPA' 
            FOPTIMFLAGS='-O3'
    
    ...      
    
    
    mex:   	
            $(MEX) $(SRC2) $(SRC7) $(SRC1) $(OBJ5)  	
            mv -f $(SRC2:.f=.mexsg64) soussas.mexsg64    ...  
  • Optionally you can create an m-file that calls the newly created executable
    function soussas(np)  
    % function soussas(np)  
    %  
    %   runs the steady-state SOUSSA program EXTERNALLY via matlab  
    %   np -- number of processors  
    %  
    soussas_matlab(np)     % runs steady_state code to generate "matlab.out"
  • Now proceed to use this m-file as you would any m-file
  • All your I/O are through data files, not stdio
  • Since there is no output coming back thru soussas_matlab.f, MATLAB does not have access to any output generated. You must read it in from a file.

left

bar right up

Documentation
Boston University
Boston University
 
OIT | CCS | July 7, 2009  
Scientific Computing & Visualization Boston University home page Boston University home page