Matlab-Java book

Undocumented Secrets of Matlab-Java Programming book
CRC promo code

Quick links:     Table of Contents     Book organization     FAQ     About the author     Errata list

I am extremely pleased to announce that after five years of research and hard work, my book on Undocumented Secrets of Matlab-Java Programming is finally published.

For a variety of reasons, the Matlab-Java interface was never fully documented. This is really quite unfortunate: Java is one of the most widely used programming languages, having many times the number of programmers and programming resources as Matlab. Also unfortunate is the popular claim that while Matlab is a fine programming platform for prototyping, it is not suitable for real-world, modern-looking applications.

Undocumented Secrets of Matlab-Java Programming (CRC Press, ISBN 9781439869031) aims to correct this.

This book shows how using Java can significantly improve Matlab program appearance and functionality. This can be done easily and even without any prior Java knowledge.

Readers are led step-by-step from simple to complex customizations. Within the book’s 700 pages, thousands of code snippets, hundreds of screenshots and ~1500 online references are provided to enable the utilization of this book as both a sequential tutorial and as a random-access reference suited for immediate use.

This book demonstrates how:

  • The Matlab programming environment relies on Java for numerous tasks, including networking, data-processing algorithms and graphical user-interface (GUI)
  • We can use Matlab for easy access to external Java functionality, either third-party or user-created
  • Using Java, we can extensively customize the Matlab environment and application GUI, enabling the creation of visually appealing and usable applications

No prior Java knowledge is required. All code snippets and examples are self-contained and can generally be used as-is. Advanced Java concepts are sometimes used, but understanding them is not required to run the code. Java-savvy readers will find it easy to tailor code samples for their particular needs; for Java newcomers, an introduction to Java and numerous online references are provided.

More info about the book, including detailed Table-of-Contents, book structure and FAQ, can be found on the book’s webpage.

Get your book copy now!
Use promo code MZK07 for a 20% discount and free worldwide shipping.

Categories: Java
Tags: ,
14 Comments

Using spinners in Matlab GUI

One of the few standard Java Swing controls that does not have any Matlab uicontrol counterpart is JSpinner. JSpinner is basically an editbox with two tiny adjacent up/down buttons. Spinners are similar in functionality to a combo-box (a.k.a. drop-down or pop-up menu), where a user can switch between several pre-selected values. They are often used when the list of possible values is too large to display in a combo-box menu. Like combo-boxes, spinners too can be editable (meaning that the user can type a value in the editbox) or not (the user can only “spin” the value using the up/down buttons).

JSpinner uses an internal data model, similarly to JTree, JTable and other complex controls. The default model is SpinnerNumberModel, which defines a min/max value (unlimited=[] by default) and step-size (1 by default). Additional predefined models are SpinnerListModel (which accepts a cell array of possible string values) and SpinnerDateModel (which defines a date range and step unit).

Here’s a basic code snippet showing how to display a simple numeric spinner for numbers between 20 and 35, with an initial value of 24 and increments of 1:

jModel = javax.swing.SpinnerNumberModel(24,20,35,1);
jSpinner = javax.swing.JSpinner(jModel);
jhSpinner = javacomponent(jSpinner, [10,10,60,20], gcf);

The spinner value can be set using the edit-box or by clicking on one of the tiny arrow buttons, or programmatically by setting the Value property. The spinner object also has related read-only properties NextValue and PreviousValue. The spinner’s model object has the corresponding Value (settable), NextValue (read-only) and PreviousValue (read-only) properties. In addition, the model also has the settable Maximum, Minimum and StepSize properties.

To attach a data-change callback, set the spinner’s StateChangedCallback property.

I have created a small Matlab demo, SpinnerDemo, which demonstrates usage of JSpinner in Matlab figures. Each of the three predefined models (number, list, and date) is presented, and the spinner values are inter-connected via their callbacks. The Matlab code is modeled after the Java code that is used to document JSpinner in the official documentation. Readers are welcome to download this demo from the Matlab File Exchange and reuse its source code.

