# Importing multiple matrices or multidimensional arrays from a text file

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

A B
C D


After importing I get

{{a,b},{c,d},{},{A,B},{C,D}}


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.

• 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. Mar 29, 2018 at 7:23
• Can you point me in the right direction before I do so? I am only familiar with using the basic fortran formatted output.
– Kai
Mar 29, 2018 at 16:25

You can split it like this

dataIn={{a,b},{c,d},{},{A0,B0},{C0,D0}};
newData=SplitBy[dataIn,#=={}&]
newData=DeleteCases[newData,{{}}] • This worked perfectly, I knew it must be possible but couldn't figure out how to do it
– Kai
Mar 29, 2018 at 16:21
• 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
– Kai
Mar 29, 2018 at 16:30