264 relevant articles found:

Animated busy (spinning) icon

Matlab includes a wide variety of internal widgets (GUI components) that could be very useful in our GUIs. One such widget is an animated spinning icon, which is often used by Matlab itself and numerous toolboxes to illustrate a running task:

Sample usage of an animated spinning icon

Sample usage of an animated spinning icon

One of the internal widgets that are readily-available for use in our Matlab GUI and displays a similar (but not identical) spinning icon is BusyAffordance, which is included in the built-in com.mathworks.widgets package. BusyAffordance creates a visible panel with an animated spinning icon and optional text label as long as the panel’s object is in the “started” mode (the mode can be started/stopped numerous times).

Animated spinner icon

Animated spinner icon

The usage is very simple: Continue reading

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

Transparent uipanels

A well-known Matlab limitation is that component position vectors must be specified as either ‘normalized’ or some fixed-sized value, but not in combination. For example, we cannot place a button in the center of the screen (normalized x/y=0.5) with a fixed sized width/height. Either all position elements are normalized, or all are fixed. Most Matlab GUIs that I’ve seen keep the normalized units, with the result that buttons look bloated or shrunken when the figure is resized:

hButton = uicontrol('Units','norm', 'Position',[0.5,0.5,0.15,0.15], 'String','click me!');

bad-looking resized normalized button

bad-looking resized normalized button

A common way to address this latter limitation is to use a borderless containing uipanel at the requested normalized position, and place a fixed-sized component as a child of that panel:

bgColor = get(gcf,'Color');
hPanel = uipanel('Units','norm', 'Position',[0.5, 0.5, 0.45, 0.45], 'BorderType','none', 'BackgroundColor',bgColor);
hButton = uicontrol('Parent',hPanel, 'Units','pixels', 'Position',[0,0,60,20], 'String','click me!');

fixed-size button at normalized position

fixed-size button at normalized position

This works well in simple figures, where there is nothing beneath the panel/control. Resizing the figure will keep the button centered, while preserving its 60×20 size. But what happens if we have an axes beneath? In this case we encounter another Matlab limitation, Continue reading

Categories: GUI, Handle graphics, Medium risk of breaking in future versions, Undocumented feature
Tags: , , ,
1 Comment

uicontextmenu performance

I would like to introduce guest blogger Robert Cumming, an independent contractor based in the UK who has recently worked on certification of the newest advanced civil aircraft. Today Robert will discuss the performance of uicontextmenus in interactive GUIs, which were used extensively in flight test analysis.

Have you ever noticed that a GUI slows down over time? I was responsible for designing a highly complex interactive GUI, which plotted flight test data for engineers and designers to analyze data for comparison with pre-flight predictions. This involved extensive plotting of data (pressure, forces/moments, anemometry, actuator settings etc….), where individual data points were required to have specific/customizable uicontextmenus.

Matlab’s documentation on uicontextmenus discusses adding them to plots, but makes no mention of the cleaning up afterwards.

Let’s start with some GUI basics. First we create a figure with a simple axes and a line:

x = [-10:0.2:10];
y = x.^2;
h = figure;
ax = axes ( 'parent',h );
hplot = plot ( ax, x, y );

Adding a uicontextmenu to the plot creates extra objects:

uic = uicontextmenu;
uimenu ( uic, 'Label','Menu A.1' );
set ( hplot, 'uicontextmenu',uic );
fprintf ( 'Figure (h) has %i objects\n', length ( findobj ( h ) ) );

In this instance there are 5 objects, the individual menu and uicontextmenu have created an additional 2 objects. All of this is quite basic as you would expect.

Basic plot with a custom context menu

Basic plot with a custom context menu


Continue reading

Categories: Guest bloggers, Handle graphics, Low risk of breaking in future versions, Undocumented feature
Tags: , , , ,
4 Comments

JSON-Matlab integration

I would like to once again welcome guest blogger Mark Mikofski. Mark has written here last year about JGIT-Matlab integration (p.s., in the recently-released R2014a, MathWorks added GIT support to Simulink projects, although for some reason not to Matlab projects). Today, Mark discusses how to integrate JSON with Matlab.

What is JSON

