I have a code written in Fortran which outputs a large block-diagonal matrix, which is then written into a file in blocks. I want to know how best to import these matrices into Mathematica (I don't necessarily need to reconstruct the full block-diagonal matrix). The Import function seems to be very unhelpful when it comes to importing .dat files. Using Import["filename.dat","Table"] places a comma every time there is a space, enclosing each line in brackets. This is fine for a single matrix, but I have multiple matrices all in the same file separated by blank spaces. For example if I had a file

a b 
c d


After importing I get


I can write a routine to break these apart using the {} as a separator but there must be some simpler way of doing this. Note that with Fortran it is very hard to control the number of spaces, so I cannot write complex expressions like {i,j}->a because generally each number is printed with a fixed number of digits, leaving extra white spaces which Mathematica will convert into extra commas.

  • $\begingroup$ Note that with Fortran it is very hard to control the number of spaces It really isn't, and maybe your effort would be better directed at modifying the code to write Mathematica-friendly files. Which would be a question for another site. $\endgroup$ Mar 29, 2018 at 7:23
  • $\begingroup$ Can you point me in the right direction before I do so? I am only familiar with using the basic fortran formatted output. $\endgroup$
    – Kai
    Mar 29, 2018 at 16:25

1 Answer 1


You can split it like this


Mathematica graphics

  • $\begingroup$ This worked perfectly, I knew it must be possible but couldn't figure out how to do it $\endgroup$
    – Kai
    Mar 29, 2018 at 16:21
  • $\begingroup$ The documentation for SplitBy does not make very it clear how to separate a list this way, which I would think would be an obvious application $\endgroup$
    – Kai
    Mar 29, 2018 at 16:30

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.