0

I have a Matlab function that finds the path where this function is within my pc and then runs a bat file on that same directory. This bat file is meant to execute an R script but for a strange reason is failing to do so.

This is my Matlab function:

function [] = myFunction(arg)

  % Find the directory of the executing script
  thisDir = fileparts(mfilename('fullpath'));

  % Save arg as a csv on this directory, this will be read by my R script
  tmpDir = strcat(thisDir,'/tmp.csv');
  csvwrite(tmpDir,arg);

  % Specify the command to run
  dosCommand = ['call "' thisDir '/runRscript.bat"'];
  dos(dosCommand);

end

The bat file has the following code:

"C:\Program Files\R\R-3.2.2\bin\x64\R.exe" CMD BATCH runRScipt.R

When I run the function in Matlab I get the below message:

C:\Users\...mypath...>"C:\Program Files\R\R-3.2.2\bin\x64\R.exe" CMD BATCH runRscript.R

Since I get this message in Matlab I have no doubt it is finding and reading the batch file, but it fails to execute the R script. I know the bat file works as expected since I can run it through the command line (with the command that should be the "dosCommand" on the Matlab script) or by clicking twice on the .bat file.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
Victor
  • 1,163
  • 4
  • 25
  • 45
  • 1
    [This](http://stackoverflow.com/questions/14167178/passing-command-line-arguments-to-r-cmd-batch) might be related. Also there seems to be a specific package for it, see [here](http://www.mathworks.com/matlabcentral/answers/31708-running-r-within-matlab). – Steve Heim May 13 '16 at 05:27

2 Answers2

0

Instead of R.exe please try Rscript.exe. R.exe runs R code in interactive mdoe while Rscript runs the code in batch mode. Ideally you should find Rscript executable in the same path as in R executable (i.e. "C:\Program Files\R\R-3.2.2\bin\x64" in your case)

abhiieor
  • 3,132
  • 4
  • 30
  • 47
  • Thanks for your answer @abhiieor. Rscript.exe is on the same path, but even if I change it, I still can't execute it from Matlab. Furthermore, with this change the batch file no longer executes the R script by double clicking it. – Victor May 18 '16 at 03:38
0

I found the answer. For a strange reason the dos() command would not work, but the system() command will do the job. Then the code will look like this:

function [] = myFunction(arg)

  % Find the directory of the executing script
  thisDir = fileparts(mfilename('fullpath'));

  % Save arg as a csv on this directory, this will be read by my R script
  tmpDir = strcat(thisDir,'/tmp.csv');
  csvwrite(tmpDir,arg);

  % Specify the command to run
  sysCommand = ['call "' thisDir '/runRscript.bat"'];
  system(sysCommand);

end

And the batch file:

"C:\Program Files\R\R-3.2.2\bin\x64\R.exe" CMD BATCH runRScipt.R

Victor
  • 1,163
  • 4
  • 25
  • 45