Java's SpinnerDemo

Java's SpinnerDemo

  
My Matlab SpinnerDemo

My Matlab SpinnerDemo

As can be seen from the screenshot, SpinnerDemo also demonstrates how to attach a label to a GUI control with an associated accelerator key (Alt-D in the screenshot example, which sets the focus to the Date control).

An internal component in Matlab, namely com.mathworks.mwswing.MJSpinner, extends javax.swing.JSpinner, but in this particular case I cannot see any big advantage of using the internal MJSpinner rather than the standard JSpinner. On the contrary, using JSpinner will likely improve forward compatibility – MathWorks may well change MJSpinner in the future, but it cannot do anything to the standard Swing JSpinner. In other cases, internal Matlab controls do offer significant advantages over the standard Swing controls, but not here it would seem. In any case, the SpinnerDemo utility uses MJSpinner, but you can safely use JSpinner instead (line #86).

The internal Matlab controls are discussed in detail in Chapter 5 of my Matlab-Java book, and MJSpinner is specifically discussed in section 5.2.1.

Another JSpinner derivative is JIDE’s com.jidesoft.grid.SpinnerCellEditor, which can be used as the cell-editor component in tables. An example of this was shown in the article about Advanced JIDE Property Grids (and section 5.7.5 in the book). You may also be interested in the com.jidesoft.combobox.DateSpinnerComboBox, which presents a control that includes both a date-selection combo-box and a spinner (section 5.7.2):

A property grid with spinner control

A property grid with spinner control

  
JIDE's DateSpinnerComboBox

JIDE's DateSpinnerComboBox

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

Matlab-Java memory leaks, performance

There are several ways of retrieving information from a Java object into Matlab. On the face of it, all these methods look similar. But it turns out that there are important differences between them in terms of memory leakage and performance.

The problem: “Matlab crashes” – now go figure…

A client of one of my Matlab programs recently complained that Matlab crashes after several hours of extensive use of the program. The problem looked like something that is memory related (messages such as Matlab’s out-of-memory error or Java’s heap-space error). Apparently this happens even on 64-bit systems having lots of memory, where memory should never be a problem.

Well, we know that this is only in theory, but in practice Matlab’s internal memory management has problems that occasionally lead to such crashes. This is one of the reasons, by the way, that recent Matlab releases have added the preference option of increasing the default Java heap space (the previous way to do this was a bit complex). Still, even with a high Java heap space setting and lots of RAM, Matlab crashed after using my program for several hours.

Not pleasant at all, even a bit of an embarrassment for me. I’m used to crashing Matlab, but only as a result of my playing around with the internals – I would hate it to happen to my clients.

Finding the leak

While we can do little with Matlab’s internal memory manager, I started searching for the exact location of the memory leak and then to find a way to overcome it. I’ll save readers the description about the grueling task of finding out exactly where the memory leak occurred in a program that has thousands of lines of code and where events get fired asynchronously on a constant basis. Matlab Profiler’s undocumented memory profiling option helped me quite a bit, as well as lots of intuition and trial-and-error. Detecting memory leak is never easy, and I consider myself somewhat lucky this time to have both detected the leak source and a workaround.

It turned out that the leakage happens in a callback that gets invoked multiple times per second by a Java object (see related articles here and here). Each time the Matlab callback function is invoked, it reads the event information from the supplied Java event-data (the callback’s second input parameter). Apparently, about 1KB of memory gets leaked whenever this event-data is being read. This may appear a very small leak, but multiply this by some 50-100K callback invocations per hour and you get a leakage of 50-100MB/hour. Not a small leak at all; more of a flood you could say…

Using get()

The leakage culprit turned out to be the following code snippet:

% 160 uSecs per call, with memory leak
eventData  = get(hEventData,{'EventName','ParamNames','EventData'});
eventName  = eventData{1};
paramNames = eventData{2};
paramData  = eventData{3}.cell;

In this innocent-looking code, hEventData is a Java object that contains the EventName, ParamNames, EventData properties: EventName is a Java String, that is automatically converted by Matlab’s get() function into a Matlab string (char array); ParamNames is a Java array of Strings, that gets automatically converted into a Matlab cell-array of string; and EventData is a Java array of Objects that needs to be converted into a Matlab cell array using the built-in cell function, as described in one of my recent articles.

The code is indeed innocent, works really well and is actually extremely fast: each invocation takes of this code segment takes less than 0.2 millisecs. Unfortunately, because of the memory leak I needed to find a better alternative.

Using handle()

The first idea was to use the built-in handle() function, under the assumption that it would solve the memory leak, as reported here. In fact, MathWorks specifically advises to use handle() rather than to work with “naked” Java objects, when setting Java object callbacks. The official documentation of the set function says:

Do not use the set function on Java objects as it will cause a memory leak.

It stands to reason then that a similar memory leak happens with get and that a similar use of handle would solve this problem:

% 300 uSecs per call, with memory leak
s = get(handle(hEventData));
eventName  = s.EventName;
paramNames = s.ParamNames;
paramData  = cell(s.EventData);

Unfortunately, this variant, although working correctly, still leaks memory, and also performs almost twice as worse than the original version, taking some 0.3 milliseconds to execute per invocation. Looks like this is a dead end.

Using Java accessor methods

The next attempt was to use the Java object’s internal accessor methods for the requested properties. These are public methods of the form getXXX(), isXXX(), setXXX() that enable Matlab to treat XXX as a property by its get and set functions. In our case, we need to use the getter methods, as follows:

% 380 uSecs per call, no memory leak
eventName  = char(hEventData.getEventName);
paramNames = cell(hEventData.getParamNames);
paramData  = cell(hEventData.getEventData);

Here, the method getEventName() returns a Java String, that we convert into a Matlab string using the char function. In our previous two variants, the get function did this conversion for us automatically, but when we use the Java method directly we need to convert the results ourselves. Similarly, when we call getParamNames(), we need to use the cell function to convert the Java String[] array into a Matlab cell array.

This version at last doesn’t leak any memory. Unfortunately, it has an even worse performance: each invocation takes almost 0.4 milliseconds. The difference may seem insignificant. However, recall that this callback gets called dozens of times each second, so the total adds up quickly. It would be nice if there were a faster alternative that does not leak any memory.

Using struct()

Luckily, I found just such an alternative. At 0.24 millisecs per invocation, it is almost as fast as the leaky best-performance original get version. Best of all, it leaks no memory, at least none that I could detect.

The mechanism relies on the little-known fact that public fields of Java objects can be retrieved in Matlab using the built-in struct function. For example:

>> fields = struct(java.awt.Rectangle)
fields = 
             x: 0
             y: 0
         width: 0
        height: 0
      OUT_LEFT: 1
       OUT_TOP: 2
     OUT_RIGHT: 4
    OUT_BOTTOM: 8
 
>> fields = struct(java.awt.Dimension)
fields = 
     width: 0
    height: 0

Note that this useful mechanism is not mentioned in the main documentation page for accessing Java object fields, although it is indeed mentioned in another doc-page – I guess this is a documentation oversight.

In any case, I converted my Java object to use public (rather than private) fields, so that I could use this struct mechanism (Matlab can only access public fields). Yes I know that using private fields is a better programming practice and all that (I’ve programmed OOP for some 15 years…), but sometimes we need to do ugly things in the interest of performance. The latest version now looks like this:

% 240 uSecs per call, no memory leak
s = struct(hEventData);
eventName  = char(s.eventName);
paramNames = cell(s.paramNames);
paramData  = cell(s.eventData);

This solved the memory leakage issue for my client. I felt fortunate that I was not only able to detect Matlab’s memory leak but also find a working workaround without sacrificing performance or functionality.

In this particular case, I was lucky to have full control over my Java object, to be able to convert its fields to become public. Unfortunately, we do not always have similar control over the object that we use, because they were coded by a third party.

By the way, Matlab itself uses this struct mechanism in its code-base. For example, Matlab timers are implemented using Java objects (com.mathworks.timer.TimerTask). The timer callback in Matlab code converts the Java timer event data into a Matlab struct using the struct function, in %matlabroot%/toolbox/matlab/iofun/@timer/timercb.m. The users of the timer callbacks then get passed a simple Matlab EventData struct without ever knowing that the original data came from a Java object.

As an interesting corollary, this same struct mechanism can be used to detect internal properties of Matlab class objects. For example, in the timers again, we can get the underlying timer’s Java object as follows (note the highlighted warning, which I find a bit ironic given the context):

>> timerObj = timerfind
 
   Timer Object: timer-1
 
   Timer Settings
      ExecutionMode: singleShot
             Period: 1
           BusyMode: drop
            Running: off
 
   Callbacks
           TimerFcn: @myTimerFcn
           ErrorFcn: ''
           StartFcn: ''
            StopFcn: ''
 
>> timerFields = struct(timerObj)
Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be avoided.Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.(Type "warning off MATLAB:structOnObject" to suppress this warning.)timerFields = 
         ud: {}
    jobject: [1x1 javahandle.com.mathworks.timer.TimerTask]
Categories: Java, Low risk of breaking in future versions, Memory, Semi-documented feature, Stock Matlab function
Tags: , , ,
9 Comments

Recovering previous editor state

Editor with multiple loaded documents I find it very useful to use the Matlab editor’s ability to load multiple files to help me remember which files I still need to work on. I typically have a few dozen files loaded in the editor. I guess you could say that the editor’s list of files is a simple reflection of my open tasks. It would be extremely inconvenient if I ever lost this list.

Which is, unfortunately, exactly what happened to me yesterday.

I was about to close a figure window and accidentally closed the editor window that was behind it.

I was now in quite a jam: reopening the editor would not load all my files, but start with a blank (empty) editor. The Matlab editor, unlike modern browsers, does not have a ‘reopen last session’ option, and using the most-recently-used (MRU) files list would at best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).

