Table of Contents

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:

- Pass data from Matlab to R using
`saveR`

. - Execute an R script file (which saves the desired results using
`writeMat`

) in Matlab using`!`

. - 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.

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

`Script.m`

% 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')

`Commands.R`

#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)

- 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 Rprofile.site file.