【问题标题】:Using R to write a .mat file not giving the right output?使用 R 编写 .mat 文件没有给出正确的输出?
【发布时间】:2014-10-10 08:43:29
【问题描述】:

我有一个想要读入 Octave 的 .csv 文件(最初尝试使用 csvread)。花了太长时间,所以我尝试使用 R 来解决:How to read large matrix from a csv efficiently in Octave 这就是我在 R 中所做的:

forest_test=read.csv('forest_test.csv')
library(R.matlab)
writeMat("forest_test.mat", forest_test_data=forest_test)

然后我回到 Octave 并这样做了:

forest_test = load('forest_test.mat')

这不是给我一个矩阵,而是一个结构。我做错了什么?

【问题讨论】:

  • read.csv 不返回矩阵;它返回一个data.frame。也许试试writeMat("forest_test.mat", forest_test_data=as.matrix(forest_test))
  • 我尝试了 MrFlick 和 BondedDust 的答案,但仍然得到一个结构。但是现在它将显示整个矩阵...也许有一种方法可以将矩阵数据从结构中提取出来?
  • 有没有人发现“writeMat”很慢?在过去几周早些时候我使用它时,它曾经更快。奇怪!

标签: r csv octave


【解决方案1】:

要回答您的确切问题,您使用的 load 函数错误。如果您只想将文件上的变量插入工作区,则不能将其输出分配给变量。来自 Octave 的load 帮助文本:

如果使用单个输出参数调用,Octave 返回数据 而不是在符号表中插入变量。如果数据 文件仅包含数字(TAB 或空格分隔的列),a 返回值矩阵。否则,'load' 返回一个 具有与变量名称相对应的成员的结构 在文件中。

用例子,跟随我们的案例:

## inserts all variables in the file in the workspace
load ("forest_test.mat");
## each variable in the file becomes a field in the forest_test struct
forest_test = load ("forest_test.mat");

但是,您发布的有关 Octave 使用 CSV 文件速度慢的链接仍然引用了 Octave 3.2.4,这是一个相当旧的版本。您是否确认在最近的版本中仍然是这种情况(最后一个版本是 3.8.2)。

【讨论】:

    【解决方案2】:

    有一个函数旨在将数据帧转换为矩阵:

    ?data.matrix
    
    forest_test=data.matrix( read.csv('forest_test.csv') )
    library(R.matlab)
    writeMat("forest_test.mat", forest_test_data=forest_test)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多