Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Authors@R: c(
person("Adam", "Lyon", role = "aut"),
person("Yalei", "Du", role = "aut")
)
Suggests: R.matlab
Maintainer: Yihui Xie <xie@yihui.name>
License: GPL
URL: https://github.com/yihui/runr
Expand Down
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ S3method(print,runr_results)
export(proc_bash)
export(proc_julia)
export(proc_python)
export(proc_matlab)
59 changes: 59 additions & 0 deletions R/matlab.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#' Run a matlab process
#'
#' This function returns a list of functions to start/run/stop a matlab process.
#' The code is sent to matlab via a socket connection, and the results are
#' written back in another socket connection.
#' @param port A TCP port number
#' @return A list of functions \code{start()}, \code{exec()}, \code{running()}
#' (check if the process has been running), and \code{stop()}.
#' @export
#' @examples \dontrun{
#' mat = proc_matlab()
#' mat$start()
#' mat$exec('1+1')
#' mat$exec('x = 1 + 1; x = x + x; x;') # return nothing
#' mat$exec('x = 1 + 1\n x = x + x\n x') # return nothing
#' mat$exec('5:9') # [ 5 6 7 8 9]
#' mat$exec('x = 1; while x < 10\n disp(x);\n x = x + 1;\n end') #Prints numbers 1 to 9
#' mat$running() # should be TRUE
#' mat$stop()
#' }

proc_matlab <- function(port = 6011){
matlab <- NULL
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll appreciate it if you use = for assignment consistently.

exec_code = function(...){
if (is.null(matlab)) stop('the process has not been started yet')
code = as.character(c(...))
result = sapply(code, function(x) R.matlab::evaluate(matlab, x, capture=TRUE))
return(do.call(paste, c(as.list(result), sep = "\n")))
}

list(
start = function() {
if (!is.null(matlab)) {
warning('the program has been started')
return(invisible())
}
R.matlab::Matlab$startServer(port=port)
matlab <<- R.matlab::Matlab(port=port)
isOpen = open(matlab, trials=30, interval = 0, timeout = 1)
if(!isOpen)
{
stop("Unable to connect to matlab server")
}
invisible()
},

exec = exec_code,

running = function() !is.null(matlab),

stop = function() {
close(matlab)
matlab <<- NULL
invisible()
}
)
}