Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

JMI wrapper – local MatlabControl part 1

May 12, 2010 6 Comments

Once again I would like to welcome guest blogger Joshua Kaplan, who continues his series of JMI-related articles

Local and remote MatlabControl

Several weeks ago, I discussed the undocumented world of JMI (Java-to-Matlab Interface), that enables calling Matlab from Java. Today I will discuss matlabcontrol, an open-source wrapper I have written for JMI, that is both documented and user-friendly.
matlabcontrol supports calling Matlab in two different ways: local control where the Java code is launched from Matlab, and remote control where the Java code launches Matlab. Today we shall explore matlabcontrol‘s local control methods; in my next post we’ll create a simple Java program that uses matlabcontrol for local control; a later post will discuss the remote control path. These posts assume a medium to high level of Java experience.
matlabcontrol is a collection of Java classes, bundled together in a downloadable jar file, which is essentially just a zip file with a different file extension. As of this post the most recent version is matlabcontrol-3.01.jar. Note down where you’ve downloaded the jar file – you’ll need to use this information shortly.
For local control we’ll interact with the classes LocalMatlabProxy and MatlabInvocationException. LocalMatlabProxy contains all the methods required for calling Matlab; instances of MatlabInvocationException will be thrown when a problem occurs while attempting to control Matlab.
To tell Matlab where matlabcontrol-3.01.jar is, add the jar file path to Matlab’s dynamic (via the built-in javaaddpath function) or static (via edit(‘classpath.txt’)) Java classpath. You will need to restart Matlab if you have modified the static classpath, but it has the benefit of working better than the dynamic classpath in some situations.
Matlab now knows where to find the Java class files in matlabcontrol. To save some typing later on, type the following in the Matlab Command Window (or in your JMI-empowered Matlab application):

import matlabcontrol.*

import matlabcontrol.*

LocalMatlabProxy methods

LocalMatlabProxy is easy to use. All of its methods are static meaning they can be called without needing to assign LocalMatlabProxy to a variable. The methods are:

void exit()
java.lang.Object getVariable(java.lang.String variableName)
void setVariable(java.lang.String variableName, java.lang.Object value)
void eval(java.lang.String command)
java.lang.Object returningEval(java.lang.String command, int returnCount)
void feval(java.lang.String functionName, java.lang.Object[] args)
java.lang.Object returningFeval(java.lang.String functionName, java.lang.Object[] args)
java.lang.Object returningFeval(java.lang.String functionName, java.lang.Object[] args, int returnCount)
void setEchoEval(boolean echoFlag)

void exit() java.lang.Object getVariable(java.lang.String variableName) void setVariable(java.lang.String variableName, java.lang.Object value) void eval(java.lang.String command) java.lang.Object returningEval(java.lang.String command, int returnCount) void feval(java.lang.String functionName, java.lang.Object[] args) java.lang.Object returningFeval(java.lang.String functionName, java.lang.Object[] args) java.lang.Object returningFeval(java.lang.String functionName, java.lang.Object[] args, int returnCount) void setEchoEval(boolean echoFlag)

