A PUZZLING QUESTION: Does Matlab's Mex file support external inputs and outputs?

Hi, I would like to ask if Mex (Fortran) files are able to use Fortran's OPEN/CLOSE/WRITE/READ from files command?
If yes, how do I implement it in Matlab's Mex files? Else, are there any alternatives to output in an external document?
Thanks
Zhonghao

Answers (1)

Yes, you can use native Fortran file I/O in mex routines. Just write the code as you normally would. The main restriction is in screen I/O ... you can't READ(5,etc) or WRITE(6,etc) in a mex routine as the operations will not work properly. But file I/O is OK.

5 Comments

However, I can't seem to write. My code is as follow. Can you spot the bug?
#include "fintrf.h"
C======================================================================
#if 0
C
C add.F
C .F file needs to be preprocessed to generate .for equivalent
C
#endif
C
C add.f
C
C Adds two integers
C
C======================================================================
C Gateway routine
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C Declarations
implicit none
C mexFunction arguments:
mwPointer plhs(*), prhs(*)
integer nlhs, nrhs
C Declare local variables for the mexfunction arguments
mwPointer a, b
mwPointer c
mwSize :: one = 1
integer*4 classid
integer*4 :: mxREAL = 0
C Declare the symbolic names and types of this function
integer mxIsNumeric
integer*4 mxClassIDFromClassName
mwPointer mxCreateNumericMatrix, mxGetData
C Prepare in/out matrix:
classid = mxClassIDFromClassName("int64")
plhs(1) = mxCreateNumericMatrix(one,one,classid,mxREAL)
a = mxGetPr(prhs(1))
b = mxGetPr(prhs(2))
c = mxGetData(plhs(1))
C Call the computational subroutine.
call add(%val(a), %val(b), %val(c))
return
end
C-----------------------------------------------------------------------
C Computational subroutine
subroutine add(a, b, c)
integer*8 a, b, c
c = b + a
open (unit=8,file='Test.txt')
write (8,*) c
close(8)
return
end
What do you mean by "can't seem to write"? Get unexpected value printed to the file? Get an error trying to write to the file? MATLAB crashes? Or what?
I mean fortran's output command (write)
Yes, but what is the specific message you see on the screen? Anything? Does anything show up in the Test.txt file?
Sorry for the confusion.
An output 'Test.txt' file was created but it is empty. Matlab also crashes when the program was being run.
I've tried compiling and running this on windows 64bit and strangely it works. (by the way, I was using OSX mavericks matlab 2012a with gfortran compiler)
Do you have any idea why this happens?

Sign in to comment.

Asked:

on 9 Jun 2014

Commented:

on 11 Jun 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!