318 relevant articles found:

Adding dynamic properties to graphic handles

A client recently asked me to extend one of Matlab’s built-in graphic containers (uiflowcontainer in this specific case) with automatic scrollbars that would enable the container to act as a scroll-panel. The basic idea would be to dynamically monitor the container’s contents and when it is determined that they overflow the container’s boundaries, then attach horizontal/vertical scrollbars to enable scrolling the contents into view:

Scrollable Matlab container

Scrollable Matlab container

This may sound simple, but there are actually quite a few undocumented hacks that make this possible, including listening to ObjectChildAdded/ObjectChildRemoved events, location/size/visibility events, layout changes etc. Maybe I’ll blog about it in some future article.

Today’s post is focused on a specific aspect of this project, attaching dynamic properties to the builtin uiflowcontainer, that would enable users to modify the container’s properties directly, as well as control aspects of the scrolling using the new properties: handles to the parent container, as well as the horizontal and vertical scrollbars, and even a new refresh() method.
Continue reading

Categories: GUI, Handle graphics, High risk of breaking in future versions, Stock Matlab function, UI controls, Undocumented feature, Undocumented function
Tags: , , , , , ,

Callback functions performance

Matlab enables a variety of ways to define callbacks for asynchronous events (such as interactive GUI actions or timer invocations). We can provide a function handle, a cell-array (of function handle and extra parameters), and in some cases also a string that will be eval‘ed in run-time. For example:

hButton = uicontrol(..., 'Callback', @myCallbackFunc);  % function handle
hButton = uicontrol(..., 'Callback', {@myCallbackFunc,data1,data2});  % cell-array
hButton = uicontrol(..., 'Callback', 'disp clicked!');  % string to eval

The first format, function handle, is by far the most common in Matlab code. This format has two variant: we can specify the direct handle to the function (as in @myCallbackFunc), or we could use an anonymous function, like this:

hButton = uicontrol(..., 'Callback', @(h,e) myCallbackFunc(h,e));  % anonymous function handle

All Matlab callbacks accept two input args by default: the control’s handle (hButton in this example), and a struct or object that contain the event’s data in internal fields. In our anonymous function variant, we therefore defined a function that accepts two input args (h,e) and calls myCallbackFunc(h,e).

These two variants are functionally equivalent:

hButton = uicontrol(..., 'Callback', @myCallbackFunc);             % direct function handle
hButton = uicontrol(..., 'Callback', @(h,e) myCallbackFunc(h,e));  % anonymous function handle

In my experience, the anonymous function variant is widely used – I see it extensively in many of my consulting clients’ code. Unfortunately, there could be a huge performance penalty when using this variant compared to a direct function handle, which many people are simply not aware of. I believe that even many MathWorkers are not aware of this, based on a recent conversation I’ve had with someone in the know, as well as from the numerous usage examples in internal Matlab code: see the screenshot below for some examples; there are numerous others scattered throughout the Matlab code corpus. Continue reading

Categories: GUI, Handle graphics, Low risk of breaking in future versions
Tags: , , , , , ,

Solving an mput (FTP) hang problem

Matlab includes a variety of builtin utility functions that enable easy access to FTP. These functions are basically methods of an FTP object using Matlab’s old class system (for example, the mput function is implemented as mput.m in the %matlabroot%\toolbox\matlab\iofun\@ftp\ folder). These are pretty old files that haven’t changed much in years.

FTPI recently needed to upload files from Matlab onto an FTP server, and discovered that calling mput simply hang Matlab to the point that I needed to kill and restart the Matlab process. The problem was not in the FTP server, since it could be accessed normally using FTP clients such as FileZilla and WinSCP. So it had to be something internal to Matlab. My initial workaround was to create an automation script (using WinSCP in my case) for the file upload. But this kludge is bot non-robust as well as slow. A fix to the Matlab problem would be much better.

Some online research yielded others who have complained about similar issues over the years, but I saw no concrete answer. I saw many references online to problems that relate to the combination of passive FTP with Windows 7 / firewall / Java 7, that suggested several fixes (example 1, example 2, example 3, example 4). However, none of them solved the problem: calling mput (or dir etc.) continued to freeze Matlab, forcing either a hard process kill or waiting several minutes for the timeout.

Today, Malcolm Lidierth, author of the Waterloo graphics package, told me that he also saw a similar situation on Mac. Fortunately, Malcolm discovered a much better solution to the problem than my external scripts workaround. It seems that simply setting the Java object underlying Matlab’s FTP object to use passive mode fixes the problem (possibly in addition to the other fixes mentioned above).
Continue reading

Categories: Java, Medium risk of breaking in future versions, Stock Matlab function, Undocumented feature
Tags: , , ,
Leave a comment

Accessing internal Java class members

Following my previous post on using the Java classloader, I thought I’d follow up today with a somewhat-related peculiarity.

Inner classes