Luckily for me, there is an escape hatch: Matlab stores its Desktop windows state in a file called MATLABDesktop.xml that is located in the user’s prefdir folder. This file includes information about the position and state (docked/undocked etc.) of every Desktop window. Since the editor files are considered Desktop documents (you can see them under the Desktop’s main menu’s Window menu), they are also included in this file. When I closed the Editor, these documents were simply removed from the MATLABDesktop.xml file.

It turns out that Matlab automatically stores a backup version of this file in another file called MATLABDesktop.xml.prev, in the same prefdir folder. We can inspect the folder using our system’s file browser. For example, on Windows we could use:

winopen(prefdir)

So before doing anything else, I closed Matlab (I actually crashed it to prevent any cleanup tasks to accidentally erase this backup file, but that turned out to be an unnecessary precaution), deleted the latest MATLABDesktop.xml file, replaced it with a copy of the MATLABDesktop.xml.prev file (which I renamed MATLABDesktop.xml), and only then did I restart Matlab.

Problem solved – everything back to normal. Resume breathing. Once again I have my never-ending virtual task list in front of me as I write this.

Lessons learned:

  1. don’t be too quick on the close button trigger
  2. always keep a relatively recent backup copy of your important config files (BTW, I use the same advice with my FireFox browser, where I normally have dozens of open tabs – I keep a backup copy of the sessionstore.js file)
  3. if you do get into a jam, don’t do anything hasty that might make recovery impossible. Calm down, look around, and maybe you’ll find an automatic backup somewhere
