通过R进行Matlab单元阵列导入失败 [英] Matlab Cell Array Import via R fails

查看:174
本文介绍了通过R进行Matlab单元阵列导入失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临以下问题.我尝试使用R中的readMat函数导入一个字符串单元.

I am facing the following problem. I try to import a cell of strings with the readMat function in R.

Matlab代码:

Names = {'A', 'B', 'C', 'D'};
save('RDataIn.mat', 'Names');

现在我想在R中使用一组字符串.我运行以下R脚本

Now i want to use the set of strings in R. I run to following R script

R代码:

library('R.matlab')
Names <- readMat("RDataIn.mat")

readMat显然不能处理单元格类型的.mat数据,它会创建一些奇怪的列表.任何人都可以解决这个问题吗?谢谢.

readMat can for apparently not handle cell type .mat data, it creates some strange list. Anyone a solution to this problem? Thanks.

推荐答案

是的.我不会说它失败",但是它的格式需要一些工作.保存上面的单元格数组并将其加载到R中时,这就是我得到的:

Yeah.... it's pretty weird like that. I wouldn't say it "fails", but it's in a format that requires some work. This is what I get when I save the above cell array and load it into R:

> library("R.matlab")
> Names <- readMat("RDataIn.mat")
> Names
$Names
$Names[[1]]
$Names[[1]][[1]]
     [,1]
[1,] "A" 


$Names[[2]]
$Names[[2]][[1]]
     [,1]
[1,] "B" 


$Names[[3]]
$Names[[3]][[1]]
     [,1]
[1,] "C" 


$Names[[4]]
$Names[[4]][[1]]
     [,1]
[1,] "D" 



attr(,"header")
attr(,"header")$description
[1] "MATLAB 5.0 MAT-file, Platform: MACI64, Created on: Sat Mar 28 13:12:31 2015                                         "

attr(,"header")$version
[1] "5"

attr(,"header")$endian
[1] "little"

如您所见,Names包含一个嵌套列表,其中每个字符串都以1 x 1矩阵存储.您可以做的是访问此列表中的唯一元素,然后在此列表中,遍历所有元素并提取出每个嵌套元素的第一个元素.它包含您要查找的每个名称"或字符串.您可以使用标准的 sapply 为此,并为列表中的每个元素调用一个自定义函数,该函数将为您提取每个嵌套元素的第一个元素.

As you can see, Names contains a nested list where each string is stored in a 1 x 1 matrix. What you can do is access the only element of this list, then within this list, go through all of the elements and extract out the first element of each nested element. This contains each "name" or string you're looking for. You can use a standard sapply call for that and for each element in the list, apply a custom function that would extract out the first element of each nested element for you.

x <- sapply(Names[[1]], function(n) n[[1]])

x是名称的向量,我得到:

x would be a vector of names, and I get:

> x
[1] "A" "B" "C" "D"

您可以通过标准矢量索引访问每个名称":

You can access each "name" by standard vector indexing:

> x[1]
[1] "A"

> x[2]
[1] "B"

> x[3]
[1] "C"

> x[4]
[1] "D"

这篇关于通过R进行Matlab单元阵列导入失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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