Detailed javadocs exist for all these methods. Here is an overview:

  • exit() is as straightforward as it sounds: it will exit Matlab. While it is possible to programmatically exit Matlab by other means, they may be unreliable. So, to exit Matlab from Java:
     LocalMatlabProxy.exit();

    LocalMatlabProxy.exit();

  • Setting and getting variables can be done using the getVariable(…) and setVariable(…) methods. These methods will auto-convert between Java and Matlab types where applicable.
       Using getVariable(…):

    • Java types in the Matlab environment retrieved will be returned as Java types.
    • Matlab types will be converted into Java types.

       Using setVariable(…):

    • Java types will be converted into Matlab types if they can. The rules are outlined here. Java Strings are converted to Matlab char arrays. Additionally, arrays of one of those Java types are converted to arrays of the corresponding Matlab type.

       Using these methods is fairly intuitive:

     >> LocalMatlabProxy.setVariable('x',5)
    >> LocalMatlabProxy.getVariable('x')
    ans =
         5

    >> LocalMatlabProxy.setVariable('x',5) >> LocalMatlabProxy.getVariable('x') ans = 5

       Getting and setting basic types (numbers, strings and Java objects) is quite reliable and consistent. It gets complicated when passing in an array (particularly multidimensional) from Java using setVariable(…), or getting a Matlab struct or cell array using getVariable(…). The type conversion in such cases is unpredictable, and may be inconsistent across Matlab versions. In such cases you are best off building a Java object with Matlab code and then getting the Java object you created.

  • The eval() and feval() methods were described in detail in my previous post. The functions will return the result, if any, as a Java object. Due to the way the underlying JMI operates, it is necessary to know in advance the number of expected return arguments. Matlab built-in nargout function reveals this number. Some functions (e.g., feval) return a variable number of arguments, in which case nargout returns -1. For instance:
     >> nargout sqrt
    ans =
         1
    >> nargout feval
    ans =
         -1

    >> nargout sqrt ans = 1 >> nargout feval ans = -1

  • LocalMatlabProxy‘s returningFeval(functionName, args) method uses the nargout information to determine the number of returned arguments and provide it to JMI. It will likely not function as expected if the function specified by functionName returns a variable number of arguments. In such a case, call returningFeval(…) with a third input argument that specifies the expected number of returned arguments. Since an eval() function can evaluate anything, just as if it were typed in the Command Window, there is no reliable way to determine what will be returned. All of this said, in most situations returningEval(…) can be used with a return count of 1, and the returningFeval(…) that automatically determines the return count will operate as expected.

Some simple usage examples

Let’s perform some of the same simple square root operations we did in the pure-JMI article, this time using matlabcontrol. First we’ll take the square root of 5, assigning the result to the Matlab variable y (note that we are calling Matlab from Java, that is called from within Matlab):

>> LocalMatlabProxy.eval('sqrt(5)')
ans =
    2.2361
>> y = LocalMatlabProxy.returningEval('sqrt(5)',1)
y =
    2.2361
>> LocalMatlabProxy.feval('sqrt',5)
>> y = LocalMatlabProxy.returningFeval('sqrt',5)
y =
    2.2361
>> y = LocalMatlabProxy.returningFeval('sqrt',5,1)
y =
    2.2361

>> LocalMatlabProxy.eval('sqrt(5)') ans = 2.2361 >> y = LocalMatlabProxy.returningEval('sqrt(5)',1) y = 2.2361 >> LocalMatlabProxy.feval('sqrt',5) >> y = LocalMatlabProxy.returningFeval('sqrt',5) y = 2.2361 >> y = LocalMatlabProxy.returningFeval('sqrt',5,1) y = 2.2361

In this situation there is no major difference between using eval() or feval() in the above situation. However, if instead of taking the square root of 5 we want to take the square root of a variable, then eval() is our only option.

>> a = 5
a =
     5
>> LocalMatlabProxy.eval('sqrt(a)')
ans =
    2.2361
>> y = LocalMatlabProxy.returningEval('sqrt(a)',1)
y =
    2.2361
>> LocalMatlabProxy.feval('sqrt','a')
??? Undefined function or method 'sqrt' for input arguments of type 'char'.
??? Java exception occurred:
matlabcontrol.MatlabInvocationException: Method could not return a value because of an internal Matlab exception
      at matlabcontrol.JMIWrapper.returningFeval(JMIWrapper.java:256)
      at matlabcontrol.JMIWrapper.feval(JMIWrapper.java:210)
      at matlabcontrol.LocalMatlabProxy.feval(LocalMatlabProxy.java:132)
Caused by: com.mathworks.jmi.MatlabException: Undefined function or method 'sqrt' for input arguments of type 'char'.
      at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
      at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:212)
      at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:121)
      at com.mathworks.jmi.Matlab.mtFevalConsoleOutput(Matlab.java:1511)
      at matlabcontrol.JMIWrapper.returningFeval(JMIWrapper.java:252)
      ... 2 more

