Running R Scripts From Matlab


A direct way to run R from Matlab is to run the R code as an External Command using RScript.exe.

To run R scripts from Matlab, download the Matlab File Exchange file saveR and install the R package R.matlab.

Running R scripts has three steps:

  1. Pass data from Matlab to R using saveR.
  2. Execute an R script file (which saves the desired results using writeMat) in Matlab using !.
  3. Import the results in Matlab using load.

Using this method, four files are used:

  • Script.m - The Matlab script file that manipulates the data, saves the data in an R formatted file, calls the R script, and loads the results for further analysis.
  • Data.R - An R formatted data file saved by Matlab.
  • Commands.R - An R script file that loads the data, performs analysis, and saves the results in a Matlab formatted file.
  • Results.mat - A Matlab formatted data file saved by R.

Example Code

The following example performs a simple one-sample t test and passes the p-value and confidence interval back to Matlab. Atap fiberglass, Properti semarang, Gps tracking orang, Gps tracker mobil


% Generate some random data
% Save the variable to an R formatted data file
% Get the current directory and switch slashes (R file pathes require '\')
% Run script in R (note that the file path cannot contain any spaces), the paths could also be written out directly for each script 
eval(['!C:/PROGRA~1/R/R-2.15.0/bin/Rscript ' CurrentDirectory '/Commands.R'])
% Load the results from R


#Load required R.matlab package
#Load data saved from Matlab
#Run one sample t test and save results
#Save results to Matlab data file

Other Information

  • An alternative is to use a COM interface (Install the COM Package with Matlab R-link) to call R directly from Matlab, however that method has difficulty parsing many commands, has difficulty dealing with NaN versus NA values, and is more complicated to set up properly.
  • R and Matlab have quite different data structures, so it can be difficult transferring complicated variables (especially Matlab structures or R lists) back and forth. It is best to stick to passing basic variables (scalars, vectors, matrices, and cell arrays of strings).
  • The call library(R.matlab) can be loaded automatically each time R is launched by placing it in the file.
tips/callingr/matlab.txt · Last modified: 2014/04/03 by baratumz
Recent changes RSS feed R Wiki powered by Driven by DokuWiki and optimized for Firefox Creative Commons License