How to import data from a file as a list / array into Mathematica

I have data (points) that I have to import from another program into Mathematica, so I can build it. I have control over how the items will be written to the file, so I can put them in any way. What is the way to import them into Mathematica? Since I'm going to use StreamDensityPlot, the variable I need to pass to StreamDensityPlot should be as follows:

data = { { { a, b, c }, {a, b, c}, {a, b, c}, { a, b, c }, {a, b, c}, {a, b, c}, { a, b, c }, {a, b, c}, {a, b, c}, } ... { { a, b, c }, {a, b, c}, {a, b, c}, { a, b, c }, {a, b, c}, {a, b, c}, { a, b, c }, {a, b, c}, {a, b, c}, } } 

How would you advise me to put the data in an intermediate text file? And what should I use to import it? I tried to import ["mytext.txt", "List"], having my own text file with something in the form shown above, but it seems like Mathematica treats dots as strings, and I can do nothing with them. Is there a way to convert strings to arbitrary data, as is possible in other languages ​​(if they are valid in this new data type)?

Summary:

  • Can I convert a string, such as "5" to a number, in Mathematica? If so, how?
  • Is it possible to convert a string like "{1, 2, 3}" to a list in Mathematica? If so, how?
  • Can I upload a CSV file to a list of lists, as shown above in Mathematica?

thanks

+6
wolfram-mathematica
source share
2 answers

Converting strings to expressions is done using ToExpression . If you have a text file foo.txt with formatting, as in your example, just import it into Mathematica using Get , i.e., << /path/to/foo.txt; will import and evaluate data way you want, without the need to translate text into expressions.

+9
source share

Try formatting the data file as follows:

 A, B, C, A, B, C, A, B, C A, B, C, A, B, C, A, B, C A, B, C, A, B, C, A, B, C ... 

So, you can use the CSV Mathematica import. Then divide each line into a list of points after import.

 Partition[#, 3]& /@ Import["file.csv", "CSV"] 

Also, keep in mind that Mathematica does scientific notation differently from C (or any language you use to write a data file.

+5
source share

All Articles