276 relevant articles found:

Inter-Matlab data transfer with memcached

Once again I welcome guest blogger Mark Mikofski. Mark has written here last year about JGIT-Matlab integration and earlier this year on JSON-Matlab integration. Today, Mark shows how to use the well-known open-source memcached library for data transfer between separate Matlab processes. Readers are also referred to Mark’s article on his blog. I have already written about various ways to communicate between separate Matlab processes – today’s article is an important complement to these methods.

Downloads

Stringpool's memcached tutorialThe memcached open-source library is great for sending objects from process to process. It is typically used to cache large data objects from databases or in a distributed environment, but we can also use it as a simple distributed shared memory system, which stores data in key-value pairs (as in a hashtable).

I was able to use memcached to set and retrieve objects from two different instances of Matlab. Both the Java and .NET variants of memcached can be used for this. memcached requires two components: server and client: The server comes precompiled, while the client needs to be compiled by us.

The memcached server was compiled by Trond Norbye from Couchbase (previously Membase and Northscale) for 32-bit and 64-bit Windows OS. See below how to run it as a service using the Python PyWin32 package.

I compiled Windows binaries of memcached-client libraries for both the Java and .NET using Java-1.7 and Visual Studio 2010 and zipped them up here.

Note: additional (non-memcached) shared-memory implementations used in Matlab include Joshua Dillon’s sharedmatrix (also see here), and Kevin Stone’s SharedMemory utilities, which use POSIX shared-memory and the Boost IPC library. Rice University’s TreadMarks library is another example of a shared-memory approach that has been used with Matlab, in the MATmarks package (note that the current availability of MATmarks is unclear).
Continue reading

Categories: Guest bloggers, Low risk of breaking in future versions
Tags:
Leave a comment

Property value change listeners

For performance reasons, it is almost always better to respond to events (asynchronously), than to continuously check a property value (synchronous polling). Therefore, if we wish to do something when some property value is changed (e.g., log the event, shut down the system, liquidate the portfolio, call the police, …), then it is preferable to attach a property-change listener callback.

The standard (documented) way of attaching a value-change listener to Matlab class properties is via the addlistener function. This only works for handle (not value) classes, and only to those properties that have the SetObservable and/or GetObservable attribute turned on:

addlistener(hClassObject, propertyName, 'PostSet', @myCallbackFcn);

This is all nice and well for Matlab class properties, but what about HG (handle Graphics: plots & GUI) properties? Can we similarly listen to changes in (say) the axes limits? Until now this has been possible, but undocumented. For example, this will trigger myCallbackFcn(hAxes,eventData) whenever the axes limits change (due to zoom, pan, plotting etc.):

addlistener(gca, 'YLim', 'PostSet', @(hAxes,eventData) myCallbackFcn(hAxes,eventData));
 
% Or (shorter equivalent):
addlistener(gca, 'YLim', 'PostSet', @myCallbackFcn);

This could be very useful when such properties could be modified from numerous different locations. Rather than updating all these location to call the relevant callback function directly, we simply attach the callback to the property-change listener. It could also be useful in cases where for some reason we cannot modify the source of the update (e.g., third-party or legacy code).

In addition to PostSet, we could also set listeners for PreSet. Also, we could set listeners on PostGet and PreGet – this could be useful for calculating dynamic (dependent) property values.
Continue reading

Categories: GUI, Handle graphics, Listeners, Low risk of breaking in future versions, Stock Matlab function, Undocumented feature
Tags: , , , ,
Leave a comment

Online (web-based) Matlab

For many years I searched for a good solution for deploying Matlab applications in online web-pages. There used to be a solution over a decade ago but it was taken off the market. We could use the Java Builder to wrap our Matlab apps in a JAR that could be called by a Java-based application server, but we’d still need to develop the front-end web GUI as well as the middle-tier plumbing. A similar limitation exists if we wish to use the new Matlab Production Server (MSP). Developing this front-end and middle-tier is by no means a trivial exercise, as much as MathWorks presentations would like it to appear. Not to mention the fact that the Builder and the MSP are relatively costly (~$5-7K and ~$30K respectively).

I was thrilled to see the answer in the recent Matlab Computational Finance Conference, London. I presented at last year’s conference, so I was excited to review this year’s presentations when I came across a nugget in Kevin Shea’s keynote presentation on new Matlab developments. Note that there were two separate Matlab computational-finance events in 2014 – in London (June 24) and NY (April 9); the interesting piece is from London. Unlike the NY conference, the London conference proceedings do not include a video recording, only the slides (perhaps the video will be added to the proceedings page later, after all it takes some time to process). The last slide of Kevin’s presentation shows a screenshot of a Chrome browser displaying what appears to be a full-fledged Matlab desktop (Workspace, Editor, Command Window, figures) at https://matlab.mathworks.com:

Matlab Online (click to zoom)
Matlab Online (click to zoom)

Continue reading

Categories: Desktop, Medium risk of breaking in future versions, Semi-documented feature
Tags: ,
2 Comments

Class object tab completion & improper field names

I recently consulted to a very large industrial client. Following a merger/acquisition, the relevant R&D department had two development groups using different technologies: one group uses Matlab, the other does not. My client wanted both groups to use Matlab, something that would naturally please MathWorks.

