开发者

How to use Matlab data in R?

Well I have a matrix in Matlab, with 4 dimensions. I'd like to export this matrix to use it in R (I want to plot with it). The problem for me is that I don't know how to export a matrix that 开发者_开发百科can be used by R, and also I don't know how to import data in R. Basically, what I've tried to do is to export my matrix in Matlab using dlmwrite, and importing it in R using read.table(). Unfortunately this isn't working.


You can write out any array to binary with fwrite, and read it into R with readBin. In R that will give a vector that you can push into shape with array() or matrix().

Here's a very simple example.

a = magic(4)

con = fopen('a.bin', 'w');
fwrite(con, a * 0.01, 'float64')
fclose(con)

a * 0.01

ans =

0.1600 0.0200 0.0300 0.1300

0.0500 0.1100 0.1000 0.0800

0.0900 0.0700 0.0600 0.1200

0.0400 0.1400 0.1500 0.0100

Now in R:

 matrix(readBin("a.bin", "double", 16), 4)

[,1] [,2] [,3] [,4]

[1,] 0.16 0.02 0.03 0.13

[2,] 0.05 0.11 0.10 0.08

[3,] 0.09 0.07 0.06 0.12

[4,] 0.04 0.14 0.15 0.01

You could replace "a" with a 4D array, and change the R code to this and it should work just as well:

## assume 4 dimensions with particular sizes
dims <- c(10, 5, 2, 3)
a <- array(readBin("a.bin", "double", prod(dims)), dims)

Finally, note that this assumes the same byte ordering in Matlab and R. See machineformat in the Matlab fwrite help if your end systems are different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