2

I want to read MATLAB output by Fortran code. Therefore, I need to write MATLAB script to generate a text file with decimal notation. like: MATLAB code

x=123.45
 fprintf(filetxt,'%f',x)

Output:

123.45

How to write output command or set format so I get this value in filetxt like:

1.2345d02 

Maximum I can get is 1.2345e02 but I want to write like 1.2345d02

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • _Why_ do you want to write like `1.2345d02`? I suspect your Fortran program won't care. – francescalus Nov 14 '18 at 17:08
  • I read fortran manual where it say we need to write float with 'd' so otherwise fortran compiler with roud off it to a single percision during reading file and assigning to variable.even if variable if declared double percision. i think my understanding must be wrong as you said. – Shahbaz Ahmed Nov 14 '18 at 18:05
  • 1
    That's true only for constants in source files. For input at run time the answer below covers things. See also [this other question](https://stackoverflow.com/q/33319357/3157076). – francescalus Nov 14 '18 at 18:10

1 Answers1

4

As suggested by @francescalus, I think your Fortran compiler will probably read in a floating-point literal like 1.2345e02 as expected into a double-precision variable (as in the code below). So, I guess you can just write 1.2345e02 rather than 1.2345d02 to a data file...

program main
    implicit none
    real :: xs
    double precision :: xd

    open(10, file='test.dat', status='old')
    read(10,*) xs
    read(10,*) xd
    close(10)

    print "(a, e30.18)", "xs = ", xs
    print "(a, e30.18)", "xd = ", xd
end

test.dat:

0.1234567890123456e12
0.1234567890123456e12

Result (gfortran test.f90):

xs =       0.123456790528000000E+12
xd =       0.123456789012345596E+12  <-- double-precision accuracy
roygvib
  • 7,218
  • 2
  • 19
  • 36
  • 2
    Perhaps the important part is "An exponent containing a D is processed identically to an exponent containing an E." That's F77. – francescalus Nov 14 '18 at 17:58
  • Thanks very much for your info, now I've changed the phrase to "your Fortran compiler...". (And, apart from OP's question, it is interesting why the "D" exponent is used in a file. I will ask somewhere later.) – roygvib Nov 14 '18 at 18:02