R Matlab
R Matlab
matlab Package
April 11, 2007
Version 1.1.3
Date 2007-04-07
Title Read and write of MAT files together with R-to-Matlab connectivity
Suggests R.utils
Description This package provides methods to read and write MAT files. It also makes it possible to
communicate (evaluate code, send and retrieve objects etc.) with Matlab v6 or higher running
locally or on a remote host.
URL http://www.braju.com/R/
DevelURL http://www.maths.lth.se/help/R/
LazyLoad TRUE
R topics documented:
1. The Matlab server running in Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Non-documented objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
R.matlab-package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Sys.setenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
as.character.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
close.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
evaluate.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
finalize.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
getOption.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
getVariable.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1
2 1. The Matlab server running in Matlab
isOpen.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
open.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
readMat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
readResult.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
setFunction.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
setOption.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
setVariable.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
setVerbose.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
startServer.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
writeCommand.Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
writeMat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Index 36
Description
This section gives addition details on the Matlab server. At the end, the MatlabServer.m script and
the InputStreamByteWrapper.java code is shown.
MatlabServer.m script
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MatlabServer
%
% This scripts starts a minimalistic Matlab "server".
%
% When started, the server listens for connections at port 9999 or the
% port number specified by the environment variable 'MATLABSERVER_PORT'.
%
% Troubleshooting: If not working out of the box, add this will to the
% Matlab path. Make sure InputStreamByteWrapper.class is in the same
% directory as this file!
%
% Requirements:
% This requires Matlab with Java support, i.e. Matlab v6 or higher.
%
% Author: Henrik Bengtsson, 2002-2006
1. The Matlab server running in Matlab 3
%
% References:
% [1] http://www.mathworks.com/access/helpdesk/help/techdoc/
% matlab_external/ch_jav34.shtml#49439
% [2] http://staff.science.uva.nl/~horus/dox/horus2.0/user/
% html/n_installUnix.html
% [3] http://www.mathworks.com/access/helpdesk/help/toolbox/
% modelsim/a1057689278b4.html
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% addpath R/R_LIBS/linux/library/R.matlab/misc/
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Matlab version-dependent setup
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
isVersion7 = eval('length(regexp(version, ''^7'')) ~= 0', '0');
if (~isVersion7)
disp('Matlab v6.x detected.');
% Default save option
saveOption = '';
% In Matlab v6 only the static Java CLASSPATH is supported. It is
% specified by a 'classpath.txt' file. The default one can be found
% by which('classpath.txt'). If a 'classpath.txt' exists in the
% current(!) directory (that Matlab is started from), it *replaces*
% the global one. Thus, it is not possible to add additional paths;
% the global ones has to be copied to the local 'classpath.txt' file.
%
% To do the above automatically from R, does not seem to be an option.
else
disp('Matlab v7.x or higher detected.');
% Matlab v7 saves compressed files, which is not recognized by
% R.matlab's readMat(); force saving in old format.
saveOption = '-V6';
disp('Saving with option -V6.');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Import Java classes
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import java.io.*;
4 1. The Matlab server running in Matlab
import java.net.*;
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% If an old Matlab server is running, close it
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% If a server object exists from a previous run, close it.
if (exist('server'))
close(server);
clear server;
end
fprintf(1, '----------------------\n');
fprintf(1, 'Matlab server started!\n');
fprintf(1, '----------------------\n');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Initiate server socket to which clients may connect
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
port = getenv('MATLABSERVER_PORT');
if (length(port) > 0)
port = str2num(port);
else
% Try to open a server socket on port 9999
port = 9999;
end
% Ports 1-1023 are reserved for the Internet Assigned Numbers Authority.
% Ports 49152-65535 are dynamic ports for the OS. [3]
if (port < 1023 | port > 65535)
error('Cannot not open connection. Port (''MATLABSERVER_PORT'') is out of range [
end
fprintf(1, 'done.\n');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Wait for client to connect
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Create a socket object from the ServerSocket to listen and accept
% connections.
% Open input and output streams
% ...client connected.
is = DataInputStream(getInputStream(clientSocket));
%is = BufferedReader(InputStreamReader(is0));
os = DataOutputStream(getOutputStream(clientSocket));
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% The Matlab server state machine
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Commands
commands = {'eval', 'send', 'receive', 'send-remote', 'receive-remote', 'echo'};
%-------------------
% 'eval'
%-------------------
elseif (state == strmatch('eval', commands, 'exact'))
bfr = char(readUTF(is));
fprintf(1, '"eval" string: "%s"\n', bfr);
try
eval(bfr);,
6 1. The Matlab server running in Matlab
writeByte(os, 0);
fprintf(1, 'Sent byte: %d\n', 0);
flush(os);
catch,
fprintf(1, 'EvaluationException: %s\n', lasterr);
writeByte(os, -1);
fprintf(1, 'Sent byte: %d\n', -1);
writeUTF(os, lasterr);
fprintf(1, 'Sent UTF: %s\n', lasterr);
flush(os);
end
flush(os);
state = 0;
%-------------------
% 'send'
%-------------------
elseif (state == strmatch('send', commands, 'exact'))
tmpname = sprintf('%s.mat', tempname);
expr = sprintf('save %s %s', tmpname, saveOption);
ok = 1;
for k=1:length(variables),
variable = variables{k};
if (exist(variable) ~= 1)
lasterr = sprintf('Variable ''%s'' not found.', variable);
ok = 0;
break;
end;
expr = sprintf('%s %s', expr, variable);
end;
if (~ok)
writeInt(os, -1);
writeUTF(os, lasterr);
else
disp(expr);
eval(expr);
writeUTF(os, tmpname);
end
answer = readByte(is);
fprintf('answer=%d\n', answer);
state = 0;
%-------------------
% 'send-remote'
%-------------------
elseif (state == strmatch('send-remote', commands, 'exact'))
1. The Matlab server running in Matlab 7
answer = readByte(is);
fprintf('answer=%d\n', answer);
state = 0;
%-------------------
% 'receive-remote'
%-------------------
8 1. The Matlab server running in Matlab
reader = InputStreamByteWrapper(4096);
bfr = [];
count = 1;
while (len > 0 & count > 0)
count = reader.read(is, min(4096, len));
if (count > 0)
bfr = [bfr; reader.bfr(1:count)];
len = len - count;
end;
end;
load(tmpfile);
delete(tmpfile);
clear tmpfile;
writeByte(os, 0);
state = 0;
%-------------------
% 'receive'
%-------------------
elseif (state == strmatch('receive', commands, 'exact'))
filename = char(readUTF(is));
fprintf(1, 'Will read MAT file: "%s"\n', filename);
load(filename);
clear filename;
writeByte(os, 0);
state = 0;
end
end
1. The Matlab server running in Matlab 9
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Shutting down the Matlab server
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fprintf(1, '-----------------------\n');
fprintf(1, 'Matlab server shutdown!\n');
fprintf(1, '-----------------------\n');
writeByte(os, 0);
close(os);
close(is);
close(server);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HISTORY:
% o Extended the accepted range of ports from [1023,49151] to [1023,66535].
% 2006-05-08
% o BUG FIX: The error message string for reporting port out of range
% was invalid and gave the error '... Line: 109 Column: 45 ")" expected,
% "identifier" found.'. Thanks Alexander Nervedi for reporting this.
% 2006-01-21
% o Now an error is thrown if port number is out of (safe) range.
% o Added option to specify the port number via the system environment
% variable MATLABSERVER_PORT, after request by Wang Yu, Iowa State Univ.
% 2005-03-08
% o BUG FIX: substring() is not recognized by Matlab v7. Using regexp()
% which works in Matlab 6.5 and 7. Workaround eval('try', 'catch').
% Thanks Patrick Drechsler, University of Wuerzburg for the bug report.
% 2005-02-24
% o Now the dynamic Java classpath is set for Matlab v7 or higher. This
% will simplify life for Matlab v7 users.
% 2005-02-22
% o Added javaaddpath() to include InputStreamByteWrapper.class.
% Thanks Yichun Wei for feedback and great suggestions.
% 2005-02-11
% o If Matlab v7 or higher is detected, all MAT structures are saved with
% option '-V6' so readMat() in R.matlab can read them.
% 2002-09-02 [or maybe a little bit earlier]
% o Created.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
InputStreamByteWrapper.(class|java) script
The Java class InputStreamByteWrapper is needed in order for Matlab to receive data via a data
stream. R sends data via a data stream if, and only if, the connection was setup for "remote"
10 1. The Matlab server running in Matlab
import java.io.*;
/*********************************************************************
% Compile from within Matlab with:
% !javac InputStreamByteWrapper.java
% Matlab example that reads a file using Java code and writes it
% back to a temporary file using Matlab code. Finally the contents
% of the new file is displayed.
in = java.io.FileInputStream('InputStreamByteWrapper.java');
bfr = [];
len = 1;
while (len > 0)
len = reader.read(in, 16); % Read 16 bytes at the time (offset=0).
if (len > 0)
bfr = [bfr; reader.bfr(1:len)]; % Add bytes to my Matlab buffer.
end
end
close(in);
clear in, reader;
disp(bfr');
tmpfile = tempname;
fh = fopen(tmpfile, 'wb');
fwrite(fh, bfr, 'char');
fclose(fh);
type(tmpfile);
*********************************************************************/
public class InputStreamByteWrapper {
public static byte[] bfr = null;
public InputStreamByteWrapper() {
this(4096);
}
Matlab 11
public int read(InputStream in, int offset, int length) throws IOException {
return in.read(bfr, offset, length);
}
/*********************************************************************
HISTORY:
2002-09-02 [or maybe a little bit earlier]
o Created.
*********************************************************************/
Description
Package: R.matlab
Class Matlab
Object
~~|
~~+--Matlab
Usage
Matlab(host="localhost", port=9999, remote=!(host %in% c("localhost", "127.0.0.1"))
12 Matlab
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 be transferred via a temporary
file.
Requirements
In order for R to 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 straightfor-
ward 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).
Matlab 13
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 R to Matlab.
In all other cases, the above Java class is not needed.
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
If using Matlab v6, make sure your classpath.txt is the current directory!
14 Matlab
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
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.
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 R
session 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.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
Stand-alone methods readMat() and writeMat() for reading and writing MAT file structures.
Examples
## Not run:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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()
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)
## End(Not run)
Non-documented objects
Non-documented objects
Description
This page contains aliases for all "non-documented" objects that R CMD check detects in this
package.
Almost all of them are generic functions that have specific document for the corresponding method
coupled to a specific class. Other functions are re-defined by setMethodS3() to default methods.
Neither of these two classes are non-documented in reality. The rest are deprecated methods.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
Description
This package provides methods to read and write MAT files. It also makes it possible to communi-
cate (evaluate code, send and retrieve objects etc.) with Matlab v6 or higher running locally or on a
remote host.
In brief, this package provides a one-directional interface from R to Matlab, with communication
taking place via a TCP/IP connection and with data transferred either through another connection or
via the file system. On the Matlab side, the TCP/IP connection is handled by a small Java add-on.
The methods for reading and writing MAT files are stable. The R to Matlab interface, that is the
Matlab class, is less prioritized and should be considered a beta version.
For package history, see showHistory(R.matlab).
R.matlab-package 17
Requirements
This is a cross-platform package implemented in plain R. This package depends on the R.oo pack-
age [1].
To use the Matlab class or requesting verbose output messages, the R.utils package is loaded when
needed (and therefore required at in those cases).
The readMat() and writeMat() methods do not require a Matlab installation neither do they
depend on the Matlab class.
To connect to Matlab, Matlab v6 or higher is required. It does not work with Matlab v5 or before
(because there those version does not support Java). For confirmed Matlab versions, see help() on
the "Matlab" class.
Installation
To install this package do
install.packages("R.matlab")
Required packages are installed in the same way.
To get the "devel" version, see http://www.braju.com/R/.
To get started
To get started, see:
1. readMat() and writeMat() - For reading and writing MAT files (Matlab is not needed).
2. Matlab - To start Matlab and communicate with it from R.
Miscellaneous
A related initiative is RMatlab by Duncan Temple Lang and Omegahat. It provides a bi-directional
interface between the R and Matlab languages. For more details, see http://www.omegahat.
org/RMatlab/. To call R from Matlab on Windows (only), see MATLAB R-link by Robert Hen-
son available at the Matlab Central File Exchange (http://www.mathworks.com/matlabcentral/
fileexchange/loadFile.do?objectId=5051).
@TECHREPORT{BengtssonH_2005,
author = {Bengtsson, Henrik},
title = {{R.matlab} - Local and remote {M}atlab connectivity in {R}},
institution = {Mathematical Statistics, Centre for Mathematical Sciences,
Lund University, Sweden},
year = {2005},
type = {{Preprint in Mathematical Sciences (manuscript in progress)}},
note = {[manuscript in progress]},
18 R.matlab-package
url = {http://www.maths.lth.se/help/R/R.matlab/},
}
Troubleshooting
In general:
For trouble shooting in general, rerun erroneous function with verbose/debug messages turned on.
For readMat() and writeMat() see their help. For communication with a Matlab server, use
The lower the threshold is the more information you will see.
Wishlist
Here is a list of features that would be useful, but which I have too little time to add myself. Con-
tributions are appreciated.
• Wrap up common Matlab commands as methods of the Matlab class, e.g. who(matlab),
clear(matlab) etc. Can this be done automatically using "reflection", so that required
arguments are automatically detected?
• Add support for reading (and writing) sparse matrices to be represented by the sparse matrix
class defined in the SparseM package.
• Add access to Matlab variables via "$" and "$<-", e.g. matlab$A and matlab$A <-
1234. Is this wanted? Maybe the same for functions, e.g. matlab$dice(1000). Is it
possible to return multiple return values?
If you consider implement some of the above, make sure it is not already implemented by down-
loading the latest "devel" version!
Acknowledgements
Thanks to the following people who contributed with valuable feedback, suggestions, and code:
License
The releases of this package is licensed under LGPL version 2.1 or newer.
The development code of the packages is under a private licence (where applicable) and patches sent
to the author fall under the latter license, but will be, if incorporated, released under the "release"
license above.
References
1 H. Bengtsson, The R.oo package - Object-Oriented Programming with References Using Standard R
Code, In Kurt Hornik, Friedrich Leisch and Achim Zeileis, editors, Proceedings of the 3rd Interna-
tional Workshop on Distributed Statistical Computing (DSC 2003), March 20-22, Vienna, Austria.
http://www.ci.tuwien.ac.at/Conferences/DSC-2003/Proceedings/
[2] Henrik Bengtsson, R.matlab - Local and remote Matlab connectivity in R, Mathematical Statis-
tics, Centre for Mathematical Sciences, Lund University, Sweden, 2005. (manuscript in progress).
Author(s)
Sys.setenv Sys.setenv
Description
If you searched for help on Sys.setenv but got this page instead, you are most likely running R
v2.5.0 or newer. Then, see the above link or help(Sys.setenv, package="base").
The reason for adding the same to this package is that in R v2.4.x only Sys.putenv() is avail-
able. To make this package work on both system, Sys.setenv() is set to Sys.putenv() on
R v2.4.x and needs to be document in order for the package to pass the tests.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
as.character.Matlab
Gets a string describing the current Matlab connection
Description
Gets a string describing the current Matlab connection.
Usage
## S3 method for class 'Matlab':
as.character(x, ...)
Arguments
... Not used.
Value
Returns a character string.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
close.Matlab 21
Description
Closes connection to Matlab server. After closing the connection the Matlab server can never more
be access again.
Usage
## S3 method for class 'Matlab':
close(con, ...)
Arguments
... Not used.
Value
Returns what *close() returns.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
Evaluates one or several Matlab expressions on the Matlab server. This method will not return until
the Matlab server is done.
If an error occured in Matlab an exception will be thrown. This expection can be caught by
tryCatch().
If you receieve error message Excepted an ’answer’ from Matlab, but kept receiving nothing, see
"Troubleshooting" under ?R.matlab.
Usage
## S3 method for class 'Matlab':
evaluate(this, ..., collapse=";")
22 finalize.Matlab
Arguments
... One or several string with Matlab expressions. If several strings are given they
will be concatenated with the separator collapse.
collapse Separator to be used to concatenate expressions.
Value
Returns (invisibly) NULL if expressions were evaluated successfully. An exception might also be
thrown.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
Finalizes the object if deleted. If a Matlab connection is opened, it is closed.
Note that you should never have to call this method explicitly. It is called automatically whenever
the object is removed from memory (by the garbage collector).
Usage
## S3 method for class 'Matlab':
finalize(this, ...)
Arguments
... Not used.
Value
Returns nothing.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
getOption.Matlab 23
Description
Gets the value of an option where the option is specified like a file pathname, e.g. "readResult/maxTries".
See *setOption() for what options are available. See the Options class for details.
Usage
## S3 method for class 'Matlab':
getOption(this, ...)
Arguments
... Arguments passed to getOption() of the Options class.
Value
Returns the value of the option.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
Description
Gets one or several Matlab variables from the Matlab server. The transfer of the data can be done lo-
cally via a temporary file (remote=FALSE) or through the socket connection (remote=TRUE),
which is always available.
Usage
## S3 method for class 'Matlab':
getVariable(this, variables, remote=this$remote, ...)
24 isOpen.Matlab
Arguments
variables String vector of Matlab containing names of variable that are to be retrieved
from the Matlab server.
remote If TRUE the variables are transferred on the socket connection, otherwise
they are transferred via a temporary file.
... Not used.
Value
Returns a list structure containing the Matlab variables as named values.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
Checks if connection to the Matlab server is open.
Usage
## S3 method for class 'Matlab':
isOpen(con, ...)
Arguments
... Not used.
Value
Returns TRUE if connection is open, otherwise FALSE.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
open.Matlab 25
Description
Tries to open a socket connection to the Matlab server. If the connection could not be opened it the
first time it will try to open it every interval second up to trials times.
Usage
## S3 method for class 'Matlab':
open(con, trials=30, interval=1, ...)
Arguments
trials The number of trials before giving up.
interval The interval in seconds between trials.
... Not used.
Value
Returns TRUE if a socket connection to the Matlab server was successfully opened, otherwise
FALSE.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
Reads a MAT file structure from an input stream, either until End of File is detected or until
maxLength bytes has been read. Using maxLength it is possible to read MAT file structure
over socket connections and other non-terminating input streams. In such cases the maxLength
has to be communicated before sending the actual MAT file structure.
Both the MAT version 4 and MAT version 5 file formats are supported. The implementation is
based on [1].
From Matlab v7, compressed MAT version 5 files are used by default [3]. These are not supported.
Use save -V6 in Matlab to write a MAT file compatible with Matlab v6, that is, to write a non-
compressed MAT version 5 file. Note: Do not mix up version numbers for the Matlab software and
the Matlab file formats.
26 readMat
Usage
## Default S3 method:
readMat(con, maxLength=NULL, fixNames=TRUE, verbose=FALSE, ...)
Arguments
con Binary connection to which the MAT file structure should be written to. A
string is interpreted as filename, which then will be opened (and closed after-
wards).
maxLength The maximum number of bytes to be read from the input stream, which should
be equal to the length of the MAT file structure. If NULL, data will be read until
End Of File has been reached.
fixNames If TRUE, names of Matlab variables and fields are renamed such that they are
valid variables names in R.
verbose Either a logical, a numeric, or a Verbose object specifying how much
verbose/debug information is written to standard output. If a Verbose object,
how detailed the information is is specified by the threshold level of the object.
If a numeric, the value is used to set the threshold of a new Verbose object. If
TRUE, the threshold is set to -1 (minimal). If FALSE, no output is written (and
neither is the R.utils package required).
... Not used.
Details
For the MAT v5 format, cell structures are read into R as a list structure.
Sparse matrices are converted into plain matrices, which means that some matrices will be too large
to be allocated.
Value
Returns a named list structure containing all variables in the MAT file structure.
Author(s)
Henrik Bengtsson, Mathematical Statistics, Lund University. The internal MAT v4 reader was
written by Andy Jacobson at Program in Atmospheric and Oceanic Sciences, Princeton University.
References
[1] The MathWorks Inc., Matlab - MAT-File Format, version 5, June 1999.
[2] The MathWorks Inc., Matlab - Application Program Interface Guide, version 5, 1998.
[3] The MathWorks Inc., Matlab - MAT-File Format, version 7, October 2004, http://www.
mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf
See Also
writeMat().
readMat 27
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Reading all example files
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
for (version in 4:5) {
cat("Loading all MAT v", version, " example files in ",
path, "...\n", sep="")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Assert that sparse matrices are read identically in MAT v4 and v5
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat4 <- readMat(file.path(path, "SparseMatrix3-v4.mat"))
mat5 <- readMat(file.path(path, "SparseMatrix3-v5.mat"))
diff <- sum(abs(mat4$sparseM - mat5$sparseM))
if (diff > .Machine$double.eps)
stop("Failed to read identical MAT v4 and MAT v5 sparse matrices.")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Assert that signed and unsigned integers are read correctly
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bs <- readMat(file.path(path, "unsignedByte.mat"))
if (!identical(as.vector(bs$A), as.double(126:255)))
stop("Error reading unsigned bytes saved by Matlab.")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example of a Matlab struct
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# File was created by
# s = struct('type',{'big','little'}, 'color','red', 'x',{3,4})
# 1x2 struct array with fields:
# type
# color
28 readResult.Matlab
# x
# save structLooped.mat s -v6
mat <- readMat(file.path(path, "structLooped.mat"))
print(s)
Description
Reads results from the Matlab server.
This method is for internal use only.
Usage
## S3 method for class 'Matlab':
readResult(this, ...)
Arguments
... Not used.
Value
Returns an R object.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
setFunction.Matlab 29
Description
Creates an M-file on the Matlab server machine (in the working directory) containing the specified
Matlab function definition.
Usage
## S3 method for class 'Matlab':
setFunction(this, code, name=NULL, collapse="
", ...)
Arguments
code The Matlab function definition.
name Optional name of the function, which will defined the name of the M-file where
the function is stored. If NULL, the name is extracted from the code.
collapse The string that the code lines, if there are more than one, is going to be concat-
tenated with.
... Not used.
Value
Returns nothing.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Examples
## Not run: code <- c(
"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;"
)
setFunction(matlab, code)
evaluate(matlab, "[w,a]=dice(1000);")
30 setOption.Matlab
## End(Not run)
Description
Sets the value of an option where the option is specified like a file pathname, e.g. "readResult/maxTries".
See the Options class for details.
Usage
## S3 method for class 'Matlab':
setOption(this, ...)
Arguments
... Arguments passed to HYPERLINK(setOption())(setOption()) of the
Options class.
Value
Returns the previous value of the option.
Available options
readResult/maxTries The maximum number of times the connection is check for an answer from the Matlab server
before giving up. Default values is 30 times.
readResult/interval The interval in seconds between each poll for an answer. Default interval is 1 (second).
With default values of the above options, the R Matlab client waits 30 seconds for a reply from the
Matlab server before giving up.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
Description
Sets one or several R variables on the Matlab server. The transfer of the data can be done locally
via a temporary file (remote=FALSE) or through the socket connection (remote=TRUE),
which is always available.
Usage
## S3 method for class 'Matlab':
setVariable(this, ..., remote=this$remote)
Arguments
... Named R variables to be set in Matlab.
remote If TRUE the variables are transferred on the socket connection, otherwise
they are transferred via a temporary file.
Value
Returns nothing. If the Matlab server did not received the variables successfully an exception is
thrown.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
setVerbose.Matlab Sets the verbose level to get more details about the Matlab access
Description
Sets the verbose level to get more details about the Matlab access.
Usage
## S3 method for class 'Matlab':
setVerbose(this, threshold=0, ...)
32 startServer.Matlab
Arguments
threshold A threshold that the level argument of any write method has to be equal to or
larger than in order to the message being written. Thus, the lower the threshold
is the more and more details will be outputted. If a large numeric or FALSE,
no verbose output will be given.
... Not used.
Details
If the threshold is set to zero (default) general comments about the Matlab access is given, such as
the Matlab server is started etc. If the threshold is -1, details about the communication with the
Matlab server is given. If the threshold is -2, low-level details about the communication with the
Matlab server is given, such as what commands are sent etc.
Value
Returns the previous threshold value (an integer) used.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
Static method which starts a Matlab server on the local machine. Note that Matlab v6 or later is
required, since the Matlab server relies on Java.
Usage
Matlab$startServer(matlab=getOption("matlab"), port=9999, minimize=TRUE, options=c(
Arguments
matlab An optional character string specifying the name of the matlab command,
if different from "matlab". An absolute path are possible.
port An optional integer in [1023,65535]. If given, the environment variable
MATLABSERVER_PORT is set specifying which port the Matlab server should
listen to for clients trying to connect. The default port is 9999.
writeCommand.Matlab 33
minimize When starting Matlab on Windows, it is always opened in a new window (see
1. The Matlab server running in Matlab). If this argument is
TRUE, the new window is minimized, otherwise not. This argument is ignored
on non-Windows systems.
options A character vector of options used to call the Matlab application.
... Not used.
Details
This method is currently supported on Windows and Unix systems. Other systems are untested, but
might work anyway.
Note that this method will return immediately upon calling system() internally, i.e. you will not
receive a return value telling wether Matlab was successfully started or not.
To specify the full path to the matlab software set the matlab option, e.g. options(matlab="/opt/bin/matlab6.1
If no such option exists, the value "matlab" will be used.
The Matlab server relies on two files: 1) MatlabServer.m and 2) InputStreamByteWrapper.class
(from InputStreamByteWrapper.java). These files exists in the externals/ directory of this package.
However, if they do not exist in the current directory, which is the directory where Matlab is started,
copies of them will automatically be made.
Value
Returns nothing.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
writeCommand.Matlab
Writes (sends) a command to the Matlab server
Description
Writes (sends) a command to the Matlab server.
This method is for internal use only.
Usage
## S3 method for class 'Matlab':
writeCommand(this, cmd, ...)
34 writeMat
Arguments
... Not used.
Value
Returns nothing.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
For more information see Matlab.
Description
This function takes the given variables (...) and places them in a MAT file structure, which is
then written to a binary connection.
Currently only the MAT version 5 file format is supported.
Usage
## Default S3 method:
writeMat(con, ..., matVersion="5", onWrite=NULL, verbose=FALSE)
Arguments
con Binary connection to which the MAT file structure should be written to. A
string is interpreted as filename, which then will be opened (and closed after-
wards).
... Named variables to be written.
matVersion A character string specifying what MAT file format version to be written to
the connection. If "5", a MAT v5 file structure is written. No other formats are
currently supported.
onWrite Function to be called just before starting to write to connection. Since the MAT
file structure does not contain information about the total size of the structure
this argument makes it possible to first write the structure size (in bytes) to the
connection.
writeMat 35
Value
Returns (invisibly) the number of bytes written. Any bytes written by any onWrite function are not
included in this count.
Author(s)
Henrik Bengtsson (http://www.braju.com/R/)
See Also
readMat().
Examples
A <- matrix(1:27, ncol=3)
B <- as.matrix(1:10)
unlink(filename)
## Not run:
# When writing to a stream connection the receiver needs to know in
# beforehand how many bytes are available. This can be done by using
# the 'onWrite' argument.
onWrite <- function(x)
writeBin(x$length, con=x$con, size=4, endian="little");
writeMat(con, A=A, B=B, onWrite=onWrite)
## End(Not run)
Index
∗Topic IO open.Matlab, 25
readMat, 25 readResult.Matlab, 28
writeMat, 34 setFunction.Matlab, 29
∗Topic classes setOption.Matlab, 30
Matlab, 11 setVariable.Matlab, 31
∗Topic documentation setVerbose.Matlab, 31
1. The Matlab server startServer.Matlab, 32
running in Matlab, 2 writeCommand.Matlab, 33
Non-documented objects, 16 ∗Topic package
Sys.setenv, 20 R.matlab-package, 16
∗Topic file * close, 21
readMat, 25 * evaluate, 14
writeMat, 34 * getOption, 30
∗Topic internal * setOption, 23
as.character.Matlab, 20 1. The Matlab server running
close.Matlab, 21 in Matlab, 2, 33
evaluate.Matlab, 21
finalize.Matlab, 22 as.character, 12
getOption.Matlab, 23 as.character,Matlab-method
getVariable.Matlab, 23 (as.character.Matlab), 20
as.character.Matlab, 20
isOpen.Matlab, 24
Non-documented objects, 16
character, 20, 32–34
open.Matlab, 25
close, 12
readResult.Matlab, 28
close,Matlab-method
setFunction.Matlab, 29
(close.Matlab), 21
setOption.Matlab, 30 close.Matlab, 21
setVariable.Matlab, 31 connection, 11, 23–26, 31, 34
setVerbose.Matlab, 31
startServer.Matlab, 32 evaluate, 12
Sys.setenv, 20 evaluate (Non-documented
writeCommand.Matlab, 33 objects), 16
∗Topic methods evaluate,Matlab-method
as.character.Matlab, 20 (evaluate.Matlab), 21
close.Matlab, 21 evaluate.Matlab, 21
evaluate.Matlab, 21
finalize.Matlab, 22 FALSE, 24–26, 32, 35
getOption.Matlab, 23 finalize, 12
getVariable.Matlab, 23 finalize,Matlab-method
isOpen.Matlab, 24 (finalize.Matlab), 22
36
INDEX 37
finalize.Matlab, 22 Matlab.setVerbose
(setVerbose.Matlab), 31
getOption, 12, 23 Matlab.startServer
getOption (Non-documented (startServer.Matlab), 32
objects), 16 Matlab.writeCommand
getOption,Matlab-method (writeCommand.Matlab), 33
(getOption.Matlab), 23
getOption.Matlab, 23 Non-documented objects, 16
getVariable, 12 NULL, 22, 29
getVariable (Non-documented numeric, 26, 32, 35
objects), 16
getVariable,Matlab-method Object, 11
(getVariable.Matlab), 23 open, 12
getVariable.Matlab, 23 open,Matlab-method (open.Matlab),
25
help, 17 open.Matlab, 25
Options, 23, 30
integer, 32
isOpen, 12 R.matlab (R.matlab-package), 16
isOpen (Non-documented objects), R.matlab-package, 16
16 R.utils, 17, 26, 35
isOpen,Matlab-method readMat, 14, 17, 25, 35
(isOpen.Matlab), 24 readResult, 12
isOpen.Matlab, 24 readResult (Non-documented
objects), 16
list, 26 readResult,Matlab-method
logical, 26, 35 (readResult.Matlab), 28
readResult.Matlab, 28
Matlab, 11, 17, 20–25, 28–34
Matlab.as.character setFunction, 12
(as.character.Matlab), 20 setFunction (Non-documented
Matlab.close (close.Matlab), 21 objects), 16
Matlab.evaluate setFunction,Matlab-method
(evaluate.Matlab), 21 (setFunction.Matlab), 29
Matlab.finalize setFunction.Matlab, 29
(finalize.Matlab), 22 setOption, 12, 14
Matlab.getOption setOption (Non-documented
(getOption.Matlab), 23 objects), 16
Matlab.getVariable setOption,Matlab-method
(getVariable.Matlab), 23 (setOption.Matlab), 30
Matlab.isOpen (isOpen.Matlab), 24 setOption.Matlab, 30
Matlab.open (open.Matlab), 25 setVariable, 12
Matlab.readResult setVariable (Non-documented
(readResult.Matlab), 28 objects), 16
Matlab.setFunction setVariable,Matlab-method
(setFunction.Matlab), 29 (setVariable.Matlab), 31
Matlab.setOption setVariable.Matlab, 31
(setOption.Matlab), 30 setVerbose, 12
Matlab.setVariable setVerbose (Non-documented
(setVariable.Matlab), 31 objects), 16
38 INDEX
setVerbose,Matlab-method
(setVerbose.Matlab), 31
setVerbose.Matlab, 31
startServer, 12
startServer (Non-documented
objects), 16
startServer,Matlab-method
(startServer.Matlab), 32
startServer.Matlab, 32
Sys.setenv, 20, 20
vector, 33
Verbose, 26, 35
writeCommand, 12
writeCommand (Non-documented
objects), 16
writeCommand,Matlab-method
(writeCommand.Matlab), 33
writeCommand.Matlab, 33
writeMat, 14, 17, 26, 34