A direct way to run R from Matlab is to run the R code as an External Command using RScript.exe.
Running R scripts has three steps:
writeMat) in Matlab using
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.
% Generate some random data x=randn(1,10); % Save the variable to an R formatted data file saveR('Data.R','x') % Get the current directory and switch slashes (R file pathes require '\') CurrentDirectory=strrep(pwd,'\','/'); % 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('Results.mat')
#Load required R.matlab package library(R.matlab) #Load data saved from Matlab source('Data.R') #Run one sample t test and save results TTestResults<-t.test(x,mu=0,conf.level=0.95) TTestP<-TTestResults$p.value TTestCI<-TTestResults$conf.int #Save results to Matlab data file writeMat('Results.mat', TTestP=TTestP, TTestCI=TTestCI)
library(R.matlab)can be loaded automatically each time R is launched by placing it in the Rprofile.site file.