Unfortunately, it turns out that a technical challenge was preventing this move: the other technology enabled data field names (identifiers) longer than Matlab’s namelengthmax=63 characters, and these names also sometimes contained illegal identifier characters, such as spaces or symbols. This prevented an easy code transition, indefinitely delaying the migration to Matlab.

Accessing improper fieldnames

I suggested to this client to use Matlab class objects that overloaded the subsref() and subsasgn() methods: the long original identifiers would be stored in some internal container (cell array or containers.Map etc.), and they would be accessed not directly (which would be impossible since they are not valid Matlab identifiers) but via the overloaded methods. Something along the following lines:
Continue reading

Categories: Desktop, Medium risk of breaking in future versions, Undocumented feature
Tags: , , ,
11 Comments

Using pure Java GUI in deployed Matlab apps

I would like to welcome repeat guest blogger Karthik Ponudurai, who has previously written here about the JTattoo look-and-feel, and about integration of Java controls’ events with Matlab callbacks. Today, Karthik discusses a problem when we wish to use pure-Java GUIs in deployed Matlab programs, and the undocumented simple solution.

Reminder: I will be visiting several US cities (Minneapolis, Boston and New York) in July 22-31 (details). Let me know if you’d like to meet me there.

Introduction

Using a pure-Java Swing-based Graphical User Interface (GUI) has several important advantages compared to using a pure-Matlab GUI:

  • Java GUI widget toolkit provides a large collection of components (scrollbar, slider, etc…) and layouts (card, spring, etc…)
  • Multiple event handling options
  • Mature third-party Java Swing IDEs for quick and easy GUI development (Netbeans, Eclipse, etc…)
  • Supports pluggable look and feel that allows applications to have a look and feel that is unrelated to the underlying platform.
  • Java Swing’s window icon can be modified, whereas Mathworks apparently places an [entirely unreasonable] license restriction on modifying the Matlab figure window icon.

When Matlab is in development (non-deployed) mode, we can load and display a Java JFrame using the following Matlab code:

% Add Java library to dynamic Java classpath
javaaddpath([pwd '\ExampleWindow.jar']);
 
% Get example Java window from the library
jFrame = examplewindow.JavaWindow();
 
% Get Java buttons
% Note: see http://UndocumentedMatlab.com/blog/matlab-callbacks-for-java-events-in-r2014a
plotMeshButton = handle(jFrame.getPlotMeshButton(),    'CallbackProperties');
showWarnButton = handle(jFrame.getShowWarnDlgButton(), 'CallbackProperties');
 
% Set Java button callbacks
set(plotMeshButton, 'ActionPerformedCallback', @myPlotMeshCallback);
set(showWarnButton, 'ActionPerformedCallback', @myShowWarnCallback);
 
% Display the Java window
jFrame.setVisible(true);

Java JFrame created in Matlab (click for full-size image)
Java JFrame created in Matlab (click for full-size image)

The problem

All this works great when ran within the Matlab environment. However, when the Matlab source code file (.m) is compiled as a Windows standalone executable application, when running the resulting executable the Java window appears for a short period and then terminates (exits). Without a visible Matlab figure, the compiled Matlab application does not retain the Java window open. The JFrame flashes on for a split-second, and then vanishes.
Continue reading

Categories: Guest bloggers, GUI, Java, Medium risk of breaking in future versions, Undocumented feature
Tags: , , , ,
1 Comment

USA visit, 22-31 July 2014

Meet me in MSP, NYC or BOS - 22-31 July 2014I’d like to break the regular flow of technical articles, to announce that I will visit several US cities on July 22-31 to meet some clients for advanced Matlab training and consulting:

  • July 22-24: Minneapolis, MN
  • July 25-27: New York City, NY
  • July 28-31: Boston, MA
  • July 31: New York City, NY

I will be happy to meet you at any of these locations to discuss how I could bring value to your Matlab programming needs, as a consultant, contractor or trainer.

If you would like to schedule a face-to-face meeting, please email me.

Categories: Uncategorized
5 Comments

Java class access pitfalls

A few days ago I consulted to a company that wanted to integrate some of their Java code in Matlab. The Java code compiled ok and ran just fine in the Java environment, but when we wanted to use the relevant Java classes in Matlab we got all sorts of errors. Since I believe that this could be a common problem, and I’m not sure that there’s any other place that does this, I thought to list the possible error causes in today’s article:

  1. Forgetting or mistyping the package name:
    >> jObject = JButton('Click me!');  % missing package name
    Undefined function 'JButton' for input arguments of type 'char'.
    
    >> jObject = java.swing.JButton('Click me!');  % should be javax.swing...
    Undefined variable "java" or class "java.swing.JButton". 
    
    >> jObject = javax.Swing.JButton('Click me!');  % should be javax.swing...
    Undefined variable "java" or class "javax.Swing.JButton". 
    
    >> import java.swing.*  % should be javax.swing... - no error here, only in the next line
    >> jObject = JButton('Click me!');   % missing package name
    Undefined function 'JButton' for input arguments of type 'char'.
    
    >> import java.swing.JButton  % should be javax.swing...
    Error using import
    Import argument 'java.swing.JButton' cannot be found or cannot be imported.
    

    Note: package names are typically lowercase, but 3rd-party packages might not follow this convention! Since Java is case-sensitive, the package name must be exact.

