1

I would like to use Rscript from MATLAB, and I want to send a matrix to Rscript by command line. I have read this post, but examples in this post were just passed number or small matrix or arrary. So my question is how to pass a matrix to Rscript by command line. Thank you in advance!

Code in MATLAB:

data=dlmread('test.txt')
data =

     5     5   477
     5   300   696
     5   595   227
   195     5   646
   195   300   606
   195   595   783

system('Rscript.exe test.R data');

Code in R:

options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)

if(length(args)==0)
  {
    print("No arguments supplied.")
  }
print(args)

a1 <- as.numeric(args[1])

a1 <- data.frame(a1)
print(a1)
Community
  • 1
  • 1
Just Rookie
  • 209
  • 3
  • 8

1 Answers1

1

I don't think matlab can pass data to the stdin of a command called with system. Your options then are:

  1. Write the data out to a file in a way that can be read in within the Rscript process (e.g. csv). This could potentially be a temporary file, and the filename could be passed as the argument to the R script.
  2. Encode the data in a cross-program way that can be passed as a command-line argument (e.g. JSON). However, this is likely to be much harder to implement successfully, and you may run into issues of maximum line length for commands.
  3. Encode the data as an R expression that can be evaluated within R (e.g. matrix(c(1, 4, 5, 2, 9, 7), nrow = 3) along the lines of the question you yourself linked to .

Unless there's a very good reason, I'd go with option 1.

Community
  • 1
  • 1
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52