4
$\begingroup$

I have a matrix. and i have shown the output of matrix one by one element in FortranForm.

the problem is i want to put "&" continuation charater in output because when i am copying the data into fortran Code, Fortran is showing warning that it exceeds 2048 characters .

So i wanted to put ampersand character in each output of matrix element in FortranForm......please help

For example if matrix(1,1)=a1^2+b11^2 (a long line 2048 characters)

then i want it to be shown like matrix(1,1)=a1^2+b11^2 & & +c^2+.....(breaking each line with '&')

Above expression is in fortranform but could not show here as text

$\endgroup$

2 Answers 2

4
$\begingroup$

I think you should try to improve your question: it always helps when you provide an example as working code that shows the problem and explain what output you want to achieve for that example. Here is code which I think should do what you have asked for:

matrixToFortranForm[mat_?MatrixQ, matName_String, lineLength_: 70] := 
Module[{x, y},
  StringRiffle[
   Flatten@Table[
     StringReplace[
      ToString[
       Row[{
         StringForm["`1`(`2`,`3`) = ", matName, x, y],
         FortranForm[mat[[x, y]]]
         }],
       PageWidth -> lineLength
       ]
      ,
      {StartOfLine ~~ " \n" -> "", "\n" -> "&\n"}
      ],
     {x, Length[mat]},
     {y, Length[First[mat]]}
     ],
   "\n\n"
   ]
  ]

to try it you could use:

m = Table[Expand[(b + x a)^y], {x, 1, 3}, {y, 5, 10}];
matrixToFortranForm[m, "matrix"]
$\endgroup$
1
  • $\begingroup$ very helpful! thank you @Albert Retey $\endgroup$
    – ABCDEMMM
    Commented Oct 29, 2018 at 1:28
3
$\begingroup$

I also have this problem, and try this code F90Format

Unprotect[D]; Clear[D]; Protect[D];
NN[exp_] := N[exp, 50];
Unprotect[Real];
RTogle = False;
Real /: Format[r_Real /; r >= 0, FortranForm] /; (RTogle = ! RTogle) :=
   Module[{mantissa, exponent, tmp},
   {mantissa, exponent} = MantissaExponent[r];
   If[r === 0., exponent = 1];
   SequenceForm[10 mantissa, D, exponent - 1]
   ];
Protect[Real];
F90Format[exp_, pre_: ""] := Module[{tmp, sqrt, splits},
   tmp = FortranForm[exp];
   tmp = ToString[tmp, PageWidth -> Infinity, 
     TotalWidth -> Infinity];
   splits = StringSplit[tmp, " "];
   tmp = Fold[If[StringLength[Last@#1] + StringLength[#2] > 100,
       Join[#1, {#2}],
       Join[Most[#1], {StringJoin[Last[#1], #2]}]] &,
     {First@splits}, Rest[splits]];
   tmp = StringJoin @@ Riffle[tmp, " &\n"];
   tmp = pre <> tmp;
   Return[tmp];
   ];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.