Learn R Programming

R.matlab (version 1.1.3)

Matlab: Matlab client for remote or local Matlab access

Description

Package: R.matlab Class Matlab Object ~~| ~~+--Matlab Directly known subclasses: public static class Matlab extends Object

Usage

Matlab(host="localhost", port=9999, remote=!(host %in% c("localhost", "127.0.0.1")))

Arguments

host
Name of host to connect to.
port
Port number on host to connect to.
remote
If TRUE, all data to and from the Matlab server will be transferred through the socket connection, otherwise the data will

Fields and Methods

Methods: rll{ as.character Gets a string describing the current Matlab connection. close Closes connection to Matlab server. evaluate Evaluates a Matlab expression. finalize Finalizes the object if deleted. getOption Gets the value of an option. getVariable Gets one or several Matlab variables. isOpen Checks if connection to the Matlab server is open. open Tries to open a connection to the Matlab server. readResult Reads results from the Matlab server. setFunction Defines a Matlab function. setOption Sets the value of an option. setVariable Sets one or several Matlab variables. setVerbose Sets the verbose level to get more details about the Matlab access. startServer Static method which starts a Matlab server. writeCommand Writes (sends) a command to the Matlab server. } Methods inherited from Object: $, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clone, detach, equals, extend, finalize, gc, getEnvironment, getFields, getInstanciationTime, getStaticInstance, hasField, hashCode, ll, load, objectSize, print, save

Requirements

In order for Rto communicate with Matlab, Matlab v6 or higher is needed. It will not work with previous versions, because they do not support Java! We use the term server to say that Matlab acts like a server with regard to R. Note that it a standard Matlab session that runs. Also, the starting of the MatlabServer is simplier from Matlab v7, although it is pretty straightforward for Matlab v6 too (this has to do with the fact that in Matlab v7, the for remote-data-transfer required Java class can be dynamically added to the Matlab Java classpath).

Remote and non-remote connections

When a remote connection (argument remote=TRUE) is used, data is send to and from Matlab via a data stream. This is needed when Ris running on a host with a seperated file system than the one Matlab is running on. If not connection "remotely" (remote=FALSE), data is communicated via the file system, that is, by saving and reading it to temporary MAT files. Troubleshooting: If "remote" transfers are used, the InputStreamByteWrapper Java class must be found by Matlab, otherwise an error will occur in Matlab as soon as data is send from Rto Matlab. In all other cases, the above Java class is not needed.

Starting the Matlab server from within R

The Matlab server may be started from within Rby calling Matlab$startServer(). By default 'matlab' is called; if named differently set options(matlab="matlab6.5"), say. The method is experimental and may not work on your system. By default the Matlab server listens for connections on port 9999. For other ports, set argument port, e.g. Matlab$startServer(port=9998). Note that the code will not halt and wait for Matlab to get started. Thus, you have to make sure you will wait long enough for the server to get up and running before the Rclient try to connect. By default, the client will try once a second for 30 seconds before giving up. Moreover, on non-Windows systems, the above command will start Matlab in the background making all Matlab messages be sent to the Routput screen. In addition, the method will copy the MatlabServer and InputStreamByteWrapper files to the current directory and start Matlab from there.

Starting the Matlab server without R