Continue reading

Categories: Java, Low risk of breaking in future versions, Undocumented feature
Tags: ,
Leave a comment

Function call timeline profiling

Back in 2012, I wrote an article about the Matlab profiler’s undocumented functionality of storing detailed information about the function-call history, including timing information. I intended to follow up on this with a utility that would bring the data to life, but I never found the time for this. With my upcoming book on Matlab performance now nearing publication (ETA: November 2014), I decided it’s finally time to finish the task. The result is my profile_history utility, available for download on the Matlab File Exchange (open-source):

Usage of profile_history is very easy, based on the latest profiling session:

profile on; surf(peaks); profile_history

Function call timeline profiling (click for full-size image)
Function call timeline profiling (click for full-size image)

Continue reading

Categories: High risk of breaking in future versions, Stock Matlab function, Undocumented feature
Tags: , ,
9 Comments

checkClass

Over the past few years I have shown numerous uses of Java components in Matlab, many of them built-into the Matlab environment and can be used as-is. I have been asked many times how I uncover these components and how I discover how to use them. The short answer is that this is indeed often not easy. The blog articles (and my book) only present “success stories“, i.e. cases where I was able to uncover the behavior, functionality and usage of such components; they do not present the numerous other cases where I have not been so successful.

Still, over the course of the past 10-15 years, I developed several tools that help me become more efficient in this work, and I’ve posted most of these on the File Exchange. I’ve already written here about the FindJObj utility, both as a means for uncovering the underlying Java reference of Matlab GUI controls, and as a means to visualize the GUI hierarchy of a specified window or container. I also wrote about my uiinspect utility, which analyzes the specified object in a compact and intuitive GUI window.

Today I wish to complete the picture by describing my checkClass utility. checkClass is more limited than uiinspect in the types of objects that it can analyze (almost only Java objects) and the information that it presents (for example, callbacks and properties are not listed separately). checkClass‘s main benefit is the fact that it is a very lightweight (230 lines of code), fast, GUI-less console application. checkClass highlights the differences between the analyzed class and its superclass, which is especially useful when investigating the functionality of objects. During the course of my work, I use checkClass for 95% of my investigations, and uiinspect/findjobj only for the remainder. For Java objects at least, a detailed console listing of the methods is quite enough, since properties are typically accessed via getPropName()/setPropName() accessor methods. The combination of checkClass and uiinspect can be very useful when investigating a new Java library or integrating a 3rd-party API.

Here is a sample output for the com.mathworks.mwswing.MJToggleButton class:

>> jButton = com.mathworks.mwswing.MJToggleButton;
>> checkClass(jButton)  % or: jButton.checkClass
Class com.mathworks.mwswing.MJToggleButton (uiinspect)

Superclass: javax.swing.JToggleButton

Methods in MJToggleButton missing in JToggleButton:
   hasFlyOverAppearance() : boolean
   hideText()
   isAutoMnemonicEnabled() : boolean
   isTextHidden() : boolean
   setAutoMnemonicEnabled(boolean)
   setFlyOverAppearance(boolean)
   setFocusTraversable(boolean)
   unHideText()

Methods inherited & modified by MJToggleButton:
   getForeground() : java.awt.Color
   getParent() : java.awt.Container
   isFocusTraversable() : boolean
   paint(java.awt.Graphics)
   setAction(javax.swing.Action)
   setModel(javax.swing.ButtonModel)
   setText(java.lang.String)

Interfaces in JToggleButton missing in MJToggleButton:
   javax.accessibility.Accessible

Interfaces in MJToggleButton missing in JToggleButton:
   com.mathworks.mwswing.ExtendedButton

Continue reading

Categories: Java, Medium risk of breaking in future versions
Tags: ,
Leave a comment

Bar plot customizations

Bar charts are a great way to visualize data. Matlab includes the bar function that enables displaying 2D bars in several different manners, stacked or grouped (there’s also bar3 for 3D bar-charts, and barh, bar3h for the corresponding horizontal bar charts).

Displaying stacked 1D data

bar is basically a high-level m-file wrapper for the low-level specgraph.barseries object. Such wrappers are generally a good thing, assigning default property values, checking the input data for illegal values etc. But in some cases, they are simply too smart. One such case happened to me a few days ago, when I needed to display a stacked chart of some data values. This works great when the data is a 2D matrix, but when the data happens to be 1D (a single row), bar decides to display the values in separate bars (left screenshot), rather than in a single stacked bar (right screenshot), even when I specifically ask for a ‘stacked’ graph:

bar([6,4,1], 'Stacked');

Default bar plot of 1D data

Default bar plot of 1D data

  
Bar plot of 1D data - stacked

Bar plot of 1D data - stacked


Continue reading

Categories: Handle graphics, Low risk of breaking in future versions, Stock Matlab function, Undocumented feature
Tags: , ,
7 Comments