Categories: Desktop, Low risk of breaking in future versions, Undocumented feature
Tags: , , ,
6 Comments

2011 perspective & plans for 2012

With 2011 behind us and a fresh 2012 ahead, it is time again for a short look at this website’s achievements so far, and plans for the future.

I started this blog three years ago, with an article on changing Matlab’s Command Prompt colors, shortly followed by an article on my cprintf utility, which to this day is still the most popular article on this website. cprintf is also one of my top-downloaded utilities, second only to findjobj, and closely followed by officedoc and uiinspect.

In 2011, I published 47 articles, including:

Hopefully there was enough material and diversity in there to satisfy different audiences. Judging by the traffic on the site, this appears to be the case indeed. Interest in this website still grows steadily, continuing the trend from the first two years. To date, 164,000 unique readers have read at least one article here (two on average), in over 300,000 different visits – more than doubling the figures from last year. In fact, the lowest traffic point of the year, which is customarily around Christmas/New-Year, has had about the same level of traffic this year as the highest-traffic weeks of 2010 (the other dip you see in 2011 is due to a week-long site-overhaul in March):

Steady readership growth (click for details)

Steady readership growth (click for details)

RSS and email subscription has also grown at a steady pace. I’m quite proud of the fact that there are more readers/subscribers to this blog than any other Matlab-related blog, excluding perhaps Loren’s. Having felt the pressure and difficulty in writing a fresh weekly post for the past three years, I truly admire Loren’s six years of continuous high-quality blogging.

