How to use Matlab data in R?

Well, I have a matrix in Matlab with 4 dimensions. I would like to export this matrix to use it in R (I want to build with it). The problem for me is that I don’t know how to export a matrix that R can use, and also I don’t know how to import data into R. Basically, I tried to do this, export mine to Matlab using dlmwriteand import it into R with read.table(). Unfortunately this does not work.

+3
source share
1 answer

You can write any array to a binary using fwrite and read it in R using readBin. In R, which will give a vector that you can insert into the form using array () or matrix ().

Here is 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 can 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 order in Matlab and R. See native format for help with Matlab fwrite if your target systems are different.

+3
source

Source: https://habr.com/ru/post/1777685/


All Articles