Refs:

Package R.matlab connects to an existing Matlab installation (version >= 6) and is able to transfer data from R to Matlab and vice-versa.

library(R.matlab)
## R.matlab v3.3.0 (2015-09-22) successfully loaded. See ?R.matlab for help.
## 
## Attaching package: 'R.matlab'
## 
## The following objects are masked from 'package:base':
## 
##     getOption, isOpen

The next function initializes Matlab and returns a handler (it may take 30-60 seconds):

getContext <- function() {
  
  Matlab$startServer()   # start the matlab server
  matlab <- Matlab()     # create a Matlab client
  
  if (!open(matlab))
    throw("Matlab server is not running: waited 30 seconds.")

  matlab                 # return the matlab handler
}

matlab <- getContext()

The next code shows egs of use:

x <- 10
setVariable(matlab, x = x)        # set a var into Matlab workspace
evaluate(matlab, "y=20; z=x+y")   # evaluates an expression in Matlab
res <- getVariable(matlab, "z")   # get var's value
res$z[1,1]
## [1] 30

evaluate(matlab, "B=ones(2,10);")

data <- getVariable(matlab, c("x", "z", "B"))  # we can get 1+ vars
data$x
##      [,1]
## [1,]   10
data$z
##      [,1]
## [1,]   30
data$B
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,]    1    1    1    1    1    1    1    1    1     1
## [2,]    1    1    1    1    1    1    1    1    1     1

It’s possible to define functions and export them to Matlab:

setFunction(matlab, "
  function y=average(x)
    y = sum(x)/length(x);
")

evaluate(matlab, "av=average([1 2 4 7]);")
res <- getVariable(matlab, "av")
res$av
##      [,1]
## [1,]  3.5

setFunction(matlab, "
  function [y1,y2]=my_f(x1,x2)
    y1=x1+x2;
    y2=x1-x2;
")

evaluate(matlab, "[z1,z2]=my_f(3,5);")
res <- getVariable(matlab, c("z1","z2"))
res$z1
##      [,1]
## [1,]    8
res$z2
##      [,1]
## [1,]   -2

To close Matlab:

close(matlab)