Package matlabcontrol
Class MatlabProxy
- java.lang.Object
-
- matlabcontrol.MatlabProxy
-
- All Implemented Interfaces:
MatlabOperations
- Direct Known Subclasses:
LoggingMatlabProxy
public abstract class MatlabProxy extends java.lang.Object implements MatlabOperations
Communicates with a running MATLAB session. This class cannot be instantiated, it may be created with aMatlabProxyFactory. Interaction with MATLAB occurs as if callingevalandfevalin the MATLAB Command Window.Communicating with MATLAB
Methods which interact with MATLAB provide Java objects to the MATLAB environment and retrieve data from the MATLAB environment as Java objects. The following description of how the conversion between MATLAB and Java types occurs is based on tests conducted on versions of MATLAB R2007b through R2010b. Unless otherwise noted the behavior was identical on all tested versions. However, this behavior is not officially documented by The MathWorks and may change for future versions of MATLAB. (matlabcontrol is not compatible with versions prior to MATLAB R2007b.)
MATLAB to Java
Numeric Classes and Logical Class
All MATLAB numeric types whether they are a singular value or an array/matrix (of any dimension) are always converted into a one-dimensional Javadouble[]. For complex numbers, only the real component is converted. MATLABlogicals whether a singular value or an array/matrix (of any dimension) are always converted into a one-dimensional Javaboolean[]. MATLAB arrays are stored in a linear manner, which has been documented by The MathWorks. It is in this linear manner that MATLAB arrays are returned to Java. (Sparse matrices are stored differently and are not sent to Java in an easy to use manner.)
Character Class
MATLABcharsingular values are returned as a JavaString. One-dimensional MATLABchararrays are returned as a JavaString. Two-dimensional MATLABchararrays are returned as a JavaString[]with each row of the MATLAB array becoming a JavaString. MATLABchararrays of more than two dimensions have an inconsistent conversion to a Java type, although all observed conversions are either a JavaStringor an array ofStrings.
Cell and Struct Arrays
MATLABcellarrays andstructarrays are converted to a JavaObject[], often with arrays inside of them.
Function Handles and Non-Built-In Classes
MATLABfunction_handles and all non-built-in classes (such as theMapclass or user defined classes) are converted to an instance ofcom.mathworks.jmi.types.MLArrayRefthat is notSerializablewhich prevents it from being transferred to a Java application running outside MATLAB (more information on this can be found in the exception section below).
Java to MATLAB
Primitives
It is not possible to directly send a Java primitive to the MATLAB environment because all methods which interact with MATLAB take in eitherObjectorObject[]which results in the Java primitives becoming their auto-boxed class equivalent. (For exampleintbecomesInteger.) Java primitive arrays, such asint[]areObjects and can therefore be sent to the MATLAB environment. They are converted as follows:
Java Type MATLAB Type boolean[]logicalarraychar[]not supported* byte[]int8arrayshort[]int16arrayint[]int32arraylong[]not supported* float[]singlearraydouble[]doublearray
*In MATLAB R2009b and higher, MATLAB will throw an exception. In MATLAB R2008b and earlier, MATLAB will segfault. The behavior in MATLAB R2009a is not known.Numbers
Subclasses ofNumber, which includes all of the auto-boxed versions of Java primitive numeric types, become MATLABdoubles.Booleans
Booleans are converted to MATLABlogicals.Characters
Characters are converted to MATLABchars.Strings
Strings are converted to MATLABchararrays.
Object Arrays
Arrays of non-primitive types are converted to MATLABcellarrays. The contents of the array are converted according to these same rules. Note that Java's multidimensional arrays are not an exception to this rule. For instance adouble[][]is an array ofdouble[]s and so MATLAB will create a cell array of MATLABdoublearrays.
Other Classes
Classes not otherwise mentioned remain as their original Java type. Objects contained within that class or instances of that class are not automatically converted by MATLAB, although when fields or methods are accessed in the MATLAB environment they may be converted into MATLAB types as documented by The MathWorks.
Behavior of transferred data
How Java objects sent to MATLAB or retrieved from MATLAB behave depends on several factors:
Running outside MATLAB
References to Java objects are copies. (There is one exception to this rule. Objects that areRemotewill act as if they are not copies. This is because matlabcontrol communicates with MATLAB's Java Virtual Machine using Remote Method Invocation.)
Running inside MATLAB
References to Java objects in MATLAB that are returned to Java, reference the same object. When passing a reference to a Java object to MATLAB, if the Java object is not converted to a MATLAB type then it will reference the same object in the MATLAB environment.
Help transferring data
TheMatlabProxyLoggerexists to record what is being returned from MATLAB. TheMatlabTypeConvertercan convert between complicated Java and MATLAB types. Currently only MATLAB numeric arrays are supported.Exceptions
Proxy methods that are relayed to MATLAB can throwMatlabInvocationExceptions. They will be thrown if:- The proxy has been disconnected via
disconnect(). - Attempting to do anything that would normally cause an error in MATLAB such as calling a function improperly or referencing a variable that does not exist.
- The underlying Java MATLAB Interface (JMI) API does not support the operation. For instance, attempting to send
a
long[]to MATLAB. Due to the undocumented nature of this interface, it is not entirely known what actions may result in an exception. - Communication between this Java Virtual Machine and the one that MATLAB is running in is disrupted, most commonly due to closing MATLAB.
- The class of an object to be sent or returned is not
SerializableorRemote.1 Java primitives and arrays behave as if they wereSerializable. - The class of an object to be returned from MATLAB is not defined in your application and no
SecurityManagerhas been installed.2 - The class of an object to sent to MATLAB is not defined in MATLAB and the class is not on your application's classpath.3
Running outside MATLAB
2 This is due to Remote Method Invocation prohibiting loading classes defined in remote Java Virtual Machines unless aSecurityManagerhas been set.PermissiveSecurityManagerexists to provide an easy way to set a security manager without further restricting permissions. Please consultPermissiveSecurityManager's documentation for more information.
3 MATLAB sessions started by aMatlabProxyFactoryare able to load all classes defined in your application's class path as specified by thejava.class.pathproperty. Some frameworks load classes without placing them on the class path, in that case matlabcontrol will not know about them and cannot tell MATLAB how to load them.Thread Safety
This proxy is unconditionally thread-safe. Methods which interact with MATLAB may be called concurrently; however they will be completed sequentially on MATLAB's main thread. Calls to MATLAB from a given thread will be executed in the order they were invoked. No guarantees are made about the relative ordering of calls made from different threads. This proxy may not be the only thing interacting with MATLAB's main thread. One proxy running outside MATLAB and any number of proxies running inside MATLAB may be simultaneously connected. If MATLAB is not hidden from user interaction then a user may also be making use of MATLAB's main thread. This means that two sequential calls to the proxy from the same thread that interact with MATLAB will execute in that order, but interactions with MATLAB may occur between the two calls. In typical use it is unlikely this behavior will pose a problem. However, for some uses cases it may be necessary to guarantee that several interactions with MATLAB occur without interruption. Uninterrupted access to MATLAB's main thread may be obtained by use ofinvokeAndWait(...).Threads
When running outside MATLAB, the proxy makes use of multiple internally managed threads. When the proxy becomes disconnected from MATLAB it notifies its disconnection listeners and then terminates all threads it was using internally. A proxy may disconnect from MATLAB without exiting MATLAB by callingdisconnect().
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceMatlabProxy.DisconnectionListenerListens for a proxy's disconnection from MATLAB.static interfaceMatlabProxy.IdentifierUniquely identifies a proxy.static interfaceMatlabProxy.MatlabThreadCallable<T>Uninterrupted block of computation performed in MATLAB.static interfaceMatlabProxy.MatlabThreadProxyOperates on MATLAB's main thread without interruption.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description voidaddDisconnectionListener(MatlabProxy.DisconnectionListener listener)Adds a disconnection listener that will be notified when this proxy becomes disconnected from MATLAB.abstract booleandisconnect()Disconnects the proxy from MATLAB.abstract voidexit()Exits MATLAB.MatlabProxy.IdentifiergetIdentifier()Returns the unique identifier for this proxy.abstract <T> TinvokeAndWait(MatlabProxy.MatlabThreadCallable<T> callable)Runs thecallableon MATLAB's main thread and waits for it to return its result.abstract booleanisConnected()Whether this proxy is connected to MATLAB.booleanisExistingSession()Whether this proxy is connected to a session of MATLAB that was running previous to the request to create this proxy.abstract booleanisRunningInsideMatlab()Whether this proxy is running inside of MATLAB.voidremoveDisconnectionListener(MatlabProxy.DisconnectionListener listener)Removes a disconnection listener.java.lang.StringtoString()Returns a brief description of this proxy.-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface matlabcontrol.MatlabOperations
eval, feval, getVariable, returningEval, returningFeval, setVariable
-
-
-
-
Method Detail
-
getIdentifier
public MatlabProxy.Identifier getIdentifier()
Returns the unique identifier for this proxy.- Returns:
- identifier
-
isExistingSession
public boolean isExistingSession()
Whether this proxy is connected to a session of MATLAB that was running previous to the request to create this proxy.- Returns:
- if existing session
-
toString
public java.lang.String toString()
Returns a brief description of this proxy. The exact details of this representation are unspecified and are subject to change.- Overrides:
toStringin classjava.lang.Object- Returns:
-
addDisconnectionListener
public void addDisconnectionListener(MatlabProxy.DisconnectionListener listener)
Adds a disconnection listener that will be notified when this proxy becomes disconnected from MATLAB.- Parameters:
listener-
-
removeDisconnectionListener
public void removeDisconnectionListener(MatlabProxy.DisconnectionListener listener)
Removes a disconnection listener. It will no longer be notified.- Parameters:
listener-
-
isRunningInsideMatlab
public abstract boolean isRunningInsideMatlab()
Whether this proxy is running inside of MATLAB.- Returns:
-
isConnected
public abstract boolean isConnected()
Whether this proxy is connected to MATLAB.
The most likely reasons for this method to returnfalseare if the proxy has been disconnected viadisconnect()or MATLAB has been closed (when running outside MATLAB).- Returns:
- if connected
- See Also:
disconnect(),exit()
-
disconnect
public abstract boolean disconnect()
Disconnects the proxy from MATLAB. MATLAB will not exit. After disconnecting, any method sent to MATLAB will throw an exception. A proxy cannot be reconnected. Returnstrueif the proxy is now disconnected,falseotherwise.- Returns:
- if disconnected
- See Also:
exit(),isConnected()
-
exit
public abstract void exit() throws MatlabInvocationExceptionExits MATLAB. Attempting to exit MATLAB with either aevalorfevalcommand will cause MATLAB to hang indefinitely.- Throws:
MatlabInvocationException- See Also:
disconnect(),isConnected()
-
invokeAndWait
public abstract <T> T invokeAndWait(MatlabProxy.MatlabThreadCallable<T> callable) throws MatlabInvocationException
Runs thecallableon MATLAB's main thread and waits for it to return its result. This method allows for uninterrupted access to MATLAB's main thread between two or more interactions with MATLAB.
If running outside MATLAB thecallablemust beSerializable; it may not beRemote.- Type Parameters:
T-- Parameters:
callable-- Returns:
- result of the callable
- Throws:
MatlabInvocationException
-
-