I would like to import multiple files to a 2d array. I know to get a list of files I can do


Is it possible to get my data files in a 2d array if, for example, my files look like


where the numbers in the filenames correspond to an x and y index. I have done this using for loops. Is there a more functional way?

  • 1
    $\begingroup$ its best if your files end with .dat; your command should work as is (?) $\endgroup$ – chris Nov 5 '12 at 12:32
  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2)Read the FAQs! 3) When you see good Q&A, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. ALSO, remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign`. Another suggestion: a nice user name? $\endgroup$ – Sjoerd C. de Vries Nov 5 '12 at 20:08

A different interpretation:

Yes, it's possible and easy using GatherBy

myfiles = {"file11.txt", "file12.txt", "file21.txt", "file22.txt"};    
t = GatherBy[myfiles, {StringTake[#, -5] &}] // Transpose

(* ==> {{"file11.txt", "file12.txt"}, {"file21.txt", "file22.txt"}} *)

t[[1, 1]]

(* ==> "file11.txt" *)

t[[2, 1]]

(* ==> "file21.txt" *)

(* import with a double map*)
Function[fs, Import /@ fs] /@ t

(*or the much more elegant way of importing -- one just has to read the docs:) *)
Map[Import, t, {2}]
  • $\begingroup$ most probably the right one too ;-) $\endgroup$ – chris Nov 5 '12 at 13:26
  • $\begingroup$ @chris Thanks :) $\endgroup$ – Ajasja Nov 5 '12 at 13:36
  • $\begingroup$ Yes, this is exactly what I wanted. Thanks $\endgroup$ – user4524 Nov 5 '12 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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