The top countries from which you readers visit this site remains unchanged from last year’s post. So this year I will show a different angle, of the top cities visiting in 2011: Munich, London, Tel Aviv, Moscow, New York, Paris, Bangalore, Berlin, Zurich and Toronto.

Natick (MA, USA), home of the MathWorks HQ and some 30,000 other inhabitants, has dropped to 12th place in 2011, although it still maintains the #3 position in all-time visits (since this blog was started). Apparently, as this website gets wider recognition by Matlab users, the relative percentage of MathWorkers interested in this blog decreases, although in absolute numbers I can see that MathWorks visits have remained more-or-less constant.

Readers from all over the world (click for details)

Readers from all over the world (click for details)

In 2012 I plan to continue posting about undocumented aspects of Matlab. Specific plans include the much-overdue articles on uiinspect and its close relative checkClass, as well as additional articles on internal built-in controls. I hope to cross out many items in my TODO list.

There will also be more articles by guest bloggers – I have a growing list of such guest bloggers, of which I am extremely pleased, and some of the promised articles are very interesting. I encourage anyone who has an idea for an article to contact me by email (altmany at gmail, or use the link at the top-right of this page).

Happy 2012 everybody!

- Yair Altman

Categories: Uncategorized
Leave a comment

Command Window text manipulation

Sometimes the most obscure problems have simple solutions.

A few days ago, a Matlab user asked whether it is possible to solve the flashing effect whenever he cleared the Command Window. It turns out that this user runs a long process, and wanted to display interim information (progress etc.) in the Command Window. The obvious solution that he employed was to display the data in the Command Window, and then erase the window (using clc) and rewrite the data periodically.

Using control characters

Now, there are obviously other ways of doing this, the most obvious being a dedicated GUI window that displays the information and updates periodically. But to solve the user’s immediate issue, the solution I provided (acting on the 80-20 Pareto principle – a dedicated GUI window is better but would take longer to set up) was to use control characters to erase old data when displaying new data, rather than clearing the window. Here is the basic pseudo-code that I suggested (slightly modified):

reverseStr = '';
for idx = 1 : someLargeNumber
 
   % Do some computation here...
 
   % Display the progress
   percentDone = 100 * idx / someLargeNumber;
   msg = sprintf('Percent done: %3.1f', percentDone)
   fprintf([reverseStr, msg]);
   reverseStr = repmat(sprintf('\b'), 1, length(msg));
end