Whenever we have an enum or inner-class defined within a Java class, it can be accessed in Java using standard dot-notation. For example, com.mathworks.hg.peer.ComboboxPeer.MLComboBox refers to an inner class MLComboBox which is defined within the ComboboxPeer class. When compiled, the class would be stored in a file called ComboboxPeer$InnerClassName.class. In other words, the JVM uses the $ separator char to indicate that MLComboBox is internal to ComboboxPeer.

Within the Java code, we would simply use the regular dot-notation (ClassName.MLComboBox) – the $ separator is part of the internal JVM implementation that the Java programmer should not be concerned about.

Unfortunately, we cannot ignore this in Matlab: Matlab’s interpreter, which acts as a bridge to the JVM, is not smart enough to know that in certain cases the dot-notation should be converted into a $. Therefore, trying to access ClassName.MLComboBox directly in Matlab fails:

>> jObject = com.mathworks.hg.peer.ComboboxPeer.MLComboBox([])
Undefined function or variable 'MLComboBox'.
>> jObject = com.mathworks.hg.peer.ComboboxPeer$MLComboBox([])
 jObject = com.mathworks.hg.peer.ComboboxPeer$MLComboBox([])
Error: The input character is not valid in MATLAB statements or expressions.

The solution in such cases is to use Matlab’s javaObject (or javaObjectEDT) function with the JVM’s internal $-representation:

>> jObject = javaObject('com.mathworks.hg.peer.ComboboxPeer$MLComboBox',[])
jObject =

Continue reading

Categories: Java, Low risk of breaking in future versions, Undocumented feature
Tags: ,
1 Comment

Static Java classpath hacks

A few days ago I encountered a situation where I needed to incorporate a JAR file into Matlab’s static Java classpath. I came across several relevant hacks that I thought could be useful for others:

The documented approach

