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.
csvread functions in Matlab, and the corresponding
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 allows you to run terminal commands using the
! operator, or the OS-specific
unix commands. Thus, to read some data, run an R script, then read back the data written by R is as simple as:
csvwrite('in.csv',[originaldat]); !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.
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 library("rjags") library("coda") 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,progress.bar="gui") #Capture and dump to out file data <- data.frame(summary(thesamps)) write.csv(data,'out.csv')
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.