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 (email)
  •  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
  • Josh (15 hours 8 minutes ago): Dear Yair, Small typo; you wrote >>Move lines up or down – CTRL + ALT + UP or DOWN allows you to move selected lines up or down but it’s actually ALT+SHIFT then UP/DOWN...
  • Yair Altman (7 days 9 hours ago): You can try to increase the Java heap memory size in the Matlab preferences (General => Java Heap Memory). Any changes to the settings will only take effect after restarting...
  • Thomas (7 days 11 hours ago): Hello, thanks for sharing! I currently receive the following memory error message when using savezip with a big object (Matlab R2020b, Windows 10). Error using...
  • Yair Altman (10 days 18 hours ago): Yerlan – either use menuItem1.setEnabled(0) or set(menuItem1,'Enabled',0)
  • Manzn (10 days 21 hours ago): Thank you man! you saved me, when there was no more light 😀
  • Yerlan (12 days 2 hours ago): Hello Mr. Altman, how can I disable menu items in the context menu? E.g. when I am trying to do this: menuItems = jmenu.getSubElements; menuItem1 = menuItems(1);...
  • Yair Altman (12 days 18 hours ago): Thanks for the note Eric – you forgot the crucial call to jTable.setLabelTable(labelTabl e) – I added it into your code snippet above.
  • Erik (14 days 5 hours ago): Thank you for this — I don’t know if this has been mentioned anywhere else before, but it could be useful to mention how to add custom labels to a jslider. I did the...
  • turhv (27 days 0 hours ago): very nice! work perfectly to me in MATLAB 2019a. thanks!!!
  • Jianfei (60 days 3 hours ago): I have tried the MathWorks CheckBoxList in Matlab 2015b. For whatever the reason, I can’t change the font properties. I can change the font color, but changing font properties...
  • Donato Coppola (65 days 23 hours ago): Hi Yair, I have a problem with the double format. When I run the treeTable function, the numbers in double format cells are displayed with comma as decimal separator. How can...
  • Kim (71 days 13 hours ago): Yair, the following didn’t work for me either: jh.setBorderPainted(false); Regards, Kim
  • Adil (73 days 14 hours ago): Thank you for the blog, it was useful for me. I have a file named App_project.mlapp.zip and when I extract it through Winzip it gives all the files exactly as you described above. I...
  • Mr Ashley Trowell (76 days 0 hours ago): Thank you so much for this analysis. Also, I find it somewhat horrifying. The take away seems to be to use && / || and NOT and / or. Thanks a bunch! ~Ashley
  • Matt (81 days 2 hours ago): Late reply I know, but you can call custom shortcuts with alt-#. Hold down Alt to see what number is assigned to the shortcuts you’ve created. Now if there was a way to create a...
Contact us
Undocumented Matlab © 2009 - Yair Altman
Scroll to top