# Using FortranForm

I need to use in Fortran, matrices that I create in Mathematica, therefore, I need to format them, so that Fortan can understand them. I focus on the simplest example:

Let's say I have tha matrix A created in Mathematica

A = {{1, 1}, {1, 1}};


Then, I am supposed to use FortranForm

FortranForm[A]


which gives as an output

List(List(1,1),List(1,1))


My question is, what do I do with this now? This cannot be the input file to Fortran, since this should be only numbers as far as I am aware. It could be that, the input file to Fortran is the out put of

List(List(1,1),List(1,1))


but this is nothing in Mathematica, so it does not give any output.

• I think FortranForm was made for converting formulae to a form that's either usable with Fortran or is easy enough to edit to make it usable with Fortran. If it encounters a function it doesn't support, it keeps its name and uses parentheses for the call. In this case it thinks List is a function. – Szabolcs Jun 23 '14 at 17:45
• I had the same problem while converting an analytical matrix to fortran. It took me several regular expressions to get the output in a reasonable form. The biggest problem was the conversion of literal constants to double precision while list indices should remain integer... – Stefan Jun 24 '14 at 5:17

FortranForm is really pretty limited. You need to do something like this:

 A = {{1, 1. 10^7}, {2., 1}}
StringJoin@{"A=reshape((/",
Riffle[ ToString[FortranForm[#]] & /@ Flatten[A] , ","],
"/),shape(a))"}


"A=reshape((/1,1.e7,2.,1/),shape(a))"

or

 StringJoin@{"data a/",
Riffle[ ToString[FortranForm[#]] & /@ Flatten[A] , ","], "/"}


"data a/1,1.e7,2.,1/"

( you likely want to Transpose[A] as well )

• Thanks alot for the answer, but, as far as I am aware, (and actually have checked) is that, if I want, Fortran to read my matrix A by using read* , the input file should be just a list of numbers with no comas, no brackets...and then Fortran will give them the position in the matrix according to the dimensions I set in the program – Mencia Jun 23 '14 at 17:35
• oh..for that just Export[filename,A,"Table"] and fortran will read it with a simple read(unit,*)a . (again you might want to Transpose[A] first.) – george2079 Jun 23 '14 at 17:42
• You mean, read(unit,*), A ? – Mencia Jun 23 '14 at 17:43
• the extra comma is not needed. If you are reading from standard input you could use read*,a as well. – george2079 Jun 23 '14 at 17:47
• @george2079 I am afraid you have made a mistake. Because fortran stores arrays as column major. for example {{1,2},{3,4}} in mathematica is actually reshape((/1,3,2,4/),(/2,2/)) in fortran. You have to transpose the list first – matheorem Dec 29 '15 at 13:01