Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Run a R script from Matlab [duplicate]

Tags:

r

matlab

I have .m file, using which I want to run a R script. How can I do this.

Matlab File

caller.m

%some matlab code

% need to call a R script

%some matlab code

R script

script.R 

some R code

I have both the files in the same folder.

How to run script.R from caller.m?


Answer by Drew Steen is in general true, as I found this on most of the places on web. But what worked for me, I am describing below:

Steps:

  1. Append "C:\Program Files\R\R-2.15.3\bin\x64" to "path" variable . This link provides procedure to set path in windows 7 os. Note that bin\x64 instead of bin, bin didn't worked for me.

  2. Restart Matlab.

  3. Use exec=system('Rscript.exe script.R') where the current script.R is in the current directory of matlab.

like image 734
Akashdeep Saluja Avatar asked Dec 10 '25 05:12

Akashdeep Saluja


1 Answers

You can use the system function in MATLAB to execute shell commands. Since you can run R from batch files,

executed = system('R CMD BATCH path/script.R')

should work. Note that path will need to be the correct relative path to your R script from whatever your active directory in MATLAB is. executed will evaluate as 0 if the system command executed successfully (which is not the same as the R script executing successfully).

like image 99
Drew Steen Avatar answered Dec 12 '25 17:12

Drew Steen