Calling R from Matlab – flat file communication

In the last post I showed how to fit a Bayesian hierarchical model in R to estimate experimental parameters. Our main data analysis pipeline uses Matlab, and we’d like to integrate these two environments for the purpose of analysis.

The example involved JAGS, which does have a direct Matlab interface in addition to the more common R one, but more generally you might need to use some unique package  for an analysis that only runs in R. So how can you pipe your data from Matlab to R and back?

Flat file communication

There are a variety of unofficial interfaces between Matlab and R – you can call R from Matlab on Windows via a COM extension, or you can spawn Matlab engines and manipulate .mat files in R – but the very simplest communication involves writing your data in flat files, and loading them on the other end.

The csvwrite and csvread functions in Matlab, and the corresponding read.csv and write.csv functions in R are really all you need. Be aware, however, that Matlab’s built-in CSV reading function doesn’t support headers or string variables. You can pick up this more fancy version from the Matlab File Exchange that does.

Matlab side

Matlab allows you to run terminal commands using the ! operator, or the OS-specific dos and unix commands. Thus, to read some data, run an R script, then read back the data written by R is as simple as:

!R CMD BATCH /home/username/Documents/script.r
dat = csvread('out.csv',1,1);

Matlab will block until R returns, so you don’t need to worry about asynchronous callbacks.

R side

On the R side, you need a batch script that reads the data, transforms it, and then writes it back. For our previous example, this would look like:

rawdat <- read.csv('in.csv',header=FALSE)

#Extract the data we need
ms <- rawdat[,1]
stds <- rawdat[,3]

#Run the MCMC model
jagresult <- jags.model('slices.model',data=list('ms'=ms,'stds'=stds,'N'=length(ms)),n.adapt = 10000)
thesamps <- coda.samples(jagresult,c('mu','tau','realmean'),n.iter=100000,thin=10,"gui")

#Capture and dump to out file
data <- data.frame(summary(thesamps))


And that’s pretty much all there is to it. You can use a similar process to call Python from Matlab. See also this post about reading pickle files in Matlab.

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s