>> a = 5 a = 5 >> LocalMatlabProxy.eval('sqrt(a)') ans = 2.2361 >> y = LocalMatlabProxy.returningEval('sqrt(a)',1) y = 2.2361 >> LocalMatlabProxy.feval('sqrt','a') ??? Undefined function or method 'sqrt' for input arguments of type 'char'. ??? Java exception occurred: matlabcontrol.MatlabInvocationException: Method could not return a value because of an internal Matlab exception at matlabcontrol.JMIWrapper.returningFeval(JMIWrapper.java:256) at matlabcontrol.JMIWrapper.feval(JMIWrapper.java:210) at matlabcontrol.LocalMatlabProxy.feval(LocalMatlabProxy.java:132) Caused by: com.mathworks.jmi.MatlabException: Undefined function or method 'sqrt' for input arguments of type 'char'. at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method) at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:212) at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:121) at com.mathworks.jmi.Matlab.mtFevalConsoleOutput(Matlab.java:1511) at matlabcontrol.JMIWrapper.returningFeval(JMIWrapper.java:252) ... 2 more

The automatic Matlab/Java type conversions discussed above are equally applicable to eval() and feval(). feval() automatically converted the argument ‘a’ into a Matlab char, instead of considering it as a Matlab variable. As seen above, the feval() invocation fails with a Java MatlabInvocationException. So, the only way to interact with Matlab variables is via eval() methods; feval() will not work.
Lastly there is the setEchoEval(echoFlag) method: If this method is called with a true argument, then all Java to Matlab calls will be logged in a dedicated window. This can be very helpful for debugging.
In my next post we shall put together this knowledge to create a small Java program that uses matlabcontrol to interact with Matlab.

Related posts:

  1. JMI wrapper – local MatlabControl part 2 – An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed...
  2. JMI wrapper – remote MatlabControl – An example using matlabcontrol for calling Matlab from a separate Java process is explained....
  3. setPrompt – Setting the Matlab Desktop prompt – The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...
  4. Creating a simple UDD class – This article explains how to create and test custom UDD packages, classes and objects...
  5. UDD and Java – UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...
  6. JMI – Java-to-Matlab Interface – JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....
Java JMI Joshua Kaplan Undocumented feature
Print Print
« Previous
Next »
6 Responses
  1. Lakshmi October 18, 2010 at 04:53 Reply

    hey, i wanted to use the ‘plot‘ command available in matlab in my java program. Can you tell me which package i should use for it?

    • Yair Altman October 18, 2010 at 11:26 Reply

      @Laksmi – take a look at the next article in the JMI series for an explanation on how to use the MatlabControl package to activate Matlab commands from within your Java code.

  2. georgeek November 14, 2010 at 14:37 Reply

    Hi,
    I disagree with the: “only way to interact with Matlab variables is via eval() methods; feval() will not work” . I think that it can be made with feval way too, its more code but functional:

    a=5;
    LocalMatlabProxy.feval('eval','sqrt(a)');

    a=5; LocalMatlabProxy.feval('eval','sqrt(a)');

    • Yair Altman November 14, 2010 at 23:04 Reply

      @georgeek – your example just illustrated the point that you need to use eval… 🙂

  3. shashank February 7, 2012 at 10:37 Reply

    Hi Yair

    I tried both(dynamic using JAVAADDPATH and static editing classpath.ext) ways of adding matlabcontrol-4.0.0.jar file but still matlab throws following error
    ??? Undefined variable “LocalMatlabProxy”

    Please help me to resolve above error , I’m using matlab R2007a version

  4. Vlad May 21, 2012 at 04:05 Reply

    Hi,

    could you post an example, how to get/set cell and struct arrays with matlabcontrol library form remote java code?
    for example i have a 1×1 struct array variable S in workspace (marker: ‘p’, value: 80, factor: ‘0.001’, unit: ‘mm’) and want to get it

    thanks, Vlad

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (6 days 14 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (6 days 14 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (6 days 21 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (7 days 18 hours ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (10 days 22 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (13 days 21 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (14 days 0 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (14 days 1 hour ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (14 days 15 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (17 days 22 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (46 days 0 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (46 days 6 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (53 days 23 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (59 days 19 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (66 days 6 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top