In most use-cases, adding Java classes (or ZIP/JAR files) to the dynamic Java classpath is good enough. This can easily be done in run-time using the javaaddpath function. In certain cases, for example where the Java code uses asynchronous events, the Java files need to be added to the static, rather than the dynamic, Java classpath. In other cases, the Java code misbehaves when loaded using Matlab’s dynamic Java classloader, rather than the system classloader (which is used for the static classpath (some additional info). One example of this are the JAR/ZIP files used to connect to various databases (each database has its own Java JDBC connector, but they all need to reside in the static Java classpath to work properly).

Adding class-file folders or ZIP/JAR files to the static Java classpath can be done in several manners: we can update the Matlab installation’s classpath.txt file, or (starting in R2012b) a user-prepared javaclasspath.txt file. Either of these files can be placed in the Matlab (or deployed application’s) startup folder, or the user’s Matlab preferences folder (prefdir). This is all documented.

There are several important drawbacks to this approach:
Continue reading

Categories: High risk of breaking in future versions, Java, Undocumented feature
Tags: ,

Using linkaxes vs. linkprop

One of my clients recently asked me to solve a very peculiar problem: He had several axes and was using Matlab’s builtin linkaxes function to link their axis limits. However, it didn’t behave quite the way that he expected. His axes were laid out as 2×2 subplots, and he wanted the two columns to be independently linked in the X axis, and the two rows to be independently linked in the Y axis:

% Prepare the axes
ax(1,1) = subplot(2,2,1); 
ax(1,2) = subplot(2,2,2); 
ax(2,1) = subplot(2,2,3); 
ax(2,2) = subplot(2,2,4);
% Plot something
x = 0 : 0.01 : 10;
line(x, sin(x),   'Parent',ax(1,1));
line(x, sin(2*x), 'Parent',ax(1,2));
line(x, cos(x),   'Parent',ax(2,1));
line(x, cos(5*x), 'Parent',ax(2,2));
% Link the relevant axes
linkaxes(ax(:,1),'x');  % left column
linkaxes(ax(:,2),'x');  % right column
linkaxes(ax(1,:),'y');  % top row
linkaxes(ax(2,:),'y');  % bottom row

The problem was that the plots didn’t behave as expected: when zooming in on the bottom-left axes, for example, only the bottom-right axes was updated (Y-limits synced), whereas the top-left axes’ X-limits remained unchanged:

Badly-synced axes limits

Badly-synced axes limits

Continue reading

Walter Roberson liked this post
Categories: Handle graphics, Hidden property, Listeners, Low risk of breaking in future versions, Stock Matlab function, Undocumented feature
Tags: , , , ,
1 Comment

Matlab designs by Tim Smith

Matlab has undergone significant facelifts in recent years: Matlab Mobile (first introduced in 2010, with various upgrades since), R2012b’s new desktop toolstrip, various Matlab Central’s website facelifts (example1, example2), R2014b’s new graphics system (HG2), Matlab on the Web (MOTW), and Matlab’s upcoming GUI framework (AppDesigner). That’s quite a lot of UI designs, new and overhauled, over a relatively short timespan.

Designer Tim Smith (designbytimsmith.com), is apparently responsible for many of the sleek UI designs, working with MathWorks’ internal User Experience (UX) team. Tim’s website showcases his work, philosophy, and design process for Matlab’s AppDesigner, Desktop toolstrip, Matlab Mobile, and Matlab on the Web.

I highly recommend reading what Tim has to say about these designs, as well as other designs that he created for other clients. Impressive work indeed.

Formerly a MathWorks visual designer, Tim left MathWorks in 2012 to join PayPal, and currently works at Google. designbytimsmith.com has no contact page, and Tim is apparently very secretive about his email address, which is a bit odd for someone who was the design lead for Google’s new Inbox product. Anyway, you can contact him via his LinkedIn profile or Google+ page.

If you want to get a feel for what Matlab might look like down the road, simply head over to Tim’s website.


Various Tim Smith designs for AppDesigner's dial widget

Various Tim Smith designs for AppDesigner's dial widget

Categories: GUI, Low risk of breaking in future versions
Leave a comment

Capturing print events

As a followup to my recent post on capturing and using HG2′s new graphic events, I would like to welcome back guest blogger Robert Cumming, who developed a commercial Matlab GUI framework. Today, Robert will highlight an unusual use of event listeners to enable print output customizations by tapping into print-related events.

One of my toolbox clients wanted to ensure that every print-out, of any Matlab GUI, would contain a datestamp footer and a project id header.

Initially I thought this would be a simple task, since the GUI framework already has saveAs and copyToClipboard methods that users could utilize. Moreover, as Yair has shown some years ago, we can easily adapt the standard callbacks associated with the Matlab figure toolbar’s <Print> button and the menu-bar’s Print action. We can even customize the standard print setup. However, all this does not help when directly invoking printout commands from the Matlab command line or from within the user program, for example:

% Create the GUI
[x,y,z] = peaks(75); 
% printout via print() or export_fig
print(gcf, .... )
export_fig filename  % see http://undocumentedmatlab.com/blog/export_fig

Printout with the expected header and footer stamps

Printout with the expected header and footer stamps

Continue reading

Categories: Figure window, Guest bloggers, Medium risk of breaking in future versions, Undocumented feature
Tags: , , ,

JGraph in Matlab figures

I would like to introduce guest blogger Scott Koch. Scott is part of the development team at Eigenvector Research Inc., makers of PLS_Toolbox, a commercial chemometrics and multivariate data analysis toolbox. Today Scott will expand on JGraph, a Java-based open source graph visualization and diagramming library.

What is JGraph?

JGraph is an interactive Java-based diagramming and graph visualization library. The maintainers of JGraph have a product family that includes a Java Swing library (open-source), a JavaScript library (proprietary commercial), as well as other technologies. They call their product family “mxGraph”, and the Swing product specifically as “JGraphX”. The Swing library is available on GitHub and licensed under BSD. I will refer to the Swing library as JGraph, since that was the original library’s name until it was completely redesigned some years ago and renamed JGraphX. You can read additional information on JGraph and access various documentation alternatives in its README file.

Graphing is a powerful visualization tool that has not yet been integrated into the core Matlab product. I assume that this will be rectified by MathWorks in a future Matlab release. But until that time, or even later if you are still using R2015a or older, we do not have a solution in the core Matlab. In our toolbox product, we use a cleverly designed image to display a simple diagram, but I always thought it would be nice to have a “real” diagramming tool that was interactive and full-featured.

So, as a long time follower of Yair’s blog, I was thrilled to see his post several years ago about integrating Java libraries for charting and diagramming in Matlab figures. Unfortunately, my first attempts at getting JGraph to work in Matlab were not very successful. Thanks to a comment on that original post by Markus Behle, I was able to gain full access to JGraph in Matlab. Today’s post will show how we can use JGraph in Matlab.

Creating a new JGraph edge in a Matlab figure

Creating a new JGraph edge in a Matlab figure

Continue reading

John Cont, Carlos David Peña liked this post
Categories: Guest bloggers, GUI, Java, Low risk of breaking in future versions
Tags: , ,

Some performance-tuning tips

Today’s post is about performance. My goal is to show that contrary to widespread perception, Matlab is not inherently too slow to be used for real-life programs. In fact, by taking a small amount of time (compared to the overall dev time), Matlab programs can be accelerated by a large factor. I wish to demonstrate this claim with work that I recently completed for the Crustal Dynamics research group at Harvard University. They have created interactive Matlab GUIs for earthquake hazard, visualizing deformation and motion at plate boundary zones, recorded as GPS velocities:

Crustal dynamics visualization GUI

Crustal dynamics visualization GUI

These GUIs served them well for several years. But when they recently tried to analyze larger problems that involved far more data, it was getting so slow that it limited their ability to interrogate the GUI results effectively and do productive science (take a look at all the data points around New Zealand in the screenshot above). This is when I stepped in to help.
Continue reading

Categories: GUI, Low risk of breaking in future versions, Stock Matlab function
Tags: , , ,