The idea is to use the backspace control-character (BS, or sprintf(‘\b’), or char(8)) repeatedly in order to erase the preceding characters from the Command Window, then print the new data.

(see related comments by Helge here)

Compatibility aspects

Back in the good-ol’-days, when I was hacking away c-shell scripts, ages ago when I created command-prompt C apps, and aeons ago on Vax (R.I.P.), I would have used the carriage-return control-char (CR, or sprintf(‘\r’), or char(13)) to completely erase everything up to the beginning of the current line. This would be much simpler than the repeated backspaces (using repmat in the pseudo-code above). Unfortunately, CRs behave differently in Matlab’s Command Window, causing \r to jump to the next line (similarly to \n), rather than erase to the beginning of the line. This is probably due to Java’s JTextArea’s implementation (on which the Command Window is based), and not due to Matlab itself. In any case, it shows that not all control characters behave the same way on different environments, which is actually not very surprising.

Another widely-used control character, the bell control-char (BEL, or sprintf(‘\g’), or char(7)) is not accepted at all by Matlab’s implementation of sprintf and its variants. Matlab users can always use the beep function of course, I’m just pointing this out as another inconsistency between Matlab’s *printf() implementation and that of other environments. And don’t even think of using raw device escape sequences (ah, the good-ol’-days, long gone now…).

Control characters that are accepted in Matlab and behave as expected include: FF (\f), NL (\n) and TAB (\t). These can be used in fprintf to modify the text spacing. The sprintf documentation mentions which of the control characters are accepted, so this is not, strictly speaking, an undocumented aspect. However, note that there is a discrepancy between the list of accepted control chars in the online/doc page compared to the help section (\a and \v are mentioned in the former but not in the latter).

For another type of Command Window text manipulation, namely colors, refer to my cprintf utility. For anyone who hasn’t noticed, I recently updated the utility on the Matlab File Exchange. Due to some internal modifications by MathWorks to the Command Window implementation in R2011b, cprintf no longer needs to pad color segments with spaces, and separate color segments can now be directly adjacent to each other (in R2011a and earlier, the spaces are unfortunately needed).

Have you used control characters in an innovative manner in your work? If so, please share your experience in a comment.

Happy New Year everyone!

Categories: Desktop, Low risk of breaking in future versions, Stock Matlab function
Tags:
3 Comments

Ideas for a new book

The experience of writing my Matlab-Java book was truly exhilarating. The book is now officially published and several hundred copies have been shipped already, first in America and starting last week also in the rest of the world. I hope these will all arrive before Christmas – if not then please be patient a few more days, since the initial demand has apparently exceeded the printing expectations.

If you are one of those who have received the book, please be kind enough to write a review of it, in book sites such as Amazon or Barnes & Noble.

As promised, I will maintain the book’s webpage with an errata list and possibly more information, as they become available.

The question of a new book

As with any birth, the initial exhilaration completely overwhelms, letting me forget how hard it has been to write the book. So while this “high” lasts, I wanted to ask you my readers for your opinion regarding a possible future book.

Which of the following books by me, possibly co-authored with another writer, would you be interested to read and/or have in your library?

  1. Professional Matlab application development
  2. Professional Matlab GUI
  3. Matlab performance tuning
  4. Undocumented Matlab – the non-Java parts
  5. Some other subject (please specify)
  6. None of the above

Please choose only a single item, or prioritize your choices. It will be a book about only one of the above topics, not several topics. I’m not going to write another 700-page monster that takes 5 years to prepare…

There are of course many factors going into a decision about whether or not to enter a book-writing project. It is a multi-year commitment that requires lots of effort, time, focus, and attention to detail. It affects the writer in a way that influences the entire family. In fact, my wife has already voted an emphatic “NO!” on this subject, and I’m pretty ambivalent about this issue myself.

Please do let me know what you think in a short comment. Happy Holidays everyone!

Categories: Uncategorized
Tags:
16 Comments