If the above does not work, the Matlab server may be started manually from Matlab itself. Please follow the below instructions carefully. To be done once: In Matlab, add the path to the directory where MatlabServer.m sits. See help pathtool in Matlab on how to do this. In R you can type system.file("externals", package="R.matlab") to find out the path to MatlabServer.m. For Matlab v6 only: Contrary to Matlab v6, Matlab v6 cannot find the InputStreamByteWrapper class automatically. Instead, the so called Java classpath has to be set. In Matlab, type which('classpath.txt') to find where the default Matlab classpath.txt file is located. Copy this file to the current directory and append the path (the directory) to InputStreamByteWrapper.class file, which is the same as the path of the MatlabServer.m you identified above. Lazy alternative: Instead of setting path and classpaths, you may try to copy the MatlabServer.m and InputStreamByteWrapper.class to the current directory from which Matlab is then started. To start the server: In order to start the Matlab server, type matlab -nodesktop -nosplash -r MatlabServer If using Matlab v6, make sure your classpath.txt is the current directory! This will start Matlab and immediately call the MatlabServer(.m) script. Here is how it should look like when the server starts: < M A T L A B > Copyright 1984-2004 The MathWorks, Inc. Version 7.0.1.24704 (R14) Service Pack 1 September 13, 2004 To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com. Matlab v7.x or higher detected. Saving with option -V6. Added InputStreamByteWrapper to dynamic Java CLASSPATH. ---------------------- Matlab server started! ---------------------- Trying to open server socket (port 9999)...done. Alternatively you can start Matlab and type MatlabServer at the prompt. By default the Matlab server listens for connections on port 9999. For other ports, set environment variable MATLABSERVER_PORT.

Confirmed Matlab versions

This package has been confirmed to work successfully out of the box together with Matlab v6.1.0.450 (R12.1), Matlab v6.5.0.180913a (R13), Matlab v7.0.0.19901 (R14), Matlab v7.0.1.24704 (R14SP1), Matlab v7.0.4.365 (R14SP2), and Matlab v7.2.0.232 (R2006a). [If you successfully use a higher Matlab version, please tell us, so we can share it here.] It does not work with Matlab v5 or before!

Security

There is no security in the communication with the Matlab server. This means that if you start the Matlab server, it will wait for requests via the connection at the specified port. As long as your Rsession has not connected to this port, others may be able to steal the connection and send malicious commands (if they know the R.matlab protocol). The Matlab server only allows one connection. In other words, if you are connected it is not possible for others to connect to the Matlab server.

Matlab server is timing out

It might be that an *evaluate() call to the Matlab server takes a long time for the server to finish resulting in a time-out exception. By default this happens after 30 seconds, but it can be changed by modifying options, cf. setOption().

See Also

Stand-alone methods readMat() and writeMat() for reading and writing MAT file structures.

Examples

Run this code
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# This example will try to start the Matlab server on the local machine,
# and then setup a Matlab object in R for communicating data between R
# and Matlab and for sending commands from R to Matlab.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Start Matlab server on the local machine (if this fails,
# see help(Matlab) for alternatives).
Matlab$startServer()

# Create a Matlab client object used to communicate with Matlab
matlab <- Matlab()

# If you experience any problems, ask for detailed outputs
# by uncommenting the next line
# setVerbose(matlab, -2)

# Connect to the Matlab server, which must already be running
if (!open(matlab))
  throw("Matlab server is not running: waited 30 seconds.")

# Run Matlab expressions on the Matlab server
evaluate(matlab, "A=1+2;", "B=ones(2,20);")

# Get Matlab variables
data <- getVariable(matlab, c("A", "B"))
cat("Received variables:\n")
str(data)

# Set variables in Matlab
ABCD <- matrix(rnorm(10000), ncol=100)
str(ABCD)
setVariable(matlab, ABCD=ABCD)

# Retrieve what we just set
data <- getVariable(matlab, "ABCD")
cat("Received variables:\n")
str(data)

# Create a function (M-file) on the Matlab server
setFunction(matlab, "          \
  function [win,aver]=dice(B)  \
  %Play the dice game B times  \
  gains=[-1,2,-3,4,-5,6];      \
  plays=unidrnd(6,B,1);        \
  win=sum(gains(plays));       \
  aver=win/B;                  \
");

evaluate(matlab, "[w,a]=dice(1000);")
res <- getVariable(matlab, c("w", "a"))
print(res)

# When done, close the Matlab client, which will also shutdown
# the Matlab server and the connection to it.
close(matlab)

Run the code above in your browser using DataLab