【问题标题】:Importing data into Mathematica in the form of a matrix以矩阵的形式将数据导入 Mathematica
【发布时间】:2013-01-04 22:29:45
【问题描述】:

我有一个文件,当我导入 Mathematica 时,它看起来像这样: {{1,1,n1},{1,2,n2},{1,3,n3},{2,1,n4},{2,2,n5},{2,3,n6}} 其中n1...n6 是一些我想作为矩阵导入的数字,如下所示:

每个块中的第一个数字指定行,第二个指定列,但它们不是矩阵的一部分。只有每个块中的第三个数字是矩阵的一部分。我该怎么做?

【问题讨论】:

    标签: matrix wolfram-mathematica


    【解决方案1】:

    如果

    data = {{1, 1, n1}, {1, 2, n2}, {1, 3, n3}, {2, 1, n4}, {2, 2, n5}, {2, 3, n6}};
    

    你可以这样做

    mat = Partition[data[[All, 3]], 3, 3]
    

    【讨论】:

    • 如果保证数据填充矩阵,但排序不正确,只需应用 Sort[] 即可获得正确的顺序。这可能比 sparsearray 方法执行得更好(或者如果您不知道先验维度,则可能不会。)
    • 非常感谢。完美运行
    【解决方案2】:

    我能想到对这个问题的几种解释。

    如果您的数据采用常规格式,并且您希望以内存高效的方式读取它,我建议仔细查看 ReadList 和相关功能,如我 already directed you toward 和另一个答案所示的 Partition 函数。

    我将重点关注数据不是完全规则形式的想法,因为给定的行和列索引对于描述数据在数组中的位置是必要的。为此,最自然的方法是使用SparseArray,它以位置和值Rule 对的形式接受数据:

    data = {{1, 1, n1}, {1, 2, n2}, {1, 3, n3}, {2, 1, n4}, {2, 2, n5}, {2, 3, n6}};
    
    array = SparseArray[{#, #2} -> #3 & @@@ data];
    
    array // MatrixForm
    

    Normal 函数可用于根据需要将SparseArray 转换为常规 list-of-lists 数组:

    Normal @ array
    
    {{n1, n2, n3}, {n4, n5, n6}}
    

    还有there is a StackExchange site 致力于Mathematica,我鼓励你去探索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-07
      • 2021-10-25
      • 2012-08-08
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多