In my research, I primarily use R
, but I try to use existing code if available. In neuroimaging and other areas, that means calling MATLAB code. There are some existing solutions for the problem of R
to MATLAB: namely the R.matlab
package and the RMatlab package (which can call R
from MATLAB as well). I do not use thse solutions usually though.
Previously, Mandy Mejia wrote “THREE WAYS TO USE MATLAB FROM R”. Option 2 is about how to use R.matlab
, and Mandy gives and example with some cod. She also describes in Options 1 and 3 how to use the system
command to call MATLAB commands.
I like this strategy options because:
 I didn’t take the time to learn
R.matlab
.  It worked for me.
 I wrote a package to wrap the options Mandy described:
matlabr
.
matlabr: Wrapping together system calls to MATLAB
The matlabr
package is located in GitHub and you can install it with the following command:
devtools::install_github("muschellij2/matlabr")
It has a very small set of functions and I will go through each function and describe what they do:

get_matlab
: Mostly internal command that will return a character string that will be passed tosystem
. Ifmatlab
is in your PATH (bash variable), and you are using R based on the terminal, the command would return"matlab"
. If MATLAB is not in your PATH or using a GUIbased system like RStudio, you must setoptions(matlab.path='/your/path/to/matlab')
. 
have_matlab
: Wrapper forget_matlab
to return a logical ifmatlab
is found. run_matlab_script
: This will pass a.m
file to MATLAB. It also wraps the command in a trycatch statement in MATLAB so that if it fails, it will print the error message. Without this trycatch, if MATLAB errors, then running the command will remain in MATLAB and not return toR
.
run_matlab_code
: This takes a character vector of MATLAB code, ends lines with;
, writes it to a temporary.m
file, and then runsrun_matlab_script
on the temporary.m
file. 
rvec_to_matlab
: Takes in a numericR
vector and creates a MATLAB column matrix. 
rvec_to_matlabclist
: Takes in a vector fromR
(usually a character vector) and quotes these strings with single quotes and places them in a MATLAB cell using curly braces:{
and}
. It then stacks these cells into a “matrix” of cells.
Setting up matlabr
Let’s set up the matlab.path
as I’m running in RStudio:
library(matlabr) options(matlab.path = "/Applications/MATLAB_R2014b.app/bin") have_matlab()
The result from have_matlab()
indicates that the matlab
command can be called.
Let’s write some code to test it
Here we will create some code to take a value for x
, y
, z
(scalars) and a matrix named a
and then save x
, a
, z
to a text file:
code = c("x = 10", "y=20;", "z=x+y", "a = [1 2 3; 4 5 6; 7 8 10]", "save('test.txt', 'x', 'a', 'z', 'ascii')") res = run_matlab_code(code)
/var/folders/1s/wrtqcpxn685_zk570bnx9_rr0000gr/T//RtmpHnOinq/file2f8352c04937.m
Output
First off, we see that test.txt
indeed was written to disk.
file.exists("test.txt")
[1] TRUE
We can read in the test.txt
from using readLines
:
output = readLines(con = "test.txt") print(output)
[1] " 1.0000000e+01" [2] " 1.0000000e+00 2.0000000e+00 3.0000000e+00" [3] " 4.0000000e+00 5.0000000e+00 6.0000000e+00" [4] " 7.0000000e+00 8.0000000e+00 1.0000000e+01" [5] " 3.0000000e+01"
Conclusions
matlabr
isn’t fancy and most likely has some drawbacks as using system
can have some quirks. However, these functions have been helpful for me to use some SPM routines and other MATLAB commands while remaining “within R
“. R.matlab
has a better framework, but it may not be as straightforward for batch processing. Also matlabr
has some wrappers that will do a trycatch so that you don’t get stuck in MATLAB after calling system
.
Let me know if this was helpful or if you have ideas on how to make this better. Or better yet, give a pull request.
Pingback: R and Matlab  Ryo Eng ®
Thank you. I am using a windows 8 PC. I tried to implement the example code you provided. But got the error message. My code and output are as follows:
library(matlabr)
options(matlab.path = “C:/Program Files/MATLAB/R2013a/bin”)
have_matlab()
(It returns True)
code = c(“x = 10”,
“y=20;”,
“z=x+y”,
“a = [1 2 3; 4 5 6; 7 8 10]”,
“save(‘test.txt’, ‘x’, ‘a’, ‘z’, ‘ascii’)”)
res = run_matlab_code(code)
(The error output is
Warning messages:
1: running command ‘which matlab’ had status 127
2: running command ‘which matlab’ had status 127
3: running command ‘C:/Program Files/MATLAB/R2013a/bin/matlab nodesktop nosplash nodisplay r “try, run(‘C:\Users\Hairong\AppData\Local\Temp\RtmpSWfZiq\file12083a713ba8.m’); catch err, disp(err.message); exit(1); end; exit(0);”‘ had status 127 )
file.exists(“test.txt”)
(output is False)
Can you please check out what caused that if you have time?
Thanks,
Hairong
Sorry for the late reply, had to get a windows box up and running with matlab.
Please reinstall matlabr using:
devtools::install_github(“muschellij2/matlabr”)
##############################
#Test code
##############################
library(matlabr)
options(matlab.path=’C:\\Program Files\\MATLAB\\R2015b\\bin’)
verbose = TRUE
code = c(“x = 10;”,
“save(‘C:\\Users\\Windows7\\Desktop\\test.txt’, ‘x’, ‘ascii’)”)
run_matlab_code(code)
Now, the matlab command window will come up and run, but the R command returns the result as 0 if it can send the command. This isn’t ideal b/c R won’t wait for matlab to finish. I haven’t figured this out on a windows machine, and is likely a byproduct of me using the system command.
I hope that helps, albeit a noncomplete answer.
I notice that matlab command has an option wait can hold the matlab until finish.
Myabe this can help.
Hi, if my matlab code is in a file how should i write the code?
Hi, i am running matlab code to get genbank file, however i cannot get the txt file. Please explain to me. Thank you.
devtools::install_github(“muschellij2/matlabr”, force = TRUE)
library(matlabr)
options(matlab.path = “C:/Program Files/MATLAB/R2016b/bin”)
have_matlab()
run_matlab_script(hiv.mat)
code = c(“hiv=getgenbank(‘NC_001802′,’SequenceOnly’,true);”,
“save(‘hiv.txt’, ‘hiv’, ‘ascii’)”)
res = run_matlab_code(code)
file.exists(“hiv.txt”)
#system(“matlab nodisplay r ‘stuff; to; do; in; matlab;'”)
#set a variable in R and save in a csv file
output = readLines(con = “hiv.txt”)
print(output)
What is the output?
This is my output
> have_matlab()
[1] TRUE
> res = run_matlab_code(code)
C:\Users\user\AppData\Local\Temp\RtmpIZ8QUH\file119c41bd3090.m
> file.exists(“hiv.txt”)
[1] FALSE
> output = readLines(con = “hiv.txt”)
Error in file(con, “r”) : cannot open the connection
In addition: Warning message:
In file(con, “r”) : cannot open file ‘hiv.txt’: No such file or directory
What is the result of res?
Hi, I would like to askwhen I run the program, why the matlab command window shows the results will automatically shut down, is this normal? How to set up to avoid this situation.
Yes, this is normal. If you want an interactive session with matlab, you can simply run system(“matlab nodesktop nosplash nodisplay”) if you wanted to get an interactive mode from R.
After running the system function, the window will also automatically close.When I run the program ‘get_matlab(try_defaults = TRUE)’, the return result is “matlab.exe nodesktop nosplash nodisplay r “.Is there any relationship between the two result? Thank you!
OH,I find a solution.I set a pause function to force the process to suspend.Now I probably can use this package.Thank you very much!