0

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

Matlab Code:

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

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

R Code:

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

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

MMCM_
  • 617
  • 5
  • 18

1 Answers1

0

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"

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 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"
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • Thanks a lot for the work around. I mean it fails in the sense that a cell array of strings is not parsed in the sense of the actual matlab structure. I think one can say that a vector of names is the equivalent representation in R. I'll raise an issue on GitHub r.matlab, maybe something worth improving in the future – MMCM_ Mar 29 '15 at 12:33
  • Ah I understand. Gotcha. OK well if my answer did help you, consider accepting my answer. Thanks and good luck! – rayryeng Mar 30 '15 at 01:29