- Enclose with " for exact match e.g., "uitable report"
- Explicit multi-threading in Matlab – part 3
- Explicit multi-threading in Matlab – part 2
- Explicit multi-threading in Matlab – part 1
- Improving Simulink performance
- Undocumented button highlighting
- Assessing Java object size in Matlab
- Serializing/deserializing Matlab data
- MathWorks blogs facelift
- 2013 perspective & plans for 2014
- Accessing private object properties
- Class object creation performance
- Plotly graphs
- sprintfc – undocumented helper function
- Performance: accessing handle properties
- Listbox layout customization
- Desktop (32)
- Figure window (34)
- Guest bloggers (39)
- GUI (105)
- Handle graphics (48)
- Hidden property (32)
- Icons (7)
- Java (126)
- Listeners (16)
- Memory (12)
- Mex (8)
- Presumed future risk (246)
- Semi-documented feature (6)
- Semi-documented function (31)
- Stock Matlab function (92)
- Toolbox (2)
- UI controls (36)
- Uncategorized (8)
- Undocumented feature (115)
- Undocumented function (27)
TagsActiveX Callbacks COM Compiler Desktop Donn Shull Editor FindJObj GUI GUIDE Handle graphics HG2 Hidden property HTML Icons Internal component Java JavaFrame JIDE JMI keyboard Listener Malcolm Lidierth Matt Whitaker MCOS Memory Menubar Mex Performance Profiler Pure Matlab schema schema.class schema.prop scribe Semi-documented function Toolbar uicontrol UIInspect uitable uitools uiundo Undocumented feature Undocumented function Undocumented property
- Yair Altman (9 hours 0 minutes ago): @Chris – I’m not sure what happened in your case but why use a button control at all? you can use an invisible axes, similar to my “buttons” in this...
- Yair Altman (9 hours 2 minutes ago): @Raj – I do not think that this is supported in a single-line editbox, but you can always use a multi-line editbox or listbox.
- Yair Altman (9 hours 3 minutes ago): I do not know of a way to integrate .NET controls in Matlab figures, but I’m guessing that this may be a solved problem in the Java world. So if you find a way to...
- Yair Altman (9 hours 6 minutes ago): @Sandro – I would be happy to provide you with my professional consulting services via email. Send me an email via the link at the top-right of this page if you are...
- Sandro (3 days 5 hours ago): I’m trying to insert an icon like in your post, but I can not. Could you send by email an example that is running? ie, for me to do ctrl+c ctrl+v. So I will be able to...
- Chris (3 days 8 hours ago): Hi Yair, thanks for all the great help! I read your instruction of changing the border of a button, but it did’nt work. I want to create a button in a matlab gui with an image...
- Raj (3 days 10 hours ago): Hey Yair, I’ve got a question. Your Text Selection Method works fine! I’ve tried make a search function for my editbox so it can mark(select) every word he found. But the...
- CitizenInsane (4 days 15 hours ago): Hi! This is great and inspirative work. Is it possible to perform a ‘reset property value to default’ with jide grid controls?. I was thinking of using .NET...
- Ayantha (4 days 18 hours ago): Thanks Yair,It worked. For some unknown reason, it didn’t work with an inbuilt example of Matlab. But it worked fine with my own code. Thanks again and keep your good work...
- Yair Altman (5 days 8 hours ago): @Jacques – use the old (pre-2008a) uitable, which returns the Java object directly
- Jacques (5 days 9 hours ago): Hello Yair, I am using your findjobj function in my code to resize the row headers of 3 uitable elements (on the same page). It has helped me a lot but it takes a significant time...
- Magu_ (6 days 16 hours ago): Thank you for your answer. This is very neat I didn’t know that exist. I did it for the fieldnames but failed for methods so far. “methods” seems to behave...
- Yair Altman (8 days 8 hours ago): @Magu – try to implement hidden methods fieldnames and/or methods in your class. The first is for properties, the second is for methods.
- Yair Altman (9 days 9 hours ago): @Darin – y.setHorizontalTextPosition(ja vax.swing.SwingConstants.LEFT) ; This is covered both in my book and my uicontrols customization report.
- Darin (10 days 5 hours ago): Hi Yair, Thanks, this info is very helpful! (Even 3+ years later ) When I used the code on a pushbutton, it centered the icon… and had the text centered as well. I tried using...
In the past weeks, I explained how we can start asynchronous Java threads to run in parallel to the main Matlab processing using Java and Dot-Net threads. Today I continue by examining C/C++ threads. This series will conclude next week, by discussing timer objects and process-spawning.
The alternatives that can be used to enable Matlab multithreading with C/C++ include standard POSIX threads, native OS threads, OpenMP, MPI (Message Passing Interface), TBB (Thread Building Blocks), Cilk, OpenACC, OpenCL or Boost. We can also use libraries targeting specific platforms/architectures: Intel MKL, C++ AMP, Bolt etc. Note that the Boost library is included in every relatively-modern Matlab release, so we can either use the built-in library (easier to deploy, consistency with Matlab), or download and install the latest version and use it separately. On Windows, we can also use .Net’s
Thread class, as explained in last week’s article. This is a very wide range of alternatives, and it’s already been covered extensively elsewhere from the C/C++ side.
Today I will only discuss the POSIX alternative. The benefit of POSIX is that is is more-or-less cross-platform, enabling the same code to work on all MATLAB platforms, as well as any other POSIX-supported platform.
POSIX threads (Pthreads) is a standard API for multi-threaded programming implemented natively on many Unix-like systems, and also supported on Windows. Pthreads includes functionality for creating and managing threads, and provides a set of synchronization primitives such as mutexes, conditional variables, semaphores, read/write locks, and barriers. POSIX has extensive offline and online documentation.
Note that POSIX is natively supported on Macs & Linux, but requires a separate installation on Windows. Two of the leading alternatives are Pthreads_Win32 (also works on Win64, despite its name…), and winpthreads (part of the extensive MinGW open-source project).
When creating a C/C++ -based function, we can either compile/link it into a dynamic/shared library (loadable into Matlab using the loadlibrary & calllib functions), or into a MEX file that can be called directly from M-code. The code looks the same, except that a MEX file has a gateway function named mexFunction that has a predefined interface. Today I’ll show the MEX variant using C; the adaptation to C++ is easy. To create multi-threaded MEX, all it takes is to connect the thread-enabled C/C++ code into our mexFunction(), provide the relevant threading library to the mex linker and we’re done.
Last week, I explained how we can start asynchronous Java threads to run in parallel to the main Matlab processing. Today I continue the series by examining .Net threads. Next week I will discuss C++ threads, followed by a final article on timers and process-spawning.
I continue using last week’s example, where we compute some data, save it to file on a relatively slow USB/network disk, and then proceed with another calculation. The purpose of multi-threading would be to offload the I/O onto a separate thread, so that the Matlab computation can continue in parallel without needing to wait for the slow I/O.
Dot-Net (.Net), like Java and C++, also enables multithreading. .Net libraries (assemblies) are commonly distributed as DLL files, which can be loaded into Matlab using the NET.addAssembly function, similarly to the javaaddpath function for Java classes. Using these assemblies in Matlab is then as straight-forward as in Java:
NET.addAssembly('C:\Yair\Code\NetThread.dll'); data = rand(5e6,1); % pre-processing (5M elements, ~40MB) start(My.NetThread('F:\test.data',data)); % start running in parallel data = fft(data); % post-processing (.Net I/O runs in parallel)
One of the limitations of Matlab already recognized by the community, 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 implicit multiprocessing which relies on built-in threading support in some MATLAB functions, or explicit multiprocessing 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 – don’t nit-pick).
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’s main processing thread (known as the Main Thread, Matlab Thread, or simply MT) than in reducing the computer’s total energy consumption. In such cases, offloading work to asynchronous C++, Java or .Net threads could remove bottlenecks from Matlab’s main thread, achieving significant speedup.
Today’s article is a derivative of a much larger section on explicit multi-threading in Matlab, that will be included in my upcoming book MATLAB Performance Tuning, which will be published later this year. It is the first in a series of articles that will be devoted to various alternatives.
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:
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.
~10 seconds happens to be too slow for our specific needs. We could perhaps improve it a bit with some fancy tricks for save or fwrite. But let’s take a different approach today, using multi-threading:
Using Java threads
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’s started with the -nojvm 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.
To use Java threads in Matlab, first create a class that implements the
Runnable interface or extends java.lang.Thread. In either case we need to implement at least the run() method, which runs the thread’s processing core.
Now let us replace the serial I/O with a very simple dedicated Java thread. Our second calculation (fft) will not need to wait for the I/O to complete, enabling much faster responsiveness on Matlab’s MT. In this case, we get a 58x (!) speedup:
One of my consulting clients approached me yesterday with a mystery: In his GUIDE-generated GUI, one of the buttons had a bluish tint, and no obvious property seemed to control this or to differentiate it from its sibling controls. Here’s a parred-down version of his GUI:
So while it was very nice to have a highlighted button in this manner, the fact that he did not know why it happened and how to control it was a bit unsettling. Which is where I came in, and it turns out that the solution to the mystery is simple and very easy to use. My client now happily switches button highlights on and off, just for the fun of it…
Before I describe the solution (spoiler alert: scroll down), I think it is instructional to understand the unsuccessful attempts, so here goes:
Have you noticed that all Java object references are displayed as using 0 bytes in the Matlab Workspace browser and the whos function? This is not a bug, but in fact a deliberate design decision, in order to avoid the need to calculate the deep-memory usage of Java references (i.e., objects that include references to other objects etc.).
Well, sometimes it so happens that we really need to know the size of the Java object, or the size difference between two objects (to help resolve memory leaks, for example). There are several resources online that explain how to do this in Matlab (examples 1, 2, 3). Today I will show two alternatives that I found useful within the context of Matlab:
Last year I wrote an article on improving the performance of the save function. The article discussed various ways by which we can store Matlab data on disk. However, in many cases we are interested in a byte-stream serialization, in order to transmit information to external processes.
The request to get a serialized byte-stream of Matlab data has been around for many years (example), but MathWorks has never released a documented way of serializing and unserializing data, except by storing onto a disk file and later loading it from file. Naturally, using a disk file significantly degrades performance. We could always use a RAM-disk or flash memory for improved performance, but in any case this seems like a major overkill to such a simple requirement.
In last year’s article, I presented a File Exchange utility for such generic serialization/deserialization. However, that utility is limited in the types of data that it supports, and while it is relatively fast, there is a much better, more generic and faster solution.
The solution appears to use the undocumented built-in functions getByteStreamFromArray and getArrayFromByteStream, which are apparently used internally by the save and load functions. The usage is very simple:
byteStream = getByteStreamFromArray(anyData); % 1xN uint8 array anyData = getArrayFromByteStream(byteStream);
Many Matlab functions, documented and undocumented alike, are defined in XML files within the %matlabroot%/bin/registry/ folder; our specific functions can be found in %matlabroot%/bin/registry/hgbuiltins.xml. While other functions include information about their location and number of input/output args, these functions do not. Their only XML attribute is
type = ":all:", which seems to indicate that they accept all data types as input. Despite the fact that the functions are defined in hgbuiltins.xml, they are not limited to HG objects – we can serialize basically any Matlab data: structs, class objects, numeric/cell arrays, sparse data, Java handles, timers, etc. For example:
For those of you who have not noticed, MathWorks has made a very nice facelift to its official blogs section on Matlab Central (there are also some unofficial internal blogs, but they are unfortunately not publicly accessible).
If you have not done so already, I encourage you to browse the available blogs and subscribe – some very interesting content has accumulated there, and continues to be added a few times each month. I follow these blogs closely, and have learned quite a bit from them over the years.
No official announcement has been released yet AFAIK. However, I expect (at the very least) a post about this in the next few days in the “Matlab Spoken Here” blog (formerly the Desktop or Community blog). If and when it is posted, I encourage you to post a comment there, letting MathWorks know what you think of the new look-&-feel. Until then, this remains an undocumented feature [ he he ] and you can leave your comments below…
Don’t let this stop you from subscribing to this blog – simply click the RSS button or subscription link at the top of this webpage to get the latest undocumented article delivered to you via email or reader, once a week. And guess what? it’s completely free… In the meantime, enjoy the following earth-shattering archaeological find that I found in some online archive:
With 2013 behind us and a fresh 2014 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 nearly five years ago, thinking it would be nice to post about a few dozen undocumented features. I had no idea whether this material would be of any use to Matlab users, and I expected the website to become just another a niche blog. In fact, I was not sure that at a rate of one article per week I would have enough content for more than a year or two.
250 posts, 2000 reader comments, and 500K unique visitors later, it is obvious that I underestimated the impact that this blog would make. My pipeline of future articles continues to grow along with all other measurable quantities of website traffic.
Stats for nerds (and potential advertisers…)
Interest in this website still grows steadily, continuing the trend from the past years. To date, 514,400 unique readers have read at least one article here (two on average), in almost a million different visits, reaching over 8000 unique visits (plus ~2000 RSS and email subscribers) per week. These figures are about 60% up from last year, so the upward trend continues although at a slightly lower pace than previously. In the following graph, the traffic dips are due to the annual December holidays and the site-overhaul in 2011. The growth trend is quite evident:
Some time ago, I needed to modify a property value of a class object. The problem was that this property was declared as
private and for some reason my client could not modify the originating classdef to make this property accessible.
We start with a very simple class definition:
classdef MyClass properties (SetAccess=private) %GetAccess = public y end properties (Access=private) %GetAccess = SetAccess = private x end methods function obj = MyClass(x,y) % constructor if nargin>0, obj.x = x; end if nargin>1, obj.y = y; end end function result = isPropEqualTo(obj,propName,value) result = (obj.(propName)==value); end end end
The problem is simple: we need to both get and set the value of inaccessible private properties x,y. But following object construction,
MyClass enables direct read access only to property y, and write access to neither of its properties:
>> obj = MyClass(3,4) obj = MyClass with properties: y: 4 >> obj.x You cannot get the 'x' property of MyClass. >> obj.x=5 You cannot set the 'x' property of MyClass. >> obj.y=5 You cannot set the read-only property 'y' of MyClass.
A dead end, would you say? – Well, it never stopped us before, has it? After all, is it not the raison-d’être of this blog?