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 2

May 19, 2010 9 Comments

Once again I welcome guest blogger Joshua Kaplan for his continued series on MatlabControl – the Java-to-Matlab Interface (JMI) wrapper
Last week I introduced a Java package called matlabcontrol which can be used to access Matlab from Java.
Let’s now put matlabcontrol to work from Java. Below is a very simple Java class called LocalExample which uses Swing to create a window (JFrame), a text field (JTextField), and a button (JButton). When the button is pressed, the text in the field will be evaluated in Matlab using LocalMatlabProxy.eval(…), which was explained in the previous post.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import matlabcontrol.LocalMatlabProxy;
import matlabcontrol.MatlabInvocationException;
/**
 * A simple demo of some of matlabcontrol's functionality.
 *
 * @author Joshua Kaplan
 */
public class LocalExample extends JFrame
{
  /**
   * Constructs this example and displays it.
   */
  public LocalExample()
  {
    //Window title
    super("Local Session Example");
    //Panel to hold field and button
    JPanel panel = new JPanel();
    this.add(panel);
    //Input field
    final JTextField inputField = new JTextField();
    inputField.setColumns(15);
    panel.add(inputField);
    //Eval button
    JButton evalButton = new JButton("eval");
    panel.add(evalButton);
    //Eval runnable, to execute in separate (non-EDT) thread
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Runnable evalRunnable = new Runnable()
    {
      public void run()
      {
        try
        {
          LocalMatlabProxy.eval(inputField.getText());
        }
        catch (MatlabInvocationException exc) { }
      }
    };
    //Eval action event for button and field
    ActionListener evalAction = new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        //This uses the EDT thread, which may hang Matlab...
        //LocalMatlabProxy.eval(inputField.getText());
        //Execute runnable on a separate (non-EDT) thread
        executor.execute(evalRunnable);
      }
    };
    evalButton.addActionListener(evalAction);
    inputField.addActionListener(evalAction);
    //On closing, release resources of this frame
    this.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        LocalExample.this.dispose();
      }
    });
    //Display
    this.pack();
    this.setResizable(false);
    this.setVisible(true);
  }
}

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import matlabcontrol.LocalMatlabProxy; import matlabcontrol.MatlabInvocationException; /** * A simple demo of some of matlabcontrol's functionality. * * @author Joshua Kaplan */ public class LocalExample extends JFrame { /** * Constructs this example and displays it. */ public LocalExample() { //Window title super("Local Session Example"); //Panel to hold field and button JPanel panel = new JPanel(); this.add(panel); //Input field final JTextField inputField = new JTextField(); inputField.setColumns(15); panel.add(inputField); //Eval button JButton evalButton = new JButton("eval"); panel.add(evalButton); //Eval runnable, to execute in separate (non-EDT) thread final ExecutorService executor = Executors.newSingleThreadExecutor(); final Runnable evalRunnable = new Runnable() { public void run() { try { LocalMatlabProxy.eval(inputField.getText()); } catch (MatlabInvocationException exc) { } } }; //Eval action event for button and field ActionListener evalAction = new ActionListener() { public void actionPerformed(ActionEvent e) { //This uses the EDT thread, which may hang Matlab... //LocalMatlabProxy.eval(inputField.getText()); //Execute runnable on a separate (non-EDT) thread executor.execute(evalRunnable); } }; evalButton.addActionListener(evalAction); inputField.addActionListener(evalAction); //On closing, release resources of this frame this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { LocalExample.this.dispose(); } }); //Display this.pack(); this.setResizable(false); this.setVisible(true); } }

We can either copy and compile the above code (remember to import the matlabcontrol JAR file in your compiler; four class files will be created), or download the already-compiled code here. Note that the already-compiled classes were compiled using JDK 1.6, so if you have Matlab R2007a (7.4) or earlier you will need to compile using an earlier Java compiler.
We now need to tell Matlab where to find both the matlabcontrol JAR file, and our LocalExample class files. We can either add the files to the static java classpath (by editing the classpath.txt file), or add them only to the current Matlab session’s dynamic classpath:

% Add Java files to current Matlab session's dynamic classpath
javaaddpath LocalExample.zip
javaaddpath matlabcontrol-3.01.jar

% Add Java files to current Matlab session's dynamic classpath javaaddpath LocalExample.zip javaaddpath matlabcontrol-3.01.jar

To run the Java program, simply type LocalExample in the Matlab Command Window – A small Java window will appear and JMI will evaluate any expression typed into it:

>> LocalExample
ans =
LocalExample[frame0,0,0,202x67,title=Local Session Example,...]

>> LocalExample ans = LocalExample[frame0,0,0,202x67,title=Local Session Example,...]

Java window calling Matlab via JMI
Java window calling Matlab via JMI

a =
          1.77245385090552

a = 1.77245385090552

When we called LocalMatlabControl.eval(…) from the Command Window last week, what occurred behind the scenes was actually quite different from what happens when we press the “eval” button in the Java program. This is because in the Command Window everything executes in Matlab’s single main thread. When we pressed “eval”, the code executed from the Event Dispatch Thread (EDT), which is a separate thread.
EDT is used extensively by Matlab when accessing graphical components such as a figure window, uicontrols or plots. When calling a function from JMI, the calling thread always blocks (pauses) until Matlab is done completing whatever has been asked of it. So, if we called JMI/matlabcontrol from the EDT and Matlab needed to use the EDT, then everything will lock up. To fix this potential problem, when you press the “eval” button the command is sent off to a separate thread which can block without preventing Matlab from doing its work. Future versions of matlabcontrol will try to simplify this process further. matlabcontrol over a remote connection, the topic of my next post, does not suffer from this complication because Matlab and your program are not sharing the same EDT or even the same Java runtime process (JVM).
While the above Java example is quite simple, using a combination of all of the methods described throughout my previous post, a much more sophisticated program can be created. To explore the methods in more detail you can use the demo available here (downloadable JAR). The demo uses a remote connection to Matlab, but the available methods are the same. In my next and final article on this subject, I will explore controlling Matlab using matlabcontrol over a remote connection.

Related posts:

  1. JMI wrapper – local MatlabControl part 1 – MatlabControl is an open-source wrapper of JMI that allows an easy and documented way to communicate from Java to Matlab. This article describes this wrapper....
  2. JMI wrapper – remote MatlabControl – An example using matlabcontrol for calling Matlab from a separate Java process is explained....
  3. Matlab and the Event Dispatch Thread (EDT) – The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  4. Explicit multi-threading in Matlab part 1 – Explicit multi-threading can be achieved in Matlab by a variety of simple means. ...
  5. Matlab callbacks for Java events in R2014a – R2014a changed the way in which Java objects expose events as Matlab callbacks. ...
  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 »
9 Responses
  1. ben May 21, 2010 at 02:33 Reply

    I am looking forward to your blog post about controlling Matlab using matlabcontrol over a remote connection. Thanks for all the effort you put into matlabcontrol!

  2. JMI wrapper – remote MatlabControl | Undocumented Matlab May 26, 2010 at 01:06 Reply

    […] Last week I demonstrated using matlabcontrol to call Matlab from Java from within the Matlab application. Today I will explain how to control Matlab from a remote Java session. […]

  3. n n October 12, 2010 at 23:29 Reply

    hello guys.
    Where should I found this file?

    import matlabcontrol.LocalMatlabProxy;
    import matlabcontrol.MatlabInvocationException;

    • Yair Altman October 13, 2010 at 01:04 Reply

      matlabcontrol.jar is available here: http://code.google.com/p/matlabcontrol/downloads/list

  4. Etienne Balmes June 24, 2011 at 07:53 Reply

    I have been following your posts with interest. Here is a question. I have very large data sets in MATLAB and would like to use a custom table model to display them in java. I tested the process in pure java and it works as it should.

    Now to implement an AbstractTableModel I need to be able to call Matlab (or possibly C), to get the correct values on getColumnCount , getRowCount and getValueAt

    Using the JMI I can get the data with a call to my own Matlab function mat.fevalConsoleOutput(“cinguj”, …);

    But when this is called by SWING I cannot use Matlab.mtFevalConsoleOutput because swing is not on the main Matlab Thread so JMI complains and fevalConsoleOutput seems to run asynchronously so that I do not get the right answer in time.

    Matlabcontrol does not call fevalConsoleOutput and thus does not address the issue. I also tried implementing the com.mathworks.jmi.CompletionObserver (just say implements CompletionObserver and add a completed method) but I have not found out to get the java to wait until completion (things I have tried locked up).

    Yair, if you don’t have an easy answer, I am willing to invest some money into it.

  5. Inno September 2, 2011 at 03:10 Reply

    Hi, I tried to compile this example, and this is what I get

    # javac LocalExample.java
    LocalExample.java:55: non-static method eval(java.lang.String) cannot be referenced from a static context
    LocalMatlabProxy.eval(inputField.getText());

    Any help will be appreciated. Thanks.

  6. weikuiwang April 17, 2012 at 02:01 Reply

    hi, can the matlabcontrol be used also for matlab runtime?

  7. Etienne Balmes June 1, 2013 at 05:02 Reply

    Hi
    I am using calls of the form
    mat= new com.mathworks.jmi.Matlab();
    mat.fevalConsoleOutput(“function”,variables);

    which works wonderfully on Matlab itself but am having a major bug when the same code is compiled (with the matlab compiler).

    The bug occurs when the callback attempts to open graphic objects.
    The stack trace differs depending on the OS and version but shows similar

      [  0] 000000007AD33FB2                  mcr.dll+278450 (mcrInstance::MCallbackAttach+000018)
      [  1] 000000007D4840FD             libmwgui.dll+213245 (MCallback::init+000253)
      [  2] 000000007D4842B7             libmwgui.dll+213687 (MCallback::MCallback+000039)
      [  3] 000000007D4847DF             libmwgui.dll+215007 (CopyMCallback+000063)
      [  4] 00000000793CB4DD                   hg.dll+3060957 (gf_PixelPosition+009997)
      [  5] 00000000794C86A0                   hg.dll+4097696 (hgConvertUDInterfaceToHandle+013760)
      [  6] 000000007C4155E6                  udd.dll+284134 (UDInterface::setE+000806)
      [  7] 000000007C3DB1E4                  udd.dll+045540 (udiSet+000068)
    
  8. Jaggi April 24, 2018 at 20:42 Reply

    I would like to debug matlab code using JMI… Localmatlabproxy.eval option
    Pls let me know yair

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
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) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
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