It’s often necessary to save objects and arrays to a file, for lots of reasons. In Matlab, you would just save the desired objects in a mat-file, but that’s a binary format that in general only Matlab can read. One reason you might want to cache objects is to pass to a non-Matlab API. True there are libraries to import mat-files (for example: JMatIO), but there are already accepted standards for passing objects such as XML and JSON (JavaScript Object Notation, http://json.org) that most APIs readily understand. Both of these methods attempt to serialize data into a text based format that limits the types of objects they can contain. Because sometimes the API is a human being who needs to read and edit the file, one of the JSON’s goals is to be “easy for humans to read and write”.

Here’s a sample of a JSON object:

{
    "students": ["Dick", "Jane"],
    "assignments": ["essay", "term paper"]
    "scores": {
        "essay": {"Dick": 86, "Jane": 88},
        "term paper":  {"Dick": 89, "Jane": 87}
    },
    "cool": {"Dick": true, "Jane": true},
    "misc": null
}

Many web services, such as Twitter, use JSON in their APIs, because another JSON goal is to be “easy for machines to parse and generate”. JSON is based on the JavaScript ECMA standard in which it is native, and is extremely well documented.
Continue reading

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

Undocumented feature list

Three years ago I posted an article on Matlab’s undocumented feature function. feature is a Matlab function that enables access to undocumented internal Matlab functionality. Most of this functionality is not very useful, but in some cases it could indeed be very interesting. As sometimes happens, this innocent-enough article generated a lot of interest, both online and offline. Perhaps the reason was that in this article I listed the known list of supported features with a short explanation and references were available. At the time, this was the only comprehensive such listing, which I manually collected from numerous sources. For this reason I was delighted to receive Yves Piguet’s tip about the availability of a programmatic interface for a full listing of features:

>> list = feature('list')   % 260 features in R2013b
list = 
1x260 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count

Which can be listed as follows:

for i = 1 : length(list)
   fprintf('%35s has_cb=%d has_bi=%d calls=%d val=%g\n', ...
      list(i).name, list(i).has_callback, list(i).has_builtin, list(i).call_count, list(i).value);
end
 
                    100 has_cb=0 has_bi=1 calls=0 val=1
                    102 has_cb=0 has_bi=1 calls=0 val=1
                     12 has_cb=0 has_bi=1 calls=0 val=1
                     14 has_cb=0 has_bi=1 calls=0 val=1
                     25 has_cb=0 has_bi=1 calls=0 val=1
                    300 has_cb=0 has_bi=0 calls=0 val=1
                    301 has_cb=0 has_bi=0 calls=0 val=1
                     44 has_cb=0 has_bi=1 calls=0 val=1
                     45 has_cb=0 has_bi=1 calls=0 val=1
                      7 has_cb=0 has_bi=0 calls=0 val=1
                      8 has_cb=0 has_bi=1 calls=0 val=1
                      9 has_cb=0 has_bi=0 calls=0 val=1
                  accel has_cb=0 has_bi=1 calls=0 val=0
         AccelBlockSize has_cb=0 has_bi=1 calls=0 val=0
          AccelMaxTemps has_cb=0 has_bi=1 calls=0 val=0
    AccelThreadBlockMin has_cb=0 has_bi=1 calls=0 val=0
              allCycles has_cb=0 has_bi=1 calls=0 val=0
 AllWarningsCanBeErrors has_cb=1 has_bi=0 calls=0 val=0
           ArrayEditing has_cb=0 has_bi=0 calls=0 val=1
       AutomationServer has_cb=0 has_bi=1 calls=0 val=0
              CachePath has_cb=0 has_bi=0 calls=0 val=1
     CaptureScreenCount has_cb=0 has_bi=0 calls=0 val=0
       CheckMallocClear has_cb=0 has_bi=0 calls=0 val=1
                    ... (etc. etc.)

Unfortunately, in the latest Matlab R2014a, which was released last week, this nice feature has been removed:

>> list = feature('list')
Error using feature
Feature list not found

Luckily, the list can still be retrieved programmatically, using an undocumented MEX library function. Place the following in a file called feature_list.cpp:
Continue reading

Walter Roberson liked this post
Categories: High risk of breaking in future versions, Mex, Undocumented function
Tags: , ,
1 Comment

Explicit multi-threading in Matlab part 4

In the past weeks, I explained how we can start asynchronous Java threads to run in parallel to the main Matlab processing using Java, Dot-Net and C++ POSIX threads. Today I conclude the mini-series by examining two other alternatives, timer objects and process-spawning. As we shall see below, these are not “real” multi-threading alternatives, but they can indeed be important in certain use-cases.

Matlab timers

Multithreading helps application performance in two related but distinct ways:

  • By allowing code to run in parallel, on different CPUs or cores
  • By allowing code to run asynchronously, rather than in serial manner

C++, Java and .Net threads can improve performance by both of these manners. Matlab timers, on the other hand, only enable the second option, of running code asynchronously. The reason for this is that all M-code, including timer callback code, is executed by Matlab’s interpreter on a single processing thread (MT).

So, while a timer callback executes, no other M-code can run. This may seem on the face of it to be unhelpful. But in fact, the ability to schedule a Matlab processing task for later (non-serial) invocation, could be very handy, if we can time it so that the timer callback is triggered when the application is idle, for example, waiting for user input, following complex GUI update, or during late hours of the night.

I continue using last weeks’ 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. Here is an implementation of our asynchronous I/O example, this time using Matlab timers. First we define the timer’s callback function, using pure M-code (this is the Matlab equivalent of the run() method in the previous examples):
Continue reading

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

Explicit multi-threading in Matlab part 3

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.
Continue reading

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

Explicit multi-threading in Matlab part 2

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)

Continue reading

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

Explicit multi-threading in Matlab part 1

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.

Sample problem

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:
Continue reading

Categories: Java, Low risk of breaking in future versions
Tags: , , ,
11 Comments

Improving Simulink performance

A few days ago I happened to speak with a colleague about Simulink run-time performance, and we discussed various ideas for simulation speed-up. This topic is very important to MathWorks, as evidenced by a dedicated documentation section, newsletter articles (1, 2), webinars (1, 2, 3, 4) and multiple blog posts on improving simulation performance using the Simulink product.

This blog covers mainly the Matlab core product and closely-related toolboxes. However, since the various suggestions for improving performance are spread across so many resources, I thought that it would be worthwhile to create a post listing all the suggestions in a single place. When faced with a slow simulation, it’s nice to know that there are so many available speed-up options, so I hope readers will find it useful. Note that these suggestions are in the large part fully documented and supported. The ideas are listed based on semantic relationship, and not by order of importance:
Continue reading

Categories: Low risk of breaking in future versions
Tags: ,
3 Comments