<?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>JMI &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/jmi/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 19 Feb 2014 19:10:55 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Explicit multi-threading in Matlab part 1</title>
		<link>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=explicit-multi-threading-in-matlab-part1</link>
					<comments>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Feb 2014 19:10:55 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4659</guid>

					<description><![CDATA[<p>Explicit multi-threading can be achieved in Matlab by a variety of simple means. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1">Explicit multi-threading in Matlab 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/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-threaded-mex" rel="bookmark" title="Multi-threaded Mex">Multi-threaded Mex </a> <small>Tips for creating and debugging multi-threaded Mex functions are discussed. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of the limitations of Matlab already <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/2713218/how-to-do-threading-in-matlab">recognized by the community</a>, is that it does not provide the users direct access to threads without the PCT (Parallel Computing Toolbox). For example, letting some expensive computations or I/O to be run in the background without freezing the main application. Instead, in Matlab there is either <i>implicit multiprocessing</i> which relies on built-in threading support in some MATLAB functions, or <i>explicit multiprocessing</i> using PCT (note: PCT workers use heavyweight processes, not lightweight threads). So the only way to achieve truly multi-threading in Matlab is via MEX, Java or .Net, or by spawning external standalone processes (yes, there are a few other esoteric variants &#8211; don&#8217;t nit-pick).<br />
Note that we do not save any CPU cycles by running tasks in parallel. In the overall balance, we actually increase the amount of CPU processing, due to the multi-threading overhead. However, in the vast majority of cases we are more interested in the responsivity of Matlab&#8217;s main processing thread (known as the <i>Main Thread</i>, <i>Matlab Thread</i>, or simply <i>MT</i>) than in reducing the computer&#8217;s total energy consumption. In such cases, offloading work to asynchronous C++, Java or .Net threads could remove bottlenecks from Matlab&#8217;s main thread, achieving significant speedup.<br />
Today&#8217;s article is a derivative of a much larger section on explicit multi-threading in Matlab, that will be included in my upcoming book <a target="_blank" rel="nofollow" href="http://www.crcpress.com/product/isbn/9781482211290"><i>MATLAB Performance Tuning</i></a>, which will be published later this year. It is the first in a series of articles that will be devoted to various alternatives.</p>
<h3 id="Problem">Sample problem</h3>
<p>In the following example, we compute some data, save it to file on a relatively slow USB/network disk, and then proceed with another calculation. We start with a simple synchronous implementation in plain Matlab:</p>
<pre lang='matlab'>
tic
data = rand(5e6,1);  % pre-processing, 5M elements, ~40MB
fid = fopen('F:\test.data','w');
fwrite(fid,data,'double');
fclose(fid);
data = fft(data);  % post-processing
toc
Elapsed time is 9.922366 seconds.
</pre>
<p>~10 seconds happens to be too slow for our specific needs. We could perhaps improve it a bit with some fancy tricks for <a target="_blank" href="/articles/improving-save-performance/"><i><b>save</b></i></a> or <a target="_blank" href="/articles/improving-fwrite-performance/"><i><b>fwrite</b></i></a>. But let&#8217;s take a different approach today, using multi-threading:</p>
<h3 id="Java">Using Java threads</h3>
<p>Matlab uses Java for numerous tasks, including networking, data-processing algorithms and graphical user-interface (GUI). In fact, under the hood, even Matlab timers employ Java threads for their internal triggering mechanism. In order to use Java, Matlab launches its own dedicated JVM (Java Virtual Machine) when it starts (unless it&#8217;s started with the <i>-nojvm</i> startup option). Once started, Java can be directly used within Matlab as a natural extension of the Matlab language. Today I will only discuss Java multithreading and its potential benefits for Matlab users: Readers are assumed to know how to program Java code and how to compile Java classes.<br />
To use Java threads in Matlab, first create a class that implements the <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html"><code>Runnable</code></a> interface or extends <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html">java.lang.Thread</a>. In either case we need to implement at least the <i>run()</i> method, which runs the thread&#8217;s processing core.<br />
Now let us replace the serial I/O with a very simple dedicated Java thread. Our second calculation (<i><b>fft</b></i>) will not need to wait for the I/O to complete, enabling much faster responsiveness on Matlab&#8217;s MT. In this case, we get a 58x (!) speedup:<br />
<span id="more-4659"></span></p>
<pre lang='matlab'>
tic
data = rand(5e6,1);  % pre-processing (5M elements, ~40MB)
javaaddpath 'C:\Yair\Code\'  % path to MyJavaThread.class
start(MyJavaThread('F:\test.data',data));  % start running in parallel
data = fft(data);  % post-processing (Java I/O runs in parallel)
toc
Elapsed time is 0.170722 seconds.   % 58x speedup !!!
</pre>
<p>Note that the call to <i><b>javaaddpath</b></i> only needs to be done once in the entire Matlab session, not repeatedly. The definition of our Java thread class is very simple (real-life classes would not be as simplistic, but the purpose here is to show the basic concept, not to teach Java threading):</p>
<pre lang='csharp'>
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class MyJavaThread extends Thread
{
    String filename;
    double[] doubleData;
    public MyJavaThread(String filename, double[] data)
    {
        this.filename = filename;
        this.doubleData = data;
    }
    @Override
    public void run()
    {
        try
        {
            DataOutputStream out = new DataOutputStream(
                                     new FileOutputStream(filename));
            for (int i=0; i < doubleData.length; i++)
            {
                out.writeDouble(doubleData[i]);
            }
            out.close();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}
</pre>
<p>Note: when compiling a Java class that should be used within Matlab, as above, ensure that you are compiling for a JVM version that is equal to, or lower than Matlab's JVM, as reported by Matlab's version function:</p>
<pre lang='matlab'>
% Matlab R2013b uses JVM 1.7, so we can use JVMs up to 7, but not 8
>> version –java
ans =
Java 1.7.0_11-b21 ...
</pre>
<h3 id="Synchronization">Matlab synchronization</h3>
<p>Java (and C++/.Net) threads are very effective when they can run entirely independently from Matlab’s main thread. But what if we need to synchronize the other thread with Matlab&#8217;s MT? For example, what if the Java code needs to run some Matlab function, or access some Matlab data? In MEX this could be done using the dedicated and documented MEX functions; in Java this can be done using the undocumented/unsupported <a target="_blank" href="/articles/jmi-java-to-matlab-interface/">JMI (Java-Matlab Interface) package</a>. Note that using standard Java Threads without Matlab synchronization is fully supported; it is only the JMI package that is undocumented and unsupported.<br />
Here is the relevant code snippet for evaluating Matlab code within a Java thread:</p>
<pre lang='java'>
import com.mathworks.jmi.Matlab;  //in %matlabroot%/java/jar/jmi.jar
...
Matlab matlabEngine = new Matlab();
...
Matlab.whenMatlabReady(runnableClass);
</pre>
<p>Where <code>runnableClass</code> is a class whose <i>run()</i> method includes calls to <code>com.mathworks.jmi.Matlab</code> methods such as:</p>
<pre lang='java'>
matlabEngine.mtEval("plot(data)");
Double value = matlabEngine.mtFeval("min",{a,b},1); //2 inputs 1 output
</pre>
<p>Unfortunately, we cannot directly call <code>matlabEngine</code>&#8216;s methods in our Java thread, since this is blocked in order to ensure synchronization Matlab only enables calling these methods from the MT, which is the reason for the <code>runnableClass</code>. Indeed, synchronizing Java code with MATLAB could be quite tricky, and can easily deadlock MATLAB. To alleviate some of the risk, I advise not to use the JMI class directly: use Joshua Kaplan&#8217;s <a target="_blank" rel="nofollow" href="https://github.com/jakaplan/matlabcontrol"><code>MatlabControl</code></a> class, a user-friendly JMI wrapper.<br />
Note that Java&#8217;s native <i>invokeAndWait()</i> method cannot be used to synchronize with Matlab. M-code executes as a single uninterrupted thread (MT). Events are simply queued by Matlab&#8217;s interpreter and processed when we relinquish control by requesting <i><b>drawnow</b></i>, <i><b>pause</b></i>, <i><b>wait</b></i>, <i><b>waitfor</b></i> etc. Matlab synchronization is robust and predictable, yet forces us to use the <code>whenMatlabReady(runnableClass)</code> mechanism to add to the event queue. The next time <i><b>drawnow</b></i> etc. is called in M-code, the event queue is purged and our submitted code will be processed by Matlab&#8217;s interpreter.<br />
Java threading can be quite tricky even without the Matlab synchronization complexity.  Deadlock, starvation and race conditions are frequent problems with Java threads. Basic Java synchronization is relatively easy, using the <code>synchronized</code> keyword. But getting the synchronization to work <i>correctly</i> is much more difficult and requires Java programming expertise that is beyond most Java programmers. In fact, many Java programmers who use threads are not even aware that their threads synchronization is buggy and that their code is not thread-safe.<br />
My general advise is to use Java threads just for simple independent tasks that require minimal interactions with other threads, Matlab engine, and/or shared resources.</p>
<h3 id="Alternatives">Additional alternatives and musings</h3>
<p>In addition to Java threads, we can use other technologies for multi-threading in Matlab: Next week&#8217;s article will explore Dot-Net (C#) threads and timers, and that will be followed by a variety of options for C++ threads and spawned-processes IPC. So don&#8217;t let anyone complain any longer about not having explicit multi-threading in Matlab. It&#8217;s not trivial, but it&#8217;s also not rocket science, and there are plenty of alternatives out there.<br />
Still, admittedly MT&#8217;s current single-threaded implementation is a pain-in-the-so-and-so, relic of a decades-old design. A likely future improvement to the Matlab M-code interpreter would be to make it thread-safe. This would enable automatic conversion of <i><b>for</b></i> loops into multiple threads running on multiple local CPUs/cores, significantly improving Matlab&#8217;s standard performance and essentially eliminating the need for a separate <i><b>parfor</b></i> in PCT (imagine me drooling here). Then again, this might reduce PCT sales&#8230;</p>
<h3 id="course">Advanced Matlab Programming course – London 10-11 March, 2014</h3>
<p>If Matlab performance interests you, consider joining my <a target="_blank" href="/training">Advanced Matlab Programming course</a> in London on 10-11 March, 2014. In this course/seminar I will explore numerous other ways by which we can improve Matlab&#8217;s performance and create professional code. This is a unique opportunity to take your Matlab skills to a higher level within a couple of days. <b><u>Registration closes this Friday</u></b>, so don&#8217;t wait too long.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1">Explicit multi-threading in Matlab 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/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-threaded-mex" rel="bookmark" title="Multi-threaded Mex">Multi-threaded Mex </a> <small>Tips for creating and debugging multi-threaded Mex functions are discussed. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1/feed</wfw:commentRss>
			<slash:comments>31</slash:comments>
		
		
			</item>
		<item>
		<title>Java stack traces in Matlab</title>
		<link>https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-stack-traces-in-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 07 Mar 2012 18:00:35 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[JMI]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2783</guid>

					<description><![CDATA[<p>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab">Java stack traces in Matlab</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/handling-red-java-console-errors" rel="bookmark" title="Handling red Java console errors">Handling red Java console errors </a> <small>Red Java errors are sometimes displayed in the Matlab console. They can be removed or avoided in a variety of means. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>When debugging Java events in Matlab callbacks, it is sometimes useful to check the stack trace of the originating Java code. Matlab&#8217;s built-in <i><b>dbstack</b></i> function only reports the stack-trace of Matlab code, and any prior Java code in the stack trace is not reported. Knowing this information is also extremely important when debugging Java components that are used in Matlab, especially when using the Java-to-Matlab Interface (<a target="_blank" href="/tag/JMI/">JMI</a>).<br />
Let&#8217;s use a specific example to illustrate: Matlab&#8217;s <i><b>uitable</b></i> passes information back and forth between its underlying Java code and Matlab, via the <i><b>arrayviewfunc</b></i> Matlab function (<i>%matlabroot%/toolbox/matlab/codetools/arrayviewfunc.m</i>). If we place a breakpoint in <i><b>arrayviewfunc</b></i> and then update the table&#8217;s data, <i><b>dbstack</b></i> will only report the Matlab stack:</p>
<pre lang='matlab'>
% Prepare an empty uitable
>> hTable = uitable('ColumnName',{'a','b','c'});
% Place a breakpoint in arrayviewfunc
>> dbstop in arrayviewfunc at reportValuesCallback
>> dbstatus
Breakpoint for arrayviewfunc>reportValuesCallback is on line 588.
% Update the table data and wait for the breakpoint to trigger
>> set(hTable,'Data',magic(3));
% Check the Matlab stack trace – no sign of the invoking Java code
K>> dbstack
> In arrayviewfunc>reportValuesCallback at 588
  In arrayviewfunc at 42
</pre>
<p>To see the originating Java stack trace, we can use <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html"><code>java.lang.Thread</code></a>&#8216;s static <i>dumpStack()</i> method, which spills the <a target="_blank" rel="nofollow" href="http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/">Java stack trace</a> onto the stderr console (will appear in red in Matlab&#8217;s Command Window):</p>
<pre lang='matlab'>
K>> java.lang.Thread.dumpStack
java.lang.Exception: Stack trace
   at java.lang.Thread.dumpStack(Unknown Source)
   at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
   at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:219)
   at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:121)
   at com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1550)
   at com.mathworks.hg.peer.ui.table.DefaultUIStyleTableModel$UITableValueTableModel$1.runOnMatlabThread(DefaultUIStyleTableModel.java:467)
   at com.mathworks.jmi.MatlabWorker$2.run(MatlabWorker.java:79)
   at com.mathworks.jmi.NativeMatlab.dispatchMTRequests(NativeMatlab.java:364)
</pre>
<p>To access and possibly parse the originating Java stack trace, we can use the <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/1069066/get-current-stack-trace-in-java">following trick</a>:</p>
<pre lang='matlab'>
K>> st = java.lang.Thread.currentThread.getStackTrace;
K>> for idx = 2 : length(st), disp(st(idx)); end
com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:219)
com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:121)
com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1550)
com.mathworks.hg.peer.ui.table.DefaultUIStyleTableModel$UITableValueTableModel$1.runOnMatlabThread(DefaultUIStyleTableModel.java:467)
com.mathworks.jmi.MatlabWorker$2.run(MatlabWorker.java:79)
com.mathworks.jmi.NativeMatlab.dispatchMTRequests(NativeMatlab.java:364)
</pre>
<p>Each of the stack trace elements can be inspected, to get specific properties:</p>
<pre lang='matlab'>
K>> st(1).getFileName
ans =
     []		% empty = unknown
K>> st(2).get
	Class = [ (1 by 1) java.lang.Class array]
	ClassName = com.mathworks.jmi.NativeMatlab
	FileName = NativeMatlab.java
	LineNumber = [-2]
	MethodName = SendMatlabMessage
	NativeMethod = on
K>> st(2).isNativeMethod
ans =
     1		% 1 = true
K>> char(st(2).getFileName)  % cast java.lang.String to a Matlab char
ans =
NativeMatlab.java
K>> st(2).getLineNumber
ans =
    -2		% negative = unknown
K>> st(5).get
	Class = [ (1 by 1) java.lang.Class array]
	ClassName = com.mathworks.jmi.Matlab
	FileName = Matlab.java
	LineNumber = [1550]
	MethodName = mtFeval
	NativeMethod = off
</pre>
<p>This works well in JVM 1.5 (i.e., Matlab 7.04 or R14 SP2) and higher. In older Matlab releases you can use a slight modification:</p>
<pre lang='matlab'>
K>> t = java.lang.Throwable; st=t.getStackTrace;
K>> for idx = 1 : length(st), disp(st(idx)); end
com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
... (etc.)
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab">Java stack traces in Matlab</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/handling-red-java-console-errors" rel="bookmark" title="Handling red Java console errors">Handling red Java console errors </a> <small>Red Java errors are sometimes displayed in the Matlab console. They can be removed or avoided in a variety of means. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Types of undocumented Matlab aspects</title>
		<link>https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=types-of-undocumented-matlab-aspects</link>
					<comments>https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 24 Nov 2011 18:00:36 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented feature]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2534</guid>

					<description><![CDATA[<p>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects">Types of undocumented Matlab aspects</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/reasons-for-undocumented-matlab-aspects" rel="bookmark" title="Reasons for undocumented Matlab aspects">Reasons for undocumented Matlab aspects </a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types" rel="bookmark" title="Undocumented plot marker types">Undocumented plot marker types </a> <small>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types-2" rel="bookmark" title="Setting class property types &#8211; take 2">Setting class property types &#8211; take 2 </a> <small>R2016a saw the addition of class property types. However, a better alternative has existed for many years. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types" rel="bookmark" title="Setting class property types">Setting class property types </a> <small>Matlab's class properties have a simple and effective mechanism for setting their type....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Why are there so many undocumented aspects in Matlab?<br />
This is a great question, recently <a target="_blank" href="/articles/guide-customization/#comment-61578">asked</a> by a reader of this blog, so I wanted to expand on it in next week&#8217;s article. Before specifying the different reasons, let&#8217;s map the nature of undocumented aspects that we find in Matlab.<br />
The term <i>undocumented/unsupported</i> (as opposed to <i>mis-documentated</i> or <i>deprecated</i>) actually refers to quite a large number of different types.<br />
In the following list, the hyperlinks on the list-item titles lead to a list of corresponding articles on this website:</p>
<ul>
<li><b><a target="_blank" href="/articles/tag/undocumented-function/">Undocumented functions</a></b><br />
Matlab functions which appears nowhere in the documentation, are usually built-in functions (do not have an m-file) and can only be inferred from online CSSM posts or usage within one of the Matlab m-functions installed with Matlab (the latter being the usual case). None of these functions is officially supported by MathWorks. <a target="_blank" href="/articles/category/mex/">MEX</a> is an important source for such functions.
</li>
<li><b><a target="_blank" href="/articles/tag/semi-documented-function/">Semi-documented functions</a></b><br />
Matlab functionality which exists in Matlab m-functions installed with Matlab, but have their main comment separated from the H1 comment line, thereby hiding it from normal view (via Matlab&#8217;s <i><b>help</b></i> function). The H1 comment line itself is simply a standard warning that this function is not officially supported and may change in some future version. To see the actual help comment, simply edit the function (using Matlab&#8217;s <i><b>edit</b></i> function or any text editor) and place a comment sign (%) at the empty line between the H1 comment and the actual help section. The entire help section will then onward be visible via the <i><b>help</b></i> function:</p>
<pre lang='matlab'>
        function [tree, container] = uitree(varargin)
        % WARNING: This feature is not supported in MATLAB
        % and the API and functionality may change in a future release.
fix =>  %
        % UITREE creates a uitree component with hierarchical data in a figure window.
        %   UITREE creates an empty uitree object with default property values in
        %   a figure window.
        %...
</pre>
<p>These functions are not documented in the full documentation (via Matlab&#8217;s <i><b>doc</b></i> function, or online). The odd thing is that some of these functions may appear in the category help output (for example, <i><b>help</b>(&#8216;uitools&#8217;)</i>), and in some cases may even have a fully-visible help section (e.g., <i><b>help</b>(&#8216;setptr&#8217;)</i>), but do not have any online help documentation (<i><b>docsearch</b>(&#8216;setptr&#8217;)</i> fails, and <i><b>doc</b>(&#8216;setptr&#8217;)</i> simply displays the readable help text).<br />
All these functions are officially unsupported by MathWorks, even when having a readable help section. The rule of thumb appears to be that a Matlab function is supported only if it has online documentation. Note, however, that in some rare cases a documentation discrepancy may be due to a MathWorks documentation error, not to unsupportability&#8230;
</li>
<li><b><a target="_blank" href="/articles/tag/undocumented-function/">Helper functions</a></b><br />
Many fully-supported Matlab functions use helper functions that have a specific use in the main (documented) function(s).  Often, these helper functions are tightly-coupled to their documented parents and are useless as stand-alone functions. But quite a few of them have quite useful stand-alone use, as I&#8217;ve already shown in some past articles.
</li>
<li><b><a target="_blank" href="/articles/tag/undocumented-feature/">Undocumented features</a> and <a target="_blank" href="/articles/tag/undocumented-property/">properties</a></b><br />
Features of otherwise-documented Matlab functions, which appear nowhere in the official documentation. You guessed it – these are also not supported by MathWorks&#8230; Like undocumented functions, you can only infer such features by the occasional CSSM post or a reference somewhere in Matlab&#8217;s m-code.
</li>
<li><b><a target="_blank" href="/articles/tag/semi-documented-feature/">Semi-documented features</a></b><br />
Features of otherwise-documented Matlab functions, which are documented in a separate section beneath the main help section, and nowhere else (not in the full doc not the online documentation). If you did not know in advance that these features existed, you could only learn of them by manually looking at Matlab&#8217;s m-files (which is what I do in most cases&#8230;).
</li>
<li><b><a target="_blank" href="/articles/tag/undocumented-property/">Undocumented properties</a></b><br />
Many Matlab objects have internal properties, which can be retrieved (via Matlab&#8217;s <i><b>get</b></i> function) and/or set (via the <i><b>set</b></i> function) programmatically. All these properties are fully documented. Many objects also possess hidden properties, some of which are very interesting and useful, but which are undocumented and (oh yes) unsupported. Like undocumented features, they can only be inferred from CSSM or existing code. In a recent <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">article</a> I described my <i><b>getundoc</b></i> utility, which lists these undocumented properties of specified objects.
</li>
<li><b><a target="_blank" href="/articles/tag/internal-component/">Internal Matlab classes</a></b><br />
Matlab uses a vast array of specialized Java classes to handle everything from algorithms to GUI. These classes are (of course) undocumented/unsupported. They can often be accessed directly from the Matlab Command Window or user m-files. GUI classes can be inferred by inspecting the figure frame&#8217;s Java components, and non-GUI classes can often be inferred from references in Matlab&#8217;s m-files.
</li>
<li><b><a target="_blank" href="/articles/tag/JMI">Matlab-Java integration</a></b><br />
Matlab&#8217;s GUI interface, as well as the Java-to-Matlab interface (JMI) is fully undocumented and unsupported. In addition to JMI, there are other mechanisms to run Matlab code from within Java (namely JMI, COM and DDE) &#8211; these are all unsupported and by-and-large undocumented.
</li>
<li><b><a target="_blank" href="/?s=UDD">Matlab&#8217;s UDD mechanism</a></b><br />
UDD (Unified Data Definition?) is used extensively in Matlab as the internal object-oriented mechanism for describing object properties and functionalities. We can use UDD for a wide variety of uses. UDD was described in a series of articles here in early 2011.
</li>
</ul>
<p>Next week I will list the reasons that cause MathWorks to decide whether a particular feature or property should be documented or not.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects">Types of undocumented Matlab aspects</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/reasons-for-undocumented-matlab-aspects" rel="bookmark" title="Reasons for undocumented Matlab aspects">Reasons for undocumented Matlab aspects </a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types" rel="bookmark" title="Undocumented plot marker types">Undocumented plot marker types </a> <small>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types-2" rel="bookmark" title="Setting class property types &#8211; take 2">Setting class property types &#8211; take 2 </a> <small>R2016a saw the addition of class property types. However, a better alternative has existed for many years. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-class-property-types" rel="bookmark" title="Setting class property types">Setting class property types </a> <small>Matlab's class properties have a simple and effective mechanism for setting their type....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Hierarchical Systems with UDD</title>
		<link>https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hierarchical-systems-with-udd</link>
					<comments>https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Mar 2011 18:00:25 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[JMI]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[uitools]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2146</guid>

					<description><![CDATA[<p>UDD objects can be grouped in structured hierarchies - this article explains how</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd">Hierarchical Systems with UDD</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/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/introduction-to-udd" rel="bookmark" title="Introduction to UDD">Introduction to UDD </a> <small>UDD classes underlie many of Matlab's handle-graphics objects and functionality. This article introduces these classes....</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>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome guest blogger <a target="_blank" rel="nofollow" href="http://aetoolbox.com/">Donn Shull</a>, who continues his multi-part series about Matlab’s undocumented UDD objects.</i><br />
We have looked at the <a target="_blank" href="/articles/introduction-to-udd/">tools for working with UDD classes</a>, and <a target="_blank" href="/articles/creating-a-simple-udd-class/">created a simple UDD class</a>. Today I shall show how to create a hierarchy of UDD objects.</p>
<h3 id="hierarchy">Creating hierarchical structures with UDD objects</h3>
<p>UDD is the foundation for both Handle Graphics (HG) and Simulink. Both are hierarchical systems. It stands to reason that UDD would offer support for hierarchical structures. It is straightforward to connect UDD objects together into searchable tree structures. All that is necessary is a collection of UDD objects that don&#8217;t have any methods or properties named <code>'connect', 'disconnect', 'up', 'down', 'left', 'right'</code> or <code>'find'</code>.<br />
We illustrate the technique by creating a hierarchy of <code>simple.object</code>s as shown in the following diagram:<br />
<center><figure style="width: 200px" class="wp-caption aligncenter"><img decoding="async" alt="Sample UDD objects hierarchy" src="https://undocumentedmatlab.com/images/UDD_structure.png" title="Sample UDD objects hierarchy" width="200" height="177" /><figcaption class="wp-caption-text">Sample UDD objects hierarchy</figcaption></figure></center><br />
To begin we create five instances of the <code>simple.object</code> class from the previous article:</p>
<pre lang="matlab">
% Remember that simple.object accepts a name and a value
a = simple.object('a', 1);
b = simple.object('b', 1);
c = simple.object('c', 0);
d = simple.object('d', 1);
e = simple.object('e', 1);
</pre>
<p>To form the structure we use the <i>connect</i> method. We can use either dot notation or the Matlab syntax:</p>
<pre lang="matlab">
% Dot-notation examples:
a.connect(b, 'down');
b.connect(a, 'up');       % alternative to the above
% Matlab notation examples:
connect(a, b, 'down');
connect(b, a, 'up');      % alternative to the above
</pre>
<p>Next, connect node c into our hierarchy. There are several options here: We can use &#8216;down&#8217; to connect a to c. Or we could use &#8216;up&#8217; to connect c to a. Similarly, we can use either &#8216;left&#8217; or &#8216;right&#8217; to connect b and c. Here&#8217;s one of the many possible ways to create our entire hierarchy:</p>
<pre lang="matlab">
b.connect(a, 'up');
c.connect(b, 'left');
d.connect(b, 'up');
e.connect(d, 'left');
</pre>
<h3 id="inspecting">Inspecting UDD hierarchy structures</h3>
<p>We now have our structure and each object knows its connection to other objects. For example, we can inspect b&#8217;s connections as follows:</p>
<pre lang="matlab">
>> b.up
ans =
  Name: a
 Value: 1.000000
>> b.right
ans =
  Name: c
 Value: 0.000000
>> b.down
ans =
  Name: d
 Value: 1.000000
</pre>
<p>We can search our structure by using an undocumented form of the built-in <i><b>find</b></i> command. When used with connected UDD structures, <i><b>find</b></i> can be used in the following form:</p>
<pre lang="matlab">objectArray = find(startingNode, 'property', 'value', ...)</pre>
<p>To search from the top of our hierarchy for objects of type <code>simple.object</code> we would use:</p>
<pre lang="matlab">
>> find(a, '-isa', 'simple.object')
ans =
        simple.object: 5-by-1    % a, b, c, d, e
</pre>
<p>Which returns all the objects in our structure, since all of them are <code>simple.object</code>s. If we repeat that command starting at b we would get:</p>
<pre lang="matlab">
>> find(b, '-isa', 'simple.object')
ans =
	simple.object: 3-by-1    % b, d, e
</pre>
<p><i><b>find</b></i> searches the structure downward from the current node. Like many Matlab functions, <i><b>find</b></i> can be used with multiple property value pairs, so if we want to find <code>simple.object</code> objects in our structure with <b>Value</b> property =0, we would use the command:</p>
<pre lang="matlab">
>> find(a, '-isa', 'simple.object', 'Value', 0)
ans =
  Name: c
 Value: 0.000000
</pre>
<h3 id="visualizing">Visualizing a UDD hierarchy</h3>
<p>Hierarchical structures are also known as tree structures. Matlab has an undocumented function for visualizing and working with trees namely <i><b>uitree</b></i>. Yair has described <i><b>uitree</b></i> in a <a target="_blank" href="/articles/uitree/">series of articles</a>. Rather than following the techniques in shown in Yair&#8217;s articles, we are going to use a different method that will allow us to introduce the following important techniques for working with UDD objects:</p>
<ul>
<li>Subclassing, building your class on the foundation of a parent class</li>
<li>Overloading properties and methods of the superclass</li>
<li>Using meta-properties <b>GetfFunction</b> and <b>SetFunction</b></li>
</ul>
<p>Because the steps shown below will subclass an HG class, they will modify our <code>simple.object</code> class and probably make it unsuitable for general use. Yair has shown that <i><b>uitree</b></i> is ready made for displaying HG trees and we saw above that HG is a UDD system. We will use the technique from <code>uitools.uibuttongroup</code> to make our <code>simple.object</code> class a subclass of the HG class <code>hg.uipanel</code>. Modify the class definition file as follows:</p>
<pre lang="matlab">
% class definition
superPackage = findpackage('hg');
superClass = findclass(superPackage, 'uipanel');
simpleClass = schema.class(simplePackage, 'object',superClass);
</pre>
<p>Now we can either issue the <i><b>clear classes</b></i> command or restart Matlab and then recreate our structure. The first thing that you will notice is that when we create the first <code>simple.object</code> that a figure is also created. This is expected and is the reason that this technique is not useful in general. We will however use this figure to display our structure with the following commands:</p>
<pre lang="matlab">
t = uitree('v0', 'root', a);  drawnow;
t.expand(t.getRoot);  drawnow;
t.expand(t.getRoot.getFirstChild);
</pre>
<p><center><figure style="width: 441px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Simple structure presented in a Matlab uitree" src="https://undocumentedmatlab.com/images/UDD_uitree_1.png" title="Simple structure presented in a Matlab uitree" width="441" height="189" /><figcaption class="wp-caption-text">Simple structure presented in a Matlab <i><b>uitree</b></i></figcaption></figure></center><br />
The label on each of our objects is &#8216;uipanel&#8217; and this is probably not what we want. If we inspect our object or its <code>hg.uipanel</code> super-class (note: this would be a great time to use Yair&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object"><i><b>uiinspect</b></i> utility</a>), we can see there is a <b>Type</b> property that has a value of &#8216;uipanel&#8217;. Unfortunately this property is read-only, so we cannot change it. We can however overload it by placing a <i><b>schema.prop</b></i> in our class definition named <b>Type</b>. This will allow us to overload or replace the parent&#8217;s <b>Type</b> property with our own definition:</p>
<pre lang="matlab">
p = schema.prop(simpleClass, 'Type', 'string');
p.FactoryValue = 'simple.object';
</pre>
<p>Once again, issue the <i><b>clear classes</b></i> command or restart Matlab, then recreate our structure. Our tree now has each node labeled with the &#8216;simple.object&#8217; label:<br />
<center><figure style="width: 441px" class="wp-caption aligncenter"><img decoding="async" alt="Corrected node names for our UDD structure" src="https://undocumentedmatlab.com/images/UDD_uitree_2.png" title="Corrected node names for our UDD structure" width="441" height="189" /><figcaption class="wp-caption-text">Corrected node names for our UDD structure</figcaption></figure></center><br />
This is a little more descriptive but what would really be nice is if we could label each node with the value of the <b>Name</b> property. As luck would have it, we can do just that. When we add a property to a UDD class we are adding an object of type <code>schema.prop</code>. So our properties have their own properties and methods (so-called <i>meta-data</i>). We are going to set the <b>GetFunction</b> property of our <b>Type</b> property. <b>GetFunction</b> holds a handle of the function to be called whenever the property is accessed:</p>
<pre lang="matlab">
p = schema.prop(simpleClass, 'Type', 'string');
p.GetFunction = @getType;
</pre>
<p>The prototype for the function that <b>GetFunction</b> references has three inputs and one output: The inputs are the handle of the object possessing the property, the value of that property, and the property object. The output is the value that will be supplied when the property is accessed. So our <b>GetFunction</b> can be written to supply the value of the <b>Name</b> property whenever the <b>Type</b> property value is being read:</p>
<pre lang="matlab">
function propVal = getType(self, value, prop)
   propVal = self.Name;
end
</pre>
<p>Alternately, as a single one-liner in the schema definition file:</p>
<pre lang="matlab">p.GetFunction = @(self,value,prop) self.Name;</pre>
<p>Similarly, there is a corresponding <b>SetFunction</b> that enables us to intercept changes to a property&#8217;s value and possibly disallow invalid values.<br />
With these changes when we recreate our <i><b>uitree</b></i> we obtain:<br />
<center><figure style="width: 441px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Overloaded property GetFunction" src="https://undocumentedmatlab.com/images/UDD_uitree_3.png" title="Overloaded property GetFunction" width="441" height="189" /><figcaption class="wp-caption-text">Overloaded property <b>GetFunction</b></figcaption></figure></center></p>
<h3 id="java">A Java class for UDD trees</h3>
<p>We will have more to say about the relationship between UDD and Java in a future article. For now we simply note that the <code>com.mathworks.jmi.bean.UDDObjectTreeModel</code> class in the <a target="_blank" href="/articles/jmi-java-to-matlab-interface/">JMI package</a> provides some UDD tree navigation helper functions. Methods include <i>getChild, getChildCount, getIndexOfChild</i> and <i>getPathToRoot</i>. The <code>UDDObjectTreeModel</code> constructor requires one argument, an instance of your UDD tree root node:</p>
<pre lang="matlab">
% Create a UDD tree-model instance
>> uddTreeModel = com.mathworks.jmi.bean.UDDObjectTreeModel(a);
% Get index of child e and its parent b:
>> childIndex = uddTreeModel.getIndexOfChild(b, e)
childIndex =
     1
% Get the root's first child (#0):
>> child0 = uddTreeModel.getChild(a, 0)
child0 =
  Name: b
 Value: 1.000000
% Get the path from node e to the root:
>> path2root = uddTreeModel.getPathToRoot(e)
path2root =
com.mathworks.jmi.bean.UDDObject[]:
    [simple_objectBeanAdapter2]      % <= a
    [simple_objectBeanAdapter2]      % <= b
    [simple_objectBeanAdapter2]      % <= e
>> path2root(3)
ans =
  Name: e
 Value: 1.000000
</pre>
<p>We touched on a few of the things that you can do by modifying the properties of a <code>schema.prop</code> in this article. In the following article we will take a more detailed look at this essential class.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd">Hierarchical Systems with UDD</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/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/introduction-to-udd" rel="bookmark" title="Introduction to UDD">Introduction to UDD </a> <small>UDD classes underlie many of Matlab's handle-graphics objects and functionality. This article introduces these classes....</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>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/hierarchical-systems-with-udd/feed</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<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 loading="lazy" 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 loading="lazy" 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 loading="lazy" 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>
