<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Joshua Kaplan &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/joshua-kaplan/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 26 May 2010 08:06:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.3</generator>
	<item>
		<title>JMI wrapper &#8211; remote MatlabControl</title>
		<link>https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jmi-wrapper-remote-matlabcontrol</link>
					<comments>https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 26 May 2010 08:06:38 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Joshua Kaplan]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1539</guid>

					<description><![CDATA[<p>An example using matlabcontrol for calling Matlab from a separate Java process is explained.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol">JMI wrapper &#8211; remote MatlabControl</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 2">JMI wrapper &#8211; local MatlabControl part 2 </a> <small>An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Perhaps the most difficult aspect of Matlab-Java integration is JMI (Java-to-Matlab Integration) over a remote connection, meaning a Java program that communicates with a separate Matlab process. Once again I welcome guest blogger Joshua Kaplan, who concludes his series of JMI-related articles with the awaited holy grail on this topic.</i></p>
<h3 id="remote">Remote control of Matlab</h3>
<p>Last week I <a target="_blank" href="/articles/jmi-wrapper-local-matlabcontrol-part-2/">demonstrated</a> using <i>matlabcontrol</i> to call Matlab from Java from within the Matlab application. Today I will explain how to control Matlab from a remote Java session. We will create a small Java program that allows us to launch and connect to Matlab, then send it <i><b>eval</b></i> commands and receive the results. While this example will involve creating a dedicated user interface, <em>matlabcontrol</em> can be integrated into any existing Java program without requiring any user interface.<br />
<em>matlabcontrol</em> was originally created for controlling Matlab, not for performing computations. If your exclusive concern is to perform Matlab computations and use the results in Java, then check the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/products/javabuilder/">Matlab Builder JA</a> toolbox, which is made by MathWorks and is officially supported. Unfortunately this toolbox is quite expensive and does not enable interaction with a running Matlab session (it uses the non-GUI Matlab engine, much as the compiler does). It is for this purpose that the open-source (free) <em>matlabcontrol</em> package was created.<br />
Note that <em>matlabcontrol</em> opens a new running Matlab session and does not connect to an already-running session. Matlab commands can then be invoked either interactively (in Matlab&#8217;s Command Window) or remotely (from Java). Debugging an already-open Matlab session can be done with jdb over a dedicated port, using an altogether different mechanism than <em>matlabcontrol</em> &#8211; this will be discussed in a future post.<br />
Matlab has <a target="_blank" rel="nofollow" href="http://www.mathworks.co.uk/access/helpdesk/help/techdoc/matlab_external/f38569.html">documented support</a> for a COM interface (Windows) and process pipes (Unix/Mac) that allow remote communication from external applications. Unfortunately Java does not natively support COM, which is where <em>matlabcontrol</em> helps using its RMI approach. Interested readers can also try using a Java/COM bridge (<a target="_blank" rel="nofollow" href="http://sourceforge.net/projects/jacob-project/">JACOB</a> or <a target="_blank" rel="nofollow" href="http://sourceforge.net/projects/jcom/">JCOM</a>) as an alternative that would have the added benefits of enabling communication with an existing Matlab session and of MathWorks&#8217; documented support.</p>
<h3 id="RemoteExample">A simple RemoteExample</h3>
<p>Today&#8217;s RemoteExample demo is too long to paste into this post; instead you can download the <a target="_blank" href="/files/RemoteExample.java">source code</a>, or a <a target="_blank" href="/files/RemoteExample.jar">jar file</a> that contains both the pre-compiled classes and <em>matlabcontrol</em>. To run this jar on Windows or Mac OS X you only need to double click on it (if you are running on Linux I&#8217;m sure you know what to do&#8230;). If you wish to download and compile the source file, remember that you will need the <em>matlabcontrol</em> jar referenced in your Java classpath.<br />
Let&#8217;s dive in: The file begins with the mainline followed by default sizes and status messages. The user interface is then built using standard Swing components &#8211; there&#8217;s nothing special here, just some panels, panes, text fields, buttons, etc.<br />
The interesting part begins when the <em>RemoteMatlabProxyFactory</em> object is created:</p>
<pre lang="java">RemoteMatlabProxyFactory factory = new RemoteMatlabProxyFactory();</pre>
<p>This Matlab-proxy factory object is used when the user clicks the &#8220;Connect&#8221; button:</p>
<pre lang="java">factory.requestProxy();</pre>
<p>This creates a <em>RemoteMatlabProxy</em> object. <em>RemoteMatlabProxy</em>s must be created by a <em>RemoteMatlabProxyFactory</em> and cannot be directly constructed. When <em>requestProxy()</em> is called, <em>matlabcontrol</em> launches Matlab and connects to it using <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp">RMI</a>. When the connection is established, a <em>MatlabConnectionListener</em> added to the factory will be notified using its <em>connectionEstablished(RemoteMatlabProxy proxy)</em> callback method. The <em>RemoteMatlabProxy</em> object passed into this method is now connected to Matlab.<br />
<center><figure style="width: 408px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Connecting Java to Matlab using RMI" src="https://undocumentedmatlab.com/images/matlabcontrol_remote1.png" title="Connecting Java to Matlab using RMI" width="408" height="276" /><figcaption class="wp-caption-text">Connecting Java to Matlab using RMI</figcaption></figure></center><br />
While this example only deals with communicating with a single Matlab session, <em>matlabcontrol</em> can handle multiple remote sessions. Whenever a new session is established, <em>connectionEstablished(RemoteMatlabProxy proxy)</em> is invoked on each connection listener. When a connection is lost due to Matlab closing, or in very rare cases Matlab encountering extremely severe errors, <em>connectionLost(RemoteMatlabProxy proxy)</em> is called. Calling methods on this proxy will lead to exceptions being thrown, as it can no longer communicate with Matlab. The proxy is passed because this information is useful when controlling multiple sessions of Matlab simultaneously.<br />
When the &#8220;Invoke&#8221; button is pressed, the command and number of return arguments is sent to Matlab. If the number of return arguments is 0, the command will still execute but nothing will be returned. If the number is positive but less than the total number of return arguments, then only up to that number of arguments will be returned. If the number of return arguments specified exceeds the actual amount of arguments returned, a Java exception will be thrown. By default the fields are populated to return the result of &#8220;<em><b>sqrt</b>(5)</em>&#8220;. Press &#8220;Invoke&#8221; to see what happens. Change the number of return arguments to 0, and click &#8220;Invoke&#8221; again. Now change the number to 2 and try once more.<br />
<center><figure style="width: 372px" class="wp-caption aligncenter"><img decoding="async" alt="Invoking Matlab commands from Java using JMI" src="https://undocumentedmatlab.com/images/matlabcontrol_remote2.png" title="Invoking Matlab commands from Java using JMI" width="372" height="261" /><figcaption class="wp-caption-text">Invoking Matlab commands from Java using JMI</figcaption></figure></center><br />
When the Java program closes, it also exits Matlab. This is accomplished by adding a <em>WindowListener</em> to the program, which detects the Java closure event. It is important to call Matlab&#8217;s <i><b>exit</b></i> command as opposed to <i><b>eval</b>(&#8220;exit&#8221;)</i>, because all other proxy methods block (pause) until completion but in the case of exiting Matlab no signal will ever be sent by Matlab to indicate it has closed.</p>
<h3 id="return_vals">Parsing Matlab&#8217;s return values</h3>
<p>Our <i><b>eval</b></i> commands are being sent using <em>RemoteMatlabProxy</em>&#8216;s <em>returningEval(String command, int returnCount)</em> method, whose return type is <em>Object</em>, because Matlab can return multiple return types. For example, the expression &#8220;<em><b>sqrt</b>(5)</em>&#8221; will return an array of doubles, &#8220;<i><b>pwd</b></i>&#8221; will return a <em>java.lang.String</em>, and &#8220;<i><b>whos</b></i>&#8221; will return a complicated array of arrays with a variety of base types and <em>Object</em>s.<br />
This is what occurs in Matlab R2009b, but not necessarily in past or future versions. You will have to experiment to find out what is being returned on your particular platform. The demo can help as it lists everything returned, including array contents. The demo contains the <em>formatResult(Object result, int level)</em> method which recursively goes through the object returned from Matlab and builds a description of what it contains. As discussed in my introductory post on <em>matlabcontrol</em>, Matlab functions will either return a base type, an array of base types, or a <em>String</em>. However, if we call a Java function inside the Matlab environment then any Java object might be returned. This isn&#8217;t actually that absurd of a situation; it might arise if you are trying to control the Matlab UI.<br />
When returning Java objects from Matlab certain restrictions and limitations apply. First, the object must be <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a> because of the underlying use of RMI. In practice this isn&#8217;t a huge issue as a very large number of built-in Java classes are Serializable, and making your own classes Serializable is usually trivial.<br />
The second limitation is that whatever class you send from the Matlab environment to your Java program must be defined in your Java program. For any standard built-in Java class this won&#8217;t cause issues. However, if you attempt to send over classes custom to Matlab then your Java program must have those classes in its classpath (in practice this means reference the jar file containing that class). For HG (or rather, UDD) classes, you can use the following Matlab function to create a Java class interface that can be used in your Java code to access the Matlab object, or access the jar file that contains that class as explained above:</p>
<pre lang="matlab">
% This will create a figure.java file in the current folder:
myClassHandle = classhandle(handle(gcf));
myClassHandle.createJavaInterface(myClassHandle.name, pwd);
% alternately, you can use myClassHandle.JavaInterfaces{1}
% = 'com.mathworks.hg.Figure' in this particular case
% i.e., in your java code import com.mathworks.hg.Figure
</pre>
<p><i>(UDD will be described in much more detail in a future article that is currently being prepared)</i><br />
The third caveat is that you will be returned a copy of the Java object. This means that if you have a Java array in Matlab, send it to your Java program and then insert an object into the array, the array in Matlab will not be affected. However, you can then send that array back to Matlab, so in practice this does not cause significant issues. None of these restrictions are applicable to <em>matlabcontrol</em> for local sessions.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Today we have shown how a dedicated Matlab session can be started from a Java application, which then communicates with that Matlab session using the <em>matlabcontrol</em> package. This concludes my series on <em>matlabcontrol</em>. Please check out the <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol">matlabcontrol website</a> for more information, examples and updates. If you use <em>matlabcontrol</em>, filling out this <a target="_blank" rel="nofollow" href="https://spreadsheets.google.com/viewform?formkey=dENLNHB0YUotVUpHQUxqNHVremZveWc6MA">survey</a> so that I can improve it, would be greatly appreciated.<br />
<i>Since the past few articles were heavy on Matlab-Java topics, the next few articles will be devoted to undocumented pure-Matlab tips and tricks, starting next week with the topic of how to customize the default menubar and toolbar actions.</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol">JMI wrapper &#8211; remote MatlabControl</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 2">JMI wrapper &#8211; local MatlabControl part 2 </a> <small>An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-and-java" rel="bookmark" title="UDD and Java">UDD and Java </a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface" rel="bookmark" title="JMI &#8211; Java-to-Matlab Interface">JMI &#8211; Java-to-Matlab Interface </a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol/feed</wfw:commentRss>
			<slash:comments>29</slash:comments>
		
		
			</item>
		<item>
		<title>JMI wrapper &#8211; local MatlabControl part 2</title>
		<link>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jmi-wrapper-local-matlabcontrol-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 May 2010 21:00:59 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Joshua Kaplan]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1514</guid>

					<description><![CDATA[<p>An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2">JMI wrapper &#8211; local MatlabControl part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol" rel="bookmark" title="JMI wrapper &#8211; remote MatlabControl">JMI wrapper &#8211; remote MatlabControl </a> <small>An example using matlabcontrol for calling Matlab from a separate Java process is explained....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1" rel="bookmark" title="Explicit multi-threading in Matlab part 1">Explicit multi-threading in Matlab part 1 </a> <small>Explicit multi-threading can be achieved in Matlab by a variety of simple means. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome guest blogger Joshua Kaplan for his continued series on MatlabControl &#8211; the Java-to-Matlab Interface (JMI) wrapper</i><br />
Last week I <a target="_blank" href="/articles/jmi-wrapper-local-matlabcontrol-part-1/">introduced</a> a Java package called <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol"><i>matlabcontrol</i></a> which can be used to access Matlab from Java.<br />
Let&#8217;s now put <i>matlabcontrol</i> 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 <em>LocalMatlabProxy.eval(…)</em>, which was explained in the previous post.</p>
<pre lang="java">
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);
  }
}
</pre>
<p>We can either copy and compile the above code (remember to import the <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol/releases"><i>matlabcontrol</i> JAR file</a> in your compiler; four class files will be created), or download the already-compiled code <a target="_blank" href="/files/LocalExample.zip">here</a>. 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.<br />
We now need to tell Matlab where to find both the <i>matlabcontrol</i> 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&#8217;s dynamic classpath:</p>
<pre lang="matlab">
% Add Java files to current Matlab session's dynamic classpath
javaaddpath LocalExample.zip
javaaddpath matlabcontrol-3.01.jar
</pre>
<p>To run the Java program, simply type <i>LocalExample</i> in the Matlab Command Window &#8211; A small Java window will appear and JMI will evaluate any expression typed into it:</p>
<pre lang="matlab">
>> LocalExample
ans =
LocalExample[frame0,0,0,202x67,title=Local Session Example,...]
</pre>
<p><center><figure style="width: 202px" class="wp-caption aligncenter"><img decoding="async" alt="Java window calling Matlab via JMI" src="https://undocumentedmatlab.com/images/matlabcontrol_local.png" title="Java window calling Matlab via JMI" width="202" height="67" /><figcaption class="wp-caption-text">Java window calling Matlab via JMI</figcaption></figure></center></p>
<pre lang="matlab">
a =
          1.77245385090552
</pre>
<p>When we called <em>LocalMatlabControl.eval(…)</em> from the Command Window last week, what occurred behind the scenes was actually quite different from what happens when we press the &#8220;eval&#8221; button in the Java program. This is because in the Command Window everything executes in Matlab&#8217;s single main thread. When we pressed &#8220;eval&#8221;, the code executed from the <a target="_blank" href="/articles/matlab-and-the-event-dispatch-thread-edt/">Event Dispatch Thread (EDT)</a>, which is a separate thread.<br />
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/<i>matlabcontrol</i> from the EDT and Matlab needed to use the EDT, then everything will lock up. To fix this potential problem, when you press the &#8220;eval&#8221; button the command is sent off to a separate thread which can block without preventing Matlab from doing its work. Future versions of <i>matlabcontrol</i> will try to simplify this process further. <i>matlabcontrol</i> 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).<br />
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 <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol/tree/master/matlabcontrol-demo">demo available here</a> (<a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol/releases">downloadable JAR</a>). 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 <i>matlabcontrol</i> over a remote connection.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2">JMI wrapper &#8211; local MatlabControl part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol" rel="bookmark" title="JMI wrapper &#8211; remote MatlabControl">JMI wrapper &#8211; remote MatlabControl </a> <small>An example using matlabcontrol for calling Matlab from a separate Java process is explained....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1" rel="bookmark" title="Explicit multi-threading in Matlab part 1">Explicit multi-threading in Matlab part 1 </a> <small>Explicit multi-threading can be achieved in Matlab by a variety of simple means. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>JMI wrapper &#8211; local MatlabControl part 1</title>
		<link>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jmi-wrapper-local-matlabcontrol-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 12 May 2010 19:05:15 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Joshua Kaplan]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1354</guid>

					<description><![CDATA[<p>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.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1">JMI wrapper &#8211; local MatlabControl part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 2">JMI wrapper &#8211; local MatlabControl part 2 </a> <small>An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol" rel="bookmark" title="JMI wrapper &#8211; remote MatlabControl">JMI wrapper &#8211; remote MatlabControl </a> <small>An example using matlabcontrol for calling Matlab from a separate Java process is explained....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setprompt-setting-matlab-desktop-prompt" rel="bookmark" title="setPrompt &#8211; Setting the Matlab Desktop prompt">setPrompt &#8211; Setting the Matlab Desktop prompt </a> <small>The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger Joshua Kaplan, who continues his series of JMI-related articles</i></p>
<h3 id="MatlabControl">Local and remote MatlabControl</h3>
<p>Several weeks ago, I discussed the undocumented world of <a target="_blank" href="/articles/jmi-java-to-matlab-interface/">JMI (Java-to-Matlab Interface)</a>, that enables calling Matlab from Java. Today I will discuss <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol">matlabcontrol</a>, an open-source wrapper I have written for JMI, that is both documented and user-friendly.<br />
<em>matlabcontrol</em> 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 <em>matlabcontrol</em>&#8216;s local control methods; in my next post we&#8217;ll create a simple Java program that uses <em>matlabcontrol</em> for local control; a later post will discuss the remote control path. These posts assume a medium to high level of Java experience.<br />
<em>matlabcontrol</em> is a collection of Java classes, bundled together in a <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol/releases">downloadable</a> 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&#8217;ve downloaded the jar file &#8211; you&#8217;ll need to use this information shortly.<br />
For local control we&#8217;ll interact with the classes <em>LocalMatlabProxy</em> and <em>MatlabInvocationException</em>. <em>LocalMatlabProxy</em> contains all the methods required for calling Matlab; instances of <em>MatlabInvocationException</em> will be thrown when a problem occurs while attempting to control Matlab.<br />
To tell Matlab where matlabcontrol-3.01.jar is, add the jar file path to Matlab&#8217;s dynamic (via the built-in <i><b>javaaddpath</b></i> function) or static (via <i><b>edit</b>(&#8216;classpath.txt&#8217;)</i>) 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.<br />
Matlab now knows where to find the Java class files in <em>matlabcontrol</em>. To save some typing later on, type the following in the Matlab Command Window (or in your JMI-empowered Matlab application):</p>
<pre lang="java">import matlabcontrol.*</pre>
<h3 id="LocalMatlabProxy">LocalMatlabProxy methods</h3>
<p><em>LocalMatlabProxy</em> is easy to use. All of its methods are static meaning they can be called without needing to assign <em>LocalMatlabProxy</em> to a variable. The methods are:</p>
<pre lang="java">
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)
</pre>
<p>Detailed <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol/releases">javadocs</a> exist for all these methods. Here is an overview:</p>
<ul>
<li><em>exit()</em> 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:
<pre lang="matlab"> LocalMatlabProxy.exit();</pre>
</li>
<li>Setting and getting variables can be done using the <em>getVariable(…)</em> and <em>setVariable(…)</em> methods. These methods will auto-convert between Java and Matlab types where applicable.<br />
&nbsp;&nbsp; Using <em>getVariable(…)</em>:</p>
<ul>
<li>Java types in the Matlab environment retrieved will be returned as Java types.</li>
<li>Matlab types will be <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f6425.html#bq__5xw-1">converted into Java types</a>.</li>
</ul>
<p>&nbsp;&nbsp; Using <em>setVariable(…)</em>:</p>
<ul>
<li>Java types will be converted into Matlab types if they can. The rules are outlined <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f6671.html#bq__508-1">here</a>. 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.</li>
</ul>
<p>&nbsp;&nbsp; Using these methods is fairly intuitive:</p>
<pre lang="matlab">
 >> LocalMatlabProxy.setVariable('x',5)
>> LocalMatlabProxy.getVariable('x')
ans =
     5
</pre>
<p>&nbsp;&nbsp; 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 <em>setVariable(…)</em>, or getting a Matlab struct or cell array using <em>getVariable(…)</em>. 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.</li>
<li>The <i>eval()</i> and <i>feval()</i> methods were described in detail in my <a target="_blank" rel="nofollow" href="/articles/jmi-java-to-matlab-interface/">previous post</a>. 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 <i><b>nargout</b></i> function reveals this number. Some functions (e.g., <i><b>feval</b></i>) return a variable number of arguments, in which case <i><b>nargout</b></i> returns -1. For instance:
<pre lang="matlab">
 >> nargout sqrt
ans =
     1
>> nargout feval
ans =
     -1
</pre>
</li>
<li><em>LocalMatlabProxy</em>&#8216;s <em>returningFeval(functionName, args)</em> method uses the <i><b>nargout</b></i> 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 <em>returningFeval(…)</em> with a third input argument that specifies the expected number of returned arguments. Since an <i>eval()</i> 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 <em>returningEval(…)</em> can be used with a return count of 1, and the <em>returningFeval(…)</em> that automatically determines the return count will operate as expected.</li>
</ul>
<h3 id="Examples">Some simple usage examples</h3>
<p>Let&#8217;s perform some of the same simple square root operations we did in the <a target="_blank" href="/articles/jmi-java-to-matlab-interface/">pure-JMI article</a>, this time using <em>matlabcontrol</em>. First we&#8217;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):</p>
<pre lang="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
</pre>
<p>In this situation there is no major difference between using <em>eval()</em> or <em>feval()</em> 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 <em>eval()</em> is our only option.</p>
<pre lang="matlab">
>> 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
</pre>
<p>The automatic Matlab/Java type conversions discussed above are equally applicable to <i>eval()</i> and <i>feval()</i>. <i>feval()</i> automatically converted the argument &#8216;a&#8217; into a Matlab char, instead of considering it as a Matlab variable. As seen above, the <i>feval()</i> invocation fails with a Java <em>MatlabInvocationException</em>. So, the only way to interact with Matlab variables is via <i>eval()</i> methods; <i>feval()</i> will not work.<br />
Lastly there is the <em>setEchoEval(echoFlag)</em> method: If this method is called with a <i>true</i> argument, then all Java to Matlab calls will be logged in a dedicated window. This can be very helpful for debugging.<br />
In my next post we shall put together this knowledge to create a small Java program that uses <em>matlabcontrol</em> to interact with Matlab.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1">JMI wrapper &#8211; local MatlabControl part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-2" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 2">JMI wrapper &#8211; local MatlabControl part 2 </a> <small>An example using matlabcontrol for calling Matlab from within a Java class is explained and discussed...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-remote-matlabcontrol" rel="bookmark" title="JMI wrapper &#8211; remote MatlabControl">JMI wrapper &#8211; remote MatlabControl </a> <small>An example using matlabcontrol for calling Matlab from a separate Java process is explained....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setprompt-setting-matlab-desktop-prompt" rel="bookmark" title="setPrompt &#8211; Setting the Matlab Desktop prompt">setPrompt &#8211; Setting the Matlab Desktop prompt </a> <small>The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>JMI &#8211; Java-to-Matlab Interface</title>
		<link>https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jmi-java-to-matlab-interface</link>
					<comments>https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 14 Apr 2010 21:46:42 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Joshua Kaplan]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1279</guid>

					<description><![CDATA[<p>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface">JMI &#8211; Java-to-Matlab Interface</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab" rel="bookmark" title="Java stack traces in Matlab">Java stack traces in Matlab </a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matclipse-eclipse-matlab-interface" rel="bookmark" title="Matclipse &#8211; Eclipse-Matlab interface">Matclipse &#8211; Eclipse-Matlab interface </a> <small>Matclipse is an open-source plugin for the popular Eclipse IDE that connects it with Matlab. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome guest writer Joshua Kaplan, an expert in one of the darkest undocumented corners of Matlab &#8211; that of the Java-to-Matlab interface (JMI). Today, Joshua will introduce JMI and its core functionality. Later articles will explore additional aspects of this complex technology.</i><br />
As you&#8217;ve seen many times on this blog before, Matlab can easily call Java. This article explores the dark undocumented territory known as JMI (Java Matlab Interface) that enables calling Matlab from Java. This interface takes the form of a file called jmi.jar that comes with every copy of Matlab released in the past decade. JAR files are essentially a zip file containing Java class files. In this case, several Java classes in jmi.jar enable interaction with Matlab. This post will discuss the most important class: com.mathworks.jmi.Matlab.</p>
<h3 id="eval">Matlab&#8217;s dynamic evaluation functions</h3>
<p>JMI easily allows calling two built-in Matlab functions: <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/eval.html"><i><b>eval</b></i></a> and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/feval.html"><i><b>feval</b></i></a>.  Essentially, <i><b>eval</b></i> evaluates any string typed into Matlab&#8217;s Command Window, and <i><b>feval</b></i> allows calling any function by name and passing in arguments. For example:</p>
<pre lang="matlab">
>> sqrt(5)
ans =
    2.2361
>> eval('sqrt(5)')
ans =
    2.2361
>> feval('sqrt',5)
ans =
    2.2361
</pre>
<p>The first approach takes the square root of 5 normally by directly calling Matlab&#8217;s square root function <i><b>sqrt</b></i>. JMI does not enable this direct-invocation approach. Instead, JMI uses the second approach, where <i><b>eval</b></i> mimics the first call by evaluating the entire expression inside single quotes. The third option, also used by JMI, is to use <i><b>feval</b></i> where the function and arguments are specified separately. While in the above example calling <i><b>eval</b></i> and <i><b>feval</b></i> is very similar, there are differences. For instance, assignment can be done as x=5 or <i><b>eval</b></i>(‘x=5’) but there is no <i><b>feval</b></i> equivalent. There are also other <i><b>eval</b></i> relatives, such as <i><b>hgfeval</b></i>, <i><b>evalc</b></i> and <i><b>evalin</b></i>, which will not be explained today.<br />
Before we explore com.mathworks.jmi.Matlab, it is important to note a few things: Everything that follows is based on many hours of experimentation and online research and so while I am more or less certain of what I am about to explain, it could be deficient or incorrect in many respects. In fact, this area is so undocumented that an <a target="_blank" rel="nofollow" href="http://www.mathworks.com/company/newsletters/news_notes/win02/patterns.html">article written in 2002</a> by one of The MathWorks employees and published in the official newsletter, has been removed from their website a year or two ago.<br />
Secondly, this post is written to satisfy people&#8217;s curiosities regarding JMI. If you actually wish to call Matlab from Java, I strongly suggest you use <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol">MatlabControl</a>, a user-friendly Java library I have written that wraps JMI. There are many complications that arise with threading, method completion blocking, virtual machine restrictions, and other domains that prevent using JMI directly to be practical and reliable.</p>
<h3 id="mtEval">com.mathworks.jmi.Matlab class and its mtEval() method</h3>
<p>With all of that said, let&#8217;s dive in! In the Matlab Command Window type:</p>
<pre lang="matlab">methodsview('com.mathworks.jmi.Matlab')</pre>
<p>You will see all of the <em>Matlab</em> class&#8217;s numerous methods. Many of the methods have extremely similar names; many others have the same names and just different parameters. In order to call <i><b>eval</b></i> and <i><b>feval</b></i> we are going to use two of <em>Matlab</em>&#8216;s methods:</p>
<pre lang="java">
public static Object mtEval(String command, int returnCount)
public static Object mtFeval(String functionName, Object[] args, int returnCount)
</pre>
<p>Since Matlab can call Java, we can experiment with these methods from Matlab. That&#8217;s right, we&#8217;re about to use Matlab to call Java to call Matlab!<br />
First, let&#8217;s import the Java package that contains the Matlab class, to reduce typing:</p>
<pre lang="matlab">import com.mathworks.jmi.*</pre>
<p>Now let&#8217;s take the square root of 5 like we did above, but this time from Java. Using JMI&#8217;s <i><b>eval</b></i>-equivalent:</p>
<pre lang="matlab">Matlab.mtEval('sqrt(5)',1)</pre>
<p>Here, &#8216;sqrt(5)&#8217; is what will be passed to <i><b>eval</b></i>, and 1 signifies that <em>Matlab</em> should expect one value to be returned. It is important that the second argument be accurate. If instead the call had been:</p>
<pre lang="matlab">Matlab.mtEval('sqrt(5)',0)</pre>
<p>Then an empty string (&#8221;) will be returned. If instead, 2 or more were passed in:</p>
<pre lang="matlab">Matlab.mtEval('sqrt(5)',2)</pre>
<p>Then a Java exception like the one below will occur:<br />
<font color="red"></p>
<pre>
??? Java exception occurred:
com.mathworks.jmi.MatlabException: Error using ==> sqrt
Too many output arguments.
    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.mtFeval(Matlab.java:1478)
    at com.mathworks.jmi.Matlab.mtEval(Matlab.java:1439)
</pre>
<p></font><br />
Looking at this exception&#8217;s stack trace we notice that <em>mtEval()</em> is actually internally calling <em>mtFeval()</em>.</p>
<h3 id="mtFeval">com.mathworks.jmi.Matlab class&#8217;s mtFeval() method</h3>
<p>Now to perform the square root using JMI&#8217;s <i><b>feval</b></i>-equivalent:</p>
<pre lang="matlab">Matlab.mtFeval('sqrt',5,1)</pre>
<p>Here, &#8216;sqrt&#8217; is the name of the Matlab function to be called, 5 is the argument to the function, and 1 is the expected number of return values. Again, the number of return values. If this number is specified as 0 instead of 1, the function call will still succeed, although not all of the results will necessarily be returned. The second <em>mtFeval()</em> argument, which specifies the arguments to the invoked Matlab function, can take any number of arguments as an array. Therefore the following is acceptable:</p>
<pre lang="matlab">Matlab.mtFeval('sqrt',[5 3],1)</pre>
<p>This will return an array containing both of their square roots. Note that although two vales are returned, they are considered as only 1 since it is a single array that is returned.<br />
Multiple Matlab arguments can be specified in <em>mtFeval()</em> using a cell array. For example, consider the following equivalent formats (note the different returned array orientation):</p>
<pre lang="matlab">
>> min(1:4,2)
ans =
     1     2     2     2
>> Matlab.mtFeval('min',{1:4,2},1)
ans =
     1
     2
     2
     2
</pre>
<p>As we observed above, <em>mtEval()</em> is really just calling <em>mtFeval()</em>. This works because <i><b>eval</b></i> is a function, so <i><b>feval</b></i> can call it. An illustration:</p>
<pre lang="matlab">Matlab.mtFeval('eval','sqrt(5)',1)</pre>
<h3 id="mtFevalConsoleOutput">com.mathworks.jmi.Matlab class&#8217;s mtFevalConsoleOutput() method</h3>
<p>Both <em>mtFeval()</em> and <em>mtEval()</em> have allowed us to interact with Matlab, but the effects are not shown in the Command Window. There is a method that will allow us to do this:</p>
<pre lang="java">public static Object mtFevalConsoleOutput(String functionName, Object[] args, int returnCount)</pre>
<p><em>mtFevalConsoleOutput()</em> is just liked the <em>mtFeval()</em> command except that its effects will be shown. For instance:</p>
<pre lang="matlab">
>> Matlab.mtFeval('disp','hi',0);  % no visible output
>> Matlab.mtFevalConsoleOutput('disp','hi',0);
hi
</pre>
<p>There is no equivalent <em>mtEvalConsoleOutput()</em> method, but that&#8217;s not a problem because we have seen that <i><b>eval</b></i> can be accomplished using <i><b>feval</b></i>:</p>
<pre lang="matlab">
>> Matlab.mtFevalConsoleOutput('eval','x=5',0);
x =
     5
</pre>
<h3 id="others">Other methods in com.mathworks.jmi.Matlab</h3>
<p>There are many more <i><b>eval</b></i> and <i><b>feval</b></i> methods in the <em>Matlab</em> class. Most of these methods&#8217; names begin with eval or feval instead of mtEval and mtFeval. Many of these methods are asynchronous, which means their effect on Matlab can occur after the method call returns. This is often problematic because if one method call creates a variable which is then used by the next call, there is no guarantee that the first call has completed (or even begun) by the time the second call tries to use the new variable. Unlike <em>mtEval()</em> and <em>mtFeval()</em>, these methods are not static, meaning we must have an instance of the Java class Matlab:</p>
<pre lang="matlab">
>> proxy = Matlab
proxy =
com.mathworks.jmi.Matlab@1faf67f0
</pre>
<p>Using this instance we will attempt to assign a variable and then retrieve it into a different variable. The result will be a Java exception indicating that &#8216;a&#8217; does not currently exist:</p>
<pre lang="matlab">
>> proxy.evalConsoleOutput('a=5'); b = proxy.mtEval('a',1)
??? Java exception occurred:
com.mathworks.jmi.MatlabException: Error using ==> eval
Undefined function or variable 'a'.
    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.mtFeval(Matlab.java:1478)
    at com.mathworks.jmi.Matlab.mtEval(Matlab.java:1439)
a =
     5
</pre>
<p>If you run the above code you are not guaranteed to get that exception because of the nature of asynchronous method calls. However, this inherent unpredictability makes it difficult to perform almost any sequential action. Therefore, it is best to stick to <em>mtEval</em>, <em>mtFeval</em>, and <em>mtFevalConsoleOutput</em>, where this type of exception will be very remote. (They can still occur, about 1 in 100 times, as to why – I&#8217;d love to know as well.)<br />
Two particular methods that may come in handy are <em>mtSet()</em> and <em>mtGet()</em>, which are the Java proxies for the Matlab <i><b>set</b></i> and <i><b>get</b></i> functions &#8211; they accept a Matlab handle (a double value) and a property name (a string) and either set the value or return it. Like Matlab, they also accept an array of property names. This can be used to update Matlab HG handles from within Java code, without needing to pass through an intermediary Matlab eval function:</p>
<pre lang="matlab">
>> Matlab.mtSet(gcf,'Color','b')
>> Matlab.mtGet(gcf,'Color')
ans =
     0
     0
     1
>> Matlab.mtGet(gcf,{'Color','Name'})
ans =
java.lang.Object[]:
    [3x1 double]
    'My figure'
</pre>
<h3 id="summary">Summary</h3>
<p>With just <i><b>eval</b></i> and <i><b>feval</b></i>, an enormous amount of Matlab&#8217;s functionality can be accessed from Java. For instance, this allows for creating sophisticated Java GUIs with Swing and then being able to call Matlab code when the user clicks a button or moves a slider.<br />
My next post will be on using MatlabControl to control Matlab from Java from within Matlab. The following post will discuss doing the same, but from a Java program launched outside of Matlab.<br />
<b><u>Addendum 2016-10-21:</b></u> In R2016b, MathWorks has finally released <a href="http://www.mathworks.com/help/matlab/matlab-engine-api-for-java.html" rel="nofollow" target="_blank">a documented connector</a> from Java to the Matlab engine, which should be used in place of JMI where possible.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface">JMI &#8211; Java-to-Matlab Interface</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab" rel="bookmark" title="Java stack traces in Matlab">Java stack traces in Matlab </a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jmi-wrapper-local-matlabcontrol-part-1" rel="bookmark" title="JMI wrapper &#8211; local MatlabControl part 1">JMI wrapper &#8211; local MatlabControl part 1 </a> <small>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....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matclipse-eclipse-matlab-interface" rel="bookmark" title="Matclipse &#8211; Eclipse-Matlab interface">Matclipse &#8211; Eclipse-Matlab interface </a> <small>Matclipse is an open-source plugin for the popular Eclipse IDE that connects it with Matlab. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface/feed</wfw:commentRss>
			<slash:comments>27</slash:comments>
		
		
			</item>
	</channel>
</rss>
