如何在 Mathematica 中将文件中的数据作为列表/数组导入 [英] How to import data from a file as list/array in Mathematica

查看:87
本文介绍了如何在 Mathematica 中将文件中的数据作为列表/数组导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据(点),我必须从另一个程序导入到 Mathematica,所以我可以绘制它.我可以控制如何将点写入文件,因此我可以按我想要的任何方式放置它们.将它们导入 Mathematica 的最佳方法是什么?由于我将使用 StreamDensityPlot,因此我必须通过以下方式传递给 StreamDensityPlot 的变量:

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},
        }
    }

您如何建议我将数据放入中间文本文件中?我应该用什么来导入它?我试过导入 ["mytext.txt", "List"],让我的文本文件包含上面显示的形式,但似乎 Mathematica 将这些点视为字符串,我无法对它们做任何事情.有没有办法像其他语言一样将字符串转换为任意数据(前提是它们在新数据类型中有效)?

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)?

回顾:

  1. 是否可以在 Mathematica 中将字符串(例如5")转换为数字?如果是,如何?
  2. 是否可以将像 "{1 , 2, 3}" 这样的字符串转换为 Mathematica 中的列表?如果是,如何?
  3. 是否可以在 Mathematica 中将 CSV 文件加载为如上所示的列表列表?

谢谢

推荐答案

将字符串转换为表达式使用 ToExpression.如果您有一个纯文本文件 foo.txt,格式与您的示例相同,那么只需将它导入到 Mathematica 中 Get,即<< 将以您想要的方式导入和评估 data,无需文本到表达式的翻译.

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.

这篇关于如何在 Mathematica 中将文件中的数据作为列表/数组导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