开发者

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

开发者 https://www.devze.com 2022-12-15 01:43 出处:网络
I have data(points) that I have to import from another program to Mathematica, so I can plot it. I have control on how the points are going to be written to the file, so I can put them in any way I wa

I have data(points) that I have to import from another program to Mathematica, so I can plot it. I have control on how the points are going to be written to the file, so I can put them in any way I want. What is the best way to import them to Mathematica? As I'm going to use StreamDensityPlot, the variable I'll have to pass to StreamDensityPlot will have to be in the following way:

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 advice me to put the data in the intermediate text file? And what should I use to import it? I've tried Import["mytext.txt", "List"], having my text file with something in the form shown above but it seems as Mathematica considers the points as strings, and I can't do anything with them. Is there a way to convert strings开发者_运维百科 to arbitrary data as is possible in other languages (provided they are valid in that new data type)?

Recap:

  1. Is it possible to convert a string, for example, "5" to a number, in Mathematica? If yes, how?
  2. Is it possible to convert a string like "{1 , 2, 3}" to a list in Mathematica? If yes, how?
  3. Is it possible to load a CSV file as a list of lists as shown above in Mathematica?

Thanks


Converting Strings to Expressions is done with ToExpression. If you have a plain text file foo.txt, with the formatting as in your example, then just importing it into Mathematica with Get, i.e., << /path/to/foo.txt; will import and evaluate data in the way you want, no need for text to expression translations.


Try formatting your data file like this:

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 Mathematica's CSV import. Then partition each row into a list of points after import.

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

Also, keep in mind that Mathematica does scientific notation differently than C (or whatever language you're using to write the data file.

0

精彩评论

暂无评论...
验证码 换一张
取 消