Roller Blind | Anti Rayap | Pest Control | GPS Tracker
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:
saveR.writeMat) 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.
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)
library(R.matlab) can be loaded automatically each time R is launched by placing it in the Rprofile.site file.