Undocumented Matlab https://undocumentedmatlab.com Professional Matlab consulting, development and training Sun, 09 Mar 2025 15:39:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.4 Speeding-up builtin Matlab functions – part 3 https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3?utm_source=rss&utm_medium=rss&utm_campaign=speeding-up-builtin-matlab-functions-part-3 https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3#comments Mon, 06 Apr 2020 20:44:07 +0000 http://undocumentedmatlab.com/?p=11059 Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example.

The post Speeding-up builtin Matlab functions – part 3 appeared first on Undocumented Matlab.

]]>
A recurring theme in this website is that despite a common misperception, builtin Matlab functions are typically coded for maximal accuracy and correctness, but not necessarily best run-time performance. Despite this, we can often identify and fix the hotspots in these functions and use a modified faster variant in our code. I have shown multiple examples for this in various posts (example1, example2, many others).

Today I will show another example, this time speeding up the mvksdensity (multi-variate kernel probability density estimate) function, part of the Statistics toolbox since R2016a. You will need Matlab R2016a or newer with the Stats Toolbox to recreate my results, but the general methodology and conclusions hold well for numerous other builtin Matlab functions that may be slowing down your Matlab program. In my specific problem, this function was used to compute the probability density-function (PDF) over a 1024×1024 data mesh.

The builtin mvksdensity function took 76 seconds to run on my machine; I got this down to 13 seconds, a 6x speedup, without compromising accuracy. Here’s how I did this:

Preparing the work files

While we could in theory modify Matlab’s installed m-files if we have administrator privileges, doing this is not a good idea for several reasons. Instead, we should copy and rename the relevant internal files to our work folder, and only modify our local copies.

To see where the builtin files are located, we can use the which function:

>> which('mvksdensity')
C:\Program Files\Matlab\R2020a\toolbox\stats\stats\mvksdensity.m

In our case, we copy \toolbox\stats\stats\mvksdensity.m as mvksdensity_.m to our work folder, replace the function name at the top of the file from mvksdensity to mvksdensity_, and modify our code to call mvksdensity_ rather than mvksdensity.

If we run our code, we get an error telling us that Matlab can’t find the statkscompute function (in line #107 of our mvksdensity_.m). So we find statkscompute.m in the \toolbox\stats\stats\private\ folder, copy it as statkscompute_.m to our work folder, rename its function name (at the top of the file) to statkscompute_, and modify our mvksdensity_.m to call statkscompute_ rather than statkscompute:

[fout,xout,u] = statkscompute_(ftype,xi,xispecified,npoints,u,L,U,weight,cutoff,...

We now repeat the process over and over, until we have all copied all the necessary internal files for the program to run. In our case, it tuns out that in addition to mvksdensity.m and statkscompute.m, we also need to copy statkskernelinfo.m.

Finally, we check that the numeric results using the copied files are exactly the same as from the builtin method, just to be on the safe side that we have not left out some forgotten internal file.

Now that we have copied these 3 files, in practice all our attentions will be focused on the dokernel sub-function inside statkscompute_.m, since the profiling report (below) indicates that this is where all of the run-time is spent.

Identifying the hotspots

Now we run the code through the Matlab Profiler, using the “Run and Time” button in the Matlab Editor, or profile on/report in the Matlab console (Command Window). The results show that 99.8% of mvksdensity‘s time was spent in the internal dokernel function, 75% of which was spent in self-time (meaning code lines within dokernel):

Initial profiling results - pretty slow...
Initial profiling results - pretty slow...

Let’s drill into dokernel and see where the problems are:

Initial dokernel profiling results
Initial dokernel profiling results

Evaluating the normal kernel distribution

We can immediately see from the profiling results that a single line (#386) in statkscompute_.m is responsible for nearly 40% of the total run-time:

fk = feval(kernel,z);

In this case, kernel is a function handle to the normal-distribution function in \stats\private\statkskernelinfo>normal, which is evaluated 1,488,094 times. Using feval incurs an overhead, as can be seen by the difference in run-times: line #386 takes 29.55 secs, whereas the normal function evaluations only take 18.53 secs. In fact, if you drill into the normal function in the profiling report, you’ll see that the actual code line that computes the normal distribution only takes 8-9 seconds – all the rest (~20 secs, or ~30% of the total) is totally redundant function-call overhead. Let’s try to remove this overhead by calling the kernel function directly:

fk = kernel(z);

Now that we have a local copy of statkscompute_.m, we can safely modify the dokernel sub-function, specifically line #386 as explained above. It turns out that just bypassing the feval call and using the function-handle directly does not improve the run-time (decrease the function-call overhead) significantly, at least on recent Matlab releases (it has a greater effect on old Matlab releases, but that’s a side-issue).

We now recognize that the program only evaluates the normal-distribution kernel, which is the default kernel. So let’s handle this special case by inlining the kernel’s one-line code (from statkskernelinfo_.m) directly (note how we move the condition outside of the loop, so that it doesn’t get recomputed 1 million times):

...
isKernelNormal = strcmp(char(kernel),'normal');  % line #357 
for i = 1:m
    Idx = true(n,1);
    cdfIdx = true(n,1);
    cdfIdx_allBelow = true(n,1);
    for j = 1:d
        dist = txi(i,j) - ty(:,j);
        currentIdx = abs(dist) <= halfwidth(j);
        Idx = currentIdx & Idx; % pdf boundary
        if iscdf
            currentCdfIdx = dist >= -halfwidth(j);
            cdfIdx = currentCdfIdx & cdfIdx; %cdf boundary1, equal or below the query point in all dimension
            currentCdfIdx_below = dist - halfwidth(j) > 0;                   
            cdfIdx_allBelow = currentCdfIdx_below & cdfIdx_allBelow; %cdf boundary2, below the pdf lower boundary in all dimension
        end
    end
    if ~iscdf
        nearby = index(Idx);
    else
        nearby = index((Idx|cdfIdx)&(~cdfIdx_allBelow));
    end
    if ~isempty(nearby)
        ftemp = ones(length(nearby),1);
        for k =1:d
            z = (txi(i,k) - ty(nearby,k))./u(k);
            if reflectionPDF
                zleft  = (txi(i,k) + ty(nearby,k)-2*L(k))./u(k);
                zright = (txi(i,k) + ty(nearby,k)-2*U(k))./u(k);
                fk = kernel(z) + kernel(zleft) + kernel(zright);  % old: =feval()+...
            elseif isKernelNormal
                fk = exp(-0.5 * (z.*z)) ./ sqrt(2*pi);
            else
                fk = kernel(z);  %old: =feval(kernel,z);
            end
            if needUntransform(k)
                fk = untransform_f(fk,L(k),U(k),xi(i,k));
            end
            ftemp = ftemp.*fk;
        end
        f(i) = weight(nearby) * ftemp;
    end
    if iscdf && any(cdfIdx_allBelow)
        f(i) = f(i) + sum(weight(cdfIdx_allBelow));
    end
end
...

This reduced the kernel evaluation run-time from ~30 secs down to 8-9 secs. Not only did we remove the direct function-call overhead, but also the overheads associated with calling a sub-function in a different m-file. The total run-time is now down to 45-55 seconds (expect some fluctuations from run to run). Not a bad start.

Main loop – bottom part

Now let’s take a fresh look at the profiling report, and focus separately on the bottom and top parts of the main loop, which you can see above. We start with the bottom part, since we already messed with it in our fix to the kernel evaluation:

Profiling results for bottom part of the main loop
Profiling results for bottom part of the main loop

The first thing we note is that there’s an inner loop that runs d=2 times (d is set in line #127 of mvksdensity_.m – it is the input mesh’s dimensionality, and also the number of columns in the txi data matrix). We can easily vectorize this inner loop, but we take care to do this only for the special case of d==2 and when some other special conditions occur.

In addition, we hoist outside of the main loop anything that we can (such as the constant exponential power, and the weight multiplication when it is constant [which is typical]), so that they are only computed once instead of 1 million times:

...
isKernelNormal = strcmp(char(kernel),'normal');
anyNeedTransform = any(needUntransform);
uniqueWeights = unique(weight);
isSingleWeight = ~iscdf && numel(uniqueWeights)==1;
isSpecialCase1 = isKernelNormal && ~reflectionPDF && ~anyNeedTransform && d==2;
expFactor = -0.5 ./ (u.*u)';
TWO_PI = 2*pi;
for i = 1:m
    ...
    if ~isempty(nearby)
        if isSpecialCase1
            z = txi(i,:) - ty(nearby,:);
            ftemp = exp((z.*z) * expFactor);
        else
            ftemp = 1;  % no need for the slow ones()
            for k = 1:d
                z = (txi(i,k) - ty(nearby,k)) ./ u(k);
                if reflectionPDF
                    zleft  = (txi(i,k) + ty(nearby,k)-2*L(k)) ./ u(k);
                    zright = (txi(i,k) + ty(nearby,k)-2*U(k)) ./ u(k);
                    fk = kernel(z) + kernel(zleft) + kernel(zright);  % old: =feval()+...
                elseif isKernelNormal
                    fk = exp(-0.5 * (z.*z)) ./ sqrt(TWO_PI);
                else
                    fk = kernel(z);  % old: =feval(kernel,z)
                end
                if needUntransform(k)
                    fk = untransform_f(fk,L(k),U(k),xi(i,k));
                end
                ftemp = ftemp.*fk;
            end
            ftemp = ftemp * TWO_PI;
        end
        if isSingleWeight
            f(i) = sum(ftemp);
        else
            f(i) = weight(nearby) * ftemp;
        end
    end
    if iscdf && any(cdfIdx_allBelow)
        f(i) = f(i) + sum(weight(cdfIdx_allBelow));
    end
end
if isSingleWeight
    f = f * uniqueWeights;
end
if isKernelNormal && ~reflectionPDF
    f = f ./ TWO_PI;
end
...

This brings the run-time down to 31-32 secs. Not bad at all, but we can still do much better:

Main loop – top part

Now let’s take a look at the profiling report’s top part of the main loop:

Profiling results for top part of the main loop
Profiling results for top part of the main loop

Again we note is that there’s an inner loop that runs d=2 times, which we can again easily vectorize. In addition, we note the unnecessary repeated initializations of the true(n,1) vector, which can easily be hoisted outside the loop:

...
TRUE_N = true(n,1);
isSpecialCase2 = ~iscdf && d==2;
for i = 1:m
    if isSpecialCase2
        dist = txi(i,:) - ty;
        currentIdx = abs(dist) <= halfwidth;
        currentIdx = currentIdx(:,1) & currentIdx(:,2);
        nearby = index(currentIdx);
    else
        Idx = TRUE_N;
        cdfIdx = TRUE_N;
        cdfIdx_allBelow = TRUE_N;
        for j = 1:d
            dist = txi(i,j) - ty(:,j);
            currentIdx = abs(dist) <= halfwidth(j);
            Idx = currentIdx & Idx; % pdf boundary
            if iscdf
                currentCdfIdx = dist >= -halfwidth(j);
                cdfIdx = currentCdfIdx & cdfIdx; % cdf boundary1, equal or below the query point in all dimension
                currentCdfIdx_below = dist - halfwidth(j) > 0;
                cdfIdx_allBelow = currentCdfIdx_below & cdfIdx_allBelow; %cdf boundary2, below the pdf lower boundary in all dimension
            end
        end
        if ~iscdf
            nearby = index(Idx);
        else
            nearby = index((Idx|cdfIdx)&(~cdfIdx_allBelow));
        end
    end
    if ~isempty(nearby)
        ...

This brings the run-time down to 24 seconds.

We next note that instead of using numeric indexes to compute the nearby vector, we could use faster logical indexes:

...
%index = (1:n)';  % this is no longer needed
TRUE_N = true(n,1);
isSpecialCase2 = ~iscdf && d==2;
for i = 1:m
    if isSpecialCase2
        dist = txi(i,:) - ty;
        currentIdx = abs(dist) <= halfwidth;
        nearby = currentIdx(:,1) & currentIdx(:,2);
    else
        Idx = TRUE_N;
        cdfIdx = TRUE_N;
        cdfIdx_allBelow = TRUE_N;
        for j = 1:d
            dist = txi(i,j) - ty(:,j);
            currentIdx = abs(dist) <= halfwidth(j);
            Idx = currentIdx & Idx; % pdf boundary
            if iscdf
                currentCdfIdx = dist >= -halfwidth(j);
                cdfIdx = currentCdfIdx & cdfIdx; % cdf boundary1, equal or below the query point in all dimension
                currentCdfIdx_below = dist - halfwidth(j) > 0;
                cdfIdx_allBelow = currentCdfIdx_below & cdfIdx_allBelow; %cdf boundary2, below the pdf lower boundary in all dimension
            end
        end
        if ~iscdf
            nearby = Idx;  % not index(Idx)
        else
            nearby = (Idx|cdfIdx) & ~cdfIdx_allBelow;  % no index()
        end
    end
    if any(nearby)
        ...

This brings the run-time down to 20 seconds.

We now note that the main loop runs m=1,048,576 (=1024×1024) times over all rows of txi. This is expected, since the loop runs over all the elements of a 1024×1024 mesh grid, which are reshaped as a 1,048,576-element column array at some earlier point in the processing, resulting in a m-by-d matrix (1,048,576-by-2 in our specific case). This information helps us, because we know that there are only 1024 unique values in each of the two columns of txi. Therefore, instead of computing the “closeness” metric (which leads to the nearby vector) for all 1,048,576 x 2 values of txi, we calculate separate vectors for each of the 1024 unique values in each of its 2 columns, and then merge the results inside the loop:

...
isSpecialCase2 = ~iscdf && d==2;
if isSpecialCase2
    [unique1Vals, ~, unique1Idx] = unique(txi(:,1));
    [unique2Vals, ~, unique2Idx] = unique(txi(:,2));
    dist1 = unique1Vals' - ty(:,1);
    dist2 = unique2Vals' - ty(:,2);
    currentIdx1 = abs(dist1) <= halfwidth(1);
    currentIdx2 = abs(dist2) <= halfwidth(2);
end
for i = 1:m
    if isSpecialCase2
        idx1 = unique1Idx(i);
        idx2 = unique2Idx(i);
        nearby = currentIdx1(:,idx1) & currentIdx2(:,idx2);
    else
        ...

This brings the run-time down to 13 seconds, a total speedup of almost ~6x compared to the original version. Not bad at all.

For reference, here's a profiling summary of the dokernel function again, showing the updated performance hotspots:

Profiling results after optimization
Profiling results after optimization

The 2 vectorized code lines in the bottom part of the main loop now account for 72% of the remaining run-time:

    ...
    if ~isempty(nearby)
        if isSpecialCase1
            z = txi(i,:) - ty(nearby,:);
            ftemp = exp((z.*z) * expFactor);
        else
            ...

If I had the inclination, speeding up these two code lines would be the next logical step, but I stop at this point. Interested readers could pick up this challenge and post a solution in the comments section below. I haven't tried it myself, so perhaps there's no easy way to improve this. Then again, perhaps the answer is just around the corner - if you don't try, you'll never know...

Data density/resolution

So far, all the optimization I made have not affected code accuracy, generality or resolution. This is always the best approach if you have some spare coding time on your hands.

In some cases, we might have a deep understanding of our domain problem to be able to sacrifice a bit of accuracy in return for run-time speedup. In our case, we identify the main loop over 1024x1024 elements as the deciding factor in the run-time. If we reduce the grid-size by 50% in each dimension (i.e. 512x512), the run-time decreases by an additional factor of almost 4, down to ~3.5 seconds, which is what we would have expected since the main loop size has decreased 4 times in size. While this reduces the results resolution/accuracy, we got a 4x speedup in a fraction of the time that it took to make all the coding changes above.

Different situations may require different approaches: in some cases we cannot sacrifice accuracy/resolution, and must spend time to improve the algorithm implementation; in other cases coding time is at a premium and we can sacrifice accuracy/resolution; and in other cases still, we could use a combination of both approaches.

Conclusions

Matlab is composed of thousands of internal functions. Each and every one of these functions was meticulously developed and tested by engineers, who are after all only human. Whereas supreme emphasis is always placed with Matlab functions on their accuracy, run-time performance often takes a back-seat. Make no mistake about this: code accuracy is almost always more important than speed, so I’m not complaining about the current state of affairs.

But when we run into a specific run-time problem in our Matlab program, we should not despair if we see that built-in functions cause slowdown. We can try to avoid calling those functions (for example, by reducing the number of invocations, or decreasing the data resolution, or limiting the target accuracy, etc.), or we could optimize these functions in our own local copy, as I have shown today. There are multiple techniques that we could employ to improve the run time. Just use the profiler and keep an open mind about alternative speed-up mechanisms, and you’d be half-way there. For ideas about the multitude of different speedup techniques that you could use in Matlab, see my book Accelerating Matlab Performance.

Let me know if you’d like me to assist with your Matlab project, either developing it from scratch or improving your existing code, or just training you in how to improve your Matlab code’s run-time/robustness/usability/appearance.

In the meantime, Happy Easter/Passover everyone, and stay healthy!

The post Speeding-up builtin Matlab functions – part 3 appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3/feed 4
Improving graphics interactivity https://undocumentedmatlab.com/articles/improving-graphics-interactivity?utm_source=rss&utm_medium=rss&utm_campaign=improving-graphics-interactivity https://undocumentedmatlab.com/articles/improving-graphics-interactivity#comments Sun, 21 Apr 2019 21:03:10 +0000 http://undocumentedmatlab.com/?p=8723 Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes.

The post Improving graphics interactivity appeared first on Undocumented Matlab.

]]>
Matlab release R2018b added the concept of axes-specific toolbars and default axes mouse interactivity. Accelerating MATLAB Performance Plain 2D plot axes have the following default interactions enabled by default: PanInteraction, ZoomInteraction, DataTipInteraction and RulerPanInteraction.

Unfortunately, I find that while the default interactions set is much more useful than the non-interactive default axes behavior in R2018a and earlier, it could still be improved in two important ways:

  1. Performance – Matlab’s builtin Interaction objects are very inefficient. In cases of multiple overlapping axes (which is very common in multi-tab GUIs or cases of various types of axes), instead of processing events for just the top visible axes, they process all the enabled interactions for *all* axes (including non-visible ones!). This is particularly problematic with the default DataTipInteraction – it includes a Linger object whose apparent purpose is to detect when the mouse lingers for enough time on top of a chart object, and displays a data-tip in such cases. Its internal code is both inefficient and processed multiple times (for each of the axes), as can be seen via a profiling session.
  2. Usability – In my experience, RegionZoomInteraction (which enables defining a region zoom-box via click-&-drag) is usually much more useful than PanInteraction for most plot types. ZoomInteraction, which is enabled by default only enables zooming-in and -out using the mouse-wheel, which is much less useful and more cumbersome to use than RegionZoomInteraction. The panning functionality can still be accessed interactively with the mouse by dragging the X and Y rulers (ticks) to each side.

For these reasons, I typically use the following function whenever I create new axes, to replace the default sluggish DataTipInteraction and PanInteraction with RegionZoomInteraction:

function axDefaultCreateFcn(hAxes, ~)
    try
        hAxes.Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
        hAxes.Toolbar = [];
    catch
        % ignore - old Matlab release
    end
end

The purpose of these two axes property changes shall become apparent below.
This function can either be called directly (axDefaultCreateFcn(hAxes), or as part of the containing figure’s creation script to ensure than any axes created in this figure has this fix applied:

set(hFig,'defaultAxesCreateFcn',@axDefaultCreateFcn);

Test setup

Figure with default axes toolbar and interactivity
Figure with default axes toolbar and interactivity
To test the changes, let’s prepare a figure with 10 tabs, with 10 overlapping panels and a single axes in each tab:

hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel); %see MLint note below
    plot(hAxes(iTab),1:5,'-ob');
end
drawnow

p.s. – there’s a incorrect MLint (Code Analyzer) warning in line 9 about the call to axes(hPanel) being inefficient in a loop. Apparently, MLint incorrectly parses this function call as a request to make the axes in-focus, rather than as a request to create the axes in the specified hPanel parent container. We can safely ignore this warning.

Now let’s create a run-time test script that simulates 2000 mouse movements using java.awt.Robot:

tic
monitorPos = get(0,'MonitorPositions');
y0 = monitorPos(1,4) - 200;
robot = java.awt.Robot;
for iEvent = 1 : 2000
    robot.mouseMove(150, y0+mod(iEvent,100));
    drawnow
end
toc

This takes ~45 seconds to run on my laptop: ~23ms per mouse movement on average, with noticeable “linger” when the mouse pointer is near the plotted data line. Note that this figure is extremely simplistic – In a real-life program, the mouse events processing lag the mouse movements, making the GUI far more sluggish than the same GUI on R2018a or earlier. In fact, in one of my more complex GUIs, the entire GUI and Matlab itself came to a standstill that required killing the Matlab process, just by moving the mouse for several seconds.

Notice that at any time, only a single axes is actually visible in our test setup. The other 9 axes are not visible although their Visible property is 'on'. Despite this, when the mouse moves within the figure, these other axes unnecessarily process the mouse events.

Changing the default interactions

Let’s modify the axes creation script as I mentioned above, by changing the default interactions (note the highlighted code addition):

hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
end
drawnow

The test script now takes only 12 seconds to run – 4x faster than the default and yet IMHO with better interactivity (using RegionZoomInteraction).

Effects of the axes toolbar

The axes-specific toolbar, another innovation of R2018b, does not just have interactivity aspects, which are by themselves much-contested. A much less discussed aspect of the axes toolbar is that it degrades the overall performance of axes. The reason is that the axes toolbar’s transparency, visibility, background color and contents continuously update whenever the mouse moves within the axes area.

Since we have set up the default interactivity to a more-usable set above, and since we can replace the axes toolbar with figure-level toolbar controls, we can simply delete the axes-level toolbars for even more-improved performance:

hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
    hAxes(iTab).Toolbar = [];
end
drawnow

This brings the test script’s run-time down to 6 seconds – 7x faster than the default run-time. At ~3ms per mouse event, the GUI is now as performant and snippy as in R2018a, even with the new interactive mouse actions of R2018b active.

Conclusions

MathWorks definitely did not intend for this slow-down aspect, but it is an unfortunate by-product of the choice to auto-enable DataTipInteraction and of its sub-optimal implementation. Perhaps this side-effect was never noticed by MathWorks because the testing scripts probably had only a few axes in a very simple figure – in such a case the performance lags are very small and might have slipped under the radar. But I assume that many real-life complex GUIs will display significant lags in R2018b and newer Matlab releases, compared to R2018a and earlier releases. I assume that such users will be surprised/dismayed to discover that in R2018b their GUI not only interacts differently but also runs slower, although the program code has not changed.

One of the common claims that I often hear against using undocumented Matlab features is that the program might break in some future Matlab release that would not support some of these features. But users certainly do not expect that their programs might break in new Matlab releases when they only use documented features, as in this case. IMHO, this case (and others over the years) demonstrates that using undocumented features is usually not much riskier than using the standard documented features with regards to future compatibility, making the risk/reward ratio more favorable. In fact, of the ~400 posts that I have published in the past decade (this blog is already 10 years old, time flies…), very few tips no longer work in the latest Matlab release. When such forward compatibility issues do arise, whether with fully-documented or undocumented features, we can often find workarounds as I have shown above.

If your Matlab program could use a performance boost, I would be happy to assist making your program faster and more responsive. Don’t hesitate to reach out to me for a consulting quote.

The post Improving graphics interactivity appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/improving-graphics-interactivity/feed 2
Interesting Matlab puzzle – analysis https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis?utm_source=rss&utm_medium=rss&utm_campaign=interesting-matlab-puzzle-analysis https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis#comments Tue, 09 Apr 2019 11:52:00 +0000 http://undocumentedmatlab.com/?p=8664 Solution and analysis of a simple Matlab puzzle that leads to interesting insight on Matlab's parser.

The post Interesting Matlab puzzle – analysis appeared first on Undocumented Matlab.

]]>
Last week I presented a seemingly-innocent Matlab code snippet with several variants, and asked readers to speculate what its outcomes are, and why. Several readers were apparently surprised by the results. In today’s post, I offer my analysis of the puzzle.
The original code snippet was this:

function test
    try
        if (false) or (true)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end

With the following variants for the highlighted line #3:

        if (false) or (true)     % variant #1 (original)
        if (true)  or (false)    % variant #2
        if (true)  or (10< 9.9)  % variant #3
        if  true   or  10< 9.9   % variant #4
        if 10> 9.9 or  10< 9.9   % variant #5

Variant #1: if (false) or (true)

The first thing to note is that or is a function and not an operator, unlike some other programming languages. Since this function immediately follows a condition (true), it is not considered a condition by its own, and is not parsed as a part of the "if" expression.
In other words, as Roger Watt correctly stated, line #3 is actually composed of two separate expressions: if (false) and or(true). The code snippet can be represented in a more readable format as follows, where the executed lines are highlighted:

        if (false)
            or (true)
            disp('Yaba');
        else
            disp('Daba');
        end

Since the condition (false) is never true, the "if" branch of the condition is never executed; only the "else" branch is executed, displaying 'Daba' in the Matlab console. There is no parsing (syntactic) error so the code can run, and no run-time error so the "catch" block is never executed.
Also note that despite the misleading appearance of line #3 in the original code snippet, the condition only contains a single condition (false) and therefore neither short-circuit evaluation nor eager evaluation are relevant (they only come into play in expressions that contain 2+ conditions).
As Rik Wisselink speculated and Michelle Hirsch later confirmed, Matlab supports placing an expression immediately following an "if" statement, on the same line, without needing to separate the statements with a new line or even a comma (although this is suggested by the Editor's Mlint/Code-Analyzer). As Michelle mentioned, this is mainly to support backward-compatibility with old Matlab code, and is a discouraged programming practice. Over the years Matlab has made a gradual shift from being a very weakly-typed and loose-format language to a more strongly-typed one having stricter syntax. So I would not be surprised if one day in the future Matlab would prevent such same-line conditional statements, and force a new line or comma separator between the condition statement and the conditional branch statement.
Note that the "if" conditional branch never executes, and in fact it is optimized away by the interpreter. Therefore, it does not matter that the "or" function call would have errored, since it is never evaluated.

Variant #2: if (true) or (false)

In this variant, the "if" condition is always true, causing the top conditional branch to execute. This starts with a call to or(false), which throws a run-time error because the or() function expects 2 input arguments and only one is supplied (as Chris Luengo was the first to note). Therefore, execution jumps to the "catch" block and 'Doo!' is displayed in the Matlab console.
In a more verbose manner, this is the code (executed lines highlighted):

function test
    try
        if (true)
            or (false)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end

Variant #3: if (true) or (10< 9.9)

This is exactly the same as variant #2, since the condition 10< 9.9 is the same as false. The parentheses around the condition ensure that it is treated as a single logical expression (that evaluates to false) rather than being treated as 2 separate arguments. Since the or() function expects 2 input args, a run-time error will be thrown, resulting in a display of 'Doo!' in the Matlab console.
As Will correctly noted, this variant is simply a red herring whose aim was to lead up to the following variant:

Variant #4: if true or 10< 9.9

At first glance, this variant looks exactly the same as variant #3, because parentheses around conditions are not mandatory in Matlab. In fact, if a || b is equivalent to (and in many cases more readable/maintainable than) if (a) || (b). However, remember that "or" is not a logical operator but rather a function call (see variant #1 above). For this reason, the if true or 10< 9.9 statement is equivalent to the following:

        if true
            or 10< 9.9
            ...

Now, you might think that this will cause a run-time error just as before (variant #2), but take a closer look at the input to the or() function call: there are no parentheses and so the Matlab interpreter parses the rest of the line as space-separated command-line inputs to the or() function, which are parsed as strings. Therefore, the statement is in fact interpreted as follows:

        if true
            or('10<', '9.9')
            ...

This is a valid "or" statement that causes no run-time error, since the function receives 2 input arguments that happen to be 3-by-1 character arrays. 3 element-wise or are performed ('1'||'9' and so-on), based on the inputs' ASCII codes. So, the code is basically the same as:

        if true
            or([49,48,60], [57,46,57])  % =ASCII values of '10<','9.9'
            disp('Yaba');

Which results in the following output in the Matlab console:

ans =
  1×3 logical array
   1   1   1
Yaba

As Will noted, this variant was cunningly crafted so that the 2 input args to "or" would each have exactly the same number of chars, otherwise a run-time error would occur ("Matrix dimensions must agree", except for the edge case where one of the operands only has a single element). As Marshall noted, Matlab syntax highlighting (in the Matlab console or editor) can aid us understand the parsing, by highlighting the or() inputs in purple color, indicating strings.

Variant #5: if 10> 9.9 or 10< 9.9

This is another variant whose main aim is confusing the readers (sorry about that; well, not really...). This variant is exactly the same as variant #4, because (as noted above) Matlab conditions do not need to be enclosed by parentheses. But whereas 10> 9.9 is a single scalar condition (that evaluates to true), 10< 9.9 are in fact 2 separate 3-character string arguments to the "or" function. The end result is exactly the same as in variant #4.
I hope you enjoyed this little puzzle. Back to serious business in the next post!

USA visit

I will be travelling in the US (Boston, New York, Baltimore) in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.

The post Interesting Matlab puzzle – analysis appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis/feed 1
Interesting Matlab puzzle https://undocumentedmatlab.com/articles/interesting-matlab-puzzle?utm_source=rss&utm_medium=rss&utm_campaign=interesting-matlab-puzzle https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comments Sun, 31 Mar 2019 10:15:06 +0000 http://undocumentedmatlab.com/?p=8614 A simple Matlab puzzle that leads to interesting insight on Matlab's parser.

The post Interesting Matlab puzzle appeared first on Undocumented Matlab.

]]>
Here’s a nice little puzzle that came to me from long-time Matlab veteran Andrew Janke:
Without actually running the following code in Matlab, what do you expect its output to be? ‘Yaba’? ‘Daba’? perhaps ‘Doo!’? or maybe it won’t run at all because of a parsing error?

function test
    try
        if (false) or (true)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end

To muddy the waters a bit, do you think that short-circuit evaluation is at work here? or perhaps eager evaluation? or perhaps neither?
Would the results be different if we switched the order of the conditional operands, i.e. (true) or (false) instead of (false) or (true)? if so, how and why?
And does it matter if I used “false” or “10< 9.9” as the “or” conditional?
Are the parentheses around the conditions important? would the results be any different without these parentheses?
In other words, how and why would the results change for the following variants?

        if (false) or (true)     % variant #1
        if (true)  or (false)    % variant #2
        if (true)  or (10< 9.9)  % variant #3
        if  true   or  10< 9.9   % variant #4
        if 10> 9.9 or  10< 9.9   % variant #5

Please post your thoughts in a comment below (expected results and the reason, for the main code snippet above and its variants), and then run the code. You might be surprised at the results, but not less importantly at the reasons. This deceivingly innocuous code snippet leads to interesting insight on Matlab's parser.
Full marks will go to the first person who posts the correct results and reasoning/interpretation of the variants above (hint: it's not as trivial as it might look at first glance).
Addendum April 9, 2019: I have now posted my solution/analysis of this puzzle here.

USA visit

I will be travelling in the US (Boston, New York, Baltimore) in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.

The post Interesting Matlab puzzle appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/interesting-matlab-puzzle/feed 20
Undocumented plot marker types https://undocumentedmatlab.com/articles/undocumented-plot-marker-types?utm_source=rss&utm_medium=rss&utm_campaign=undocumented-plot-marker-types https://undocumentedmatlab.com/articles/undocumented-plot-marker-types#comments Wed, 13 Mar 2019 11:05:14 +0000 http://undocumentedmatlab.com/?p=8539 Undocumented plot marker styles can easily be accesses using a hidden plot-line property.

The post Undocumented plot marker types appeared first on Undocumented Matlab.

]]>
I wanted to take a break from my miniseries on the Matlab toolstrip to describe a nice little undocumented aspect of plot line markers. Plot line marker types have remained essentially unchanged in user-facing functionality for the past two+ decades, allowing the well-known marker types (.,+,o,^ etc.). Internally, lots of things changed in the graphics engine, particularly in the transition to HG2 in R2014b and the implementation of markers using OpenGL primitives. I suspect that during the massive amount of development work that was done at that time, important functionality improvements that were implemented in the engine were forgotten and did not percolate all the way up to the user-facing functions. I highlighted a few of these in the past, for example transparency and color gradient for plot lines and markers, or various aspects of contour plots.
Fortunately, Matlab usually exposes the internal objects that we can customize and which enable these extra features, in hidden properties of the top-level graphics handle. For example, the standard Matlab plot-line handle has a hidden property called MarkerHandle that we can access. This returns an internal object that enables marker transparency and color gradients. We can also use this object to set the marker style to a couple of formats that are not available in the top-level object:

>> x=1:10; y=10*x; hLine=plot(x,y,'o-'); box off; drawnow;
>> hLine.MarkerEdgeColor = 'r';
>> set(hLine, 'Marker')'  % top-level marker styles
ans =
  1×14 cell array
    {'+'} {'o'} {'*'} {'.'} {'x'} {'square'} {'diamond'} {'v'} {'^'} {'>'} {'<'} {'pentagram'} {'hexagram'} {'none'}
>> set(hLine.MarkerHandle, 'Style')'  % low-level marker styles
ans =
  1×16 cell array
    {'plus'} {'circle'} {'asterisk'} {'point'} {'x'} {'square'} {'diamond'} {'downtriangle'} {'triangle'} {'righttriangle'} {'lefttriangle'} {'pentagram'} {'hexagram'} {'vbar'} {'hbar'} {'none'}

We see that the top-level marker styles directly correspond to the low-level styles, except for the low-level ‘vbar’ and ‘hbar’ styles. Perhaps the developers forgot to add these two styles to the top-level object in the enormous upheaval of HG2. Luckily, we can set the hbar/vbar styles directly, using the line’s MarkerHandle property:

hLine.MarkerHandle.Style = 'hbar';
set(hLine.MarkerHandle, 'Style','hbar');  % alternative

hLine.MarkerHandle.Style='hbar'
hLine.MarkerHandle.Style='hbar'
hLine.MarkerHandle.Style='vbar'
hLine.MarkerHandle.Style='vbar'

USA visit

I will be travelling in the US in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.

The post Undocumented plot marker types appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/undocumented-plot-marker-types/feed 1
Matlab toolstrip – part 9 (popup figures) https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures?utm_source=rss&utm_medium=rss&utm_campaign=matlab-toolstrip-part-9-popup-figures https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures#comments Sun, 10 Feb 2019 17:00:10 +0000 http://undocumentedmatlab.com/?p=8402 Custom popup figures can be attached to Matlab GUI toolstrip controls.

The post Matlab toolstrip – part 9 (popup figures) appeared first on Undocumented Matlab.

]]>
In previous posts I showed how we can create custom Matlab app toolstrips using various controls. Today I will show how we can incorporate popup forms composed of Matlab figures into our Matlab toolstrip. These are similar in concept to drop-down and gallery selectors, in the sense that when we click the toolstrip button a custom popup is displayed. In the case of a popup form, this is a fully-customizable Matlab GUI figure.
Popup figure in Matlab toolstrip

Toolstrips can be a bit complex to develop so I’m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the Toolstrip miniseries before reading this post.
Also, remember to add the following code snippet at the beginning of your code so that the relevant toolstrip classes will be recognized by Matlab:

import matlab.ui.internal.toolstrip.*

Main steps and usage example

To attach a figure popup to a toolstrip control, follow these steps:

  1. Create a new figure, using GUIDE or the figure function. The figure should typically be created modal and non-visible, unless there’s a good reason to avoid this. Note that the figure needs to be a legacy (Java-based) figure, created with GUIDE or the figure function — web-based uifigure (created with AppDesigner or the uifigure function) is not [currently] supported.
  2. Create a callback function that opens and initializes this figure, and then moves it to the expected screen location using the following syntax: hToolGroup.showFigureDialog(hFig,hAnchor), where hFig is the figure’s handle, and hAnchor is the handle for the triggering toolstrip control.
  3. Attach the callback function to the triggering toolstrip control.

Here’s a simple usage example, in which I present a file-selector popup:

% Create a toolstrip section, column & push-button
hSection = hTab.addSection('Popup');
hColumn = hSection.addColumn();
hButton = Button('Open',Icon.OPEN_24);
hButton.ButtonPushedFcn = {@popupFigure,hButton};  % attach popup callback to the button
hColumn.add(hButton);
% Callback function invoked when the toolstrip button is clicked
function popupFigure(hAction, hEventData, hButton)
    % Create a new non-visible modal figure
    hFig = figure('MenuBar','none', 'ToolBar','none', 'WindowStyle','modal', ...
                  'Visible','off', 'NumberTitle','off', 'Name','Select file:');
    % Add interactive control(s) to the figure (in this case, a file chooser initialized to current folder)
    jFileChooser = handle(javaObjectEDT(javax.swing.JFileChooser(pwd)), 'CallbackProperties');
    [jhFileChooser, hComponent] = javacomponent(jFileChooser, [0,0,200,200], hFig);
    set(hComponent, 'Units','normalized', 'Position',[0,0,1,1]);  % resize component within containing figure
    % Set popup control's callback (in this case, display the selected file and close the popup)
    jhFileChooser.ActionPerformedCallback = @popupActionPerformedCallback;
    function popupActionPerformedCallback(jFileChooser, jEventData)
        fprintf('Selected file: %s\n', char(jFileChooser.getSelectedFile));
        delete(hFig);
    end
    % Display the popup figure onscreen, just beneath the triggering button
    showFigureDialog(hToolGroup,hFig,hButton);
    % Wait for the modal popup figure to close before resuming GUI interactivity
    waitfor(hFig);
end

This leads to the popup figure as shown in the screenshot above.
The popup figure initially appears directly beneath the triggering button. The figure can then be moved away from that position, by dragging its title bar or border frame.
Note how the popup is an independent heavy-weight figure window, having a border frame, title bar and a separate task-bar icon. Removing the border frame and title-bar of Matlab figures can be done using an undocumented visual illusion – this can make the popup less obtrusive, but also prevent its moving/resizing. An entirely different and probably better approach is to present a light-weight popup panel using the Toolpack framework, which I plan to discuss in the following post(s). The PopupPanel container that I discussed in another post cannot be used, because it is displayed as a sub-component of a Matlab figure, and in this case the popup is not attached to any figure (the toolstrip and ToolGroup are not Matlab figures, as explained here).
The astute reader may wonder why I bothered going to all the trouble of displaying a modal popup with a JFileChooser, when I could have simply used the built-in uigetfile or uiputfile functions in the button’s callback. The answer is that (a) this mechanism displays the popup directly beneath the triggering button using hToolGroup.showFigureDialog(), and also (b) enables complex popups (dialogs) that have no direct builtin Matlab function (for example, a file-selector with preview, or a multi-component input form).

Compatibility considerations for R2018a or older

In Matlab releases R2018a or older that do not have the hToolGroup.showFigureDialog() function, you can create it yourself in a separate showFigureDialog.m file, as follows:

function showFigureDialog(hToolGroup, hFig, hAnchor)
    %   showFigureDialog - Display a figure-based dialog below a toolstrip control.
    %
    %   Usage example:
    %       showFigureDialog(hToolGroup, hFig, hAnchor);
    %   where:
    %       "hToolGroup" must be a "matlab.ui.internal.desktop.ToolGroup" handle
    %       "hFig" must be a "figure" handle, not a "uifigure"
    %       "hAnchor" must be a "matlab.ui.internal.toolstrip.***" handle
    %hWarn = ctrlMsgUtils.SuspendWarnings('MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); %#ok
    hWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
    jf = get(hFig, 'JavaFrame');
    if isempty(jf)
        error('UI figure cannot be added to "ToolGroup". Use a regular figure instead.')
    else
        screen_size = get(0,'ScreenSize');
        old_pos = get(hFig,'OuterPosition');
        dpi_ratio = com.mathworks.util.ResolutionUtils.scaleSize(100)/100;
        jAnchor = hToolGroup.ToolstripSwingService.Registry.getWidgetById(hAnchor.getId());
        pt = javaMethodEDT('getLocationOnScreen',jAnchor); % pt is anchor top left
        pt.y = pt.y + jAnchor.getVisibleRect().height;     % pt is anchor bottom left
        new_x = pt.getX()/dpi_ratio-5;                           % figure outer left
        new_y = screen_size(end)-(pt.getY/dpi_ratio+old_pos(4)); % figure outer bottom
        hFig.OuterPosition = [new_x new_y old_pos(3) old_pos(4)];
        hFig.Visible = 'on';
    end
    warning(hWarn);
end

Under the hood of showFigureDialog()

How does showFigureDialog() know where to place the figure, directly beneath the triggering toolstrip anchor?
The answer is really quite simple, if you look at this method’s source-code in %matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/ToolGroup.m (around line 500, depending on the Matlab release).
The function first checks whether the input hFig handle belongs to a figure or uifigure, and issues an error message in case it’s a uifigures (only legacy figures are currently supported).
Then the function fetches the toolstrip control’s underlying Java control handle using the following code (slightly modified for clarity), as explained here:

jAnchor = hToolGroup.ToolstripSwingService.Registry.getWidgetById(hAnchor.getId());

Next, it uses the Java control’s getLocationOnScreen() to get the control’s onscreen position, accounting for monitor DPI variation that affects the X location.
The figure’s OuterPosition property is then set so that the figure’s top-left corner is exactly next to the control’s bottom-left corner.
Finally, the figure’s Visible property is set to ‘on’ to make the figure visible in its new position.
The popup figure’s location is recomputed by showFigureDialog() whenever the toolstrip control is clicked, so the popup figure is presented in the expected position even when you move or resize the tool-group window.

Toolstrip miniseries roadmap

The following post(s) will present the Toolpack framework. Non-figure (lightweight) popup toolpack panels can be created, which appear more polished/stylish than the popup figures that I presented today. The drawdown is that toolpack panels may be somewhat more complex to program than figures, and IMHO are more likely to change across Matlab releases. In addition to the benefit of popup toolpack panels, toolpack presents an alternative way for toolstrip creation and customization, enabling programmers to choose between using the toolstrip framework (that I discussed so far), and the new toolpack framework.
In a succeeding post, I’ll discuss toolstrip collapsibility, i.e. what happens when the user resizes the window, reducing the toolstrip width. Certain toolstrip controls will drop their labels, and toolstrip sections shrink into a drop-down. The priority of control/section collapsibility can be controlled, so that less-important controls will collapse before more-important ones.
In future posts, I plan to discuss docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures – not necessarily in this order.
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, please let me know.

The post Matlab toolstrip – part 9 (popup figures) appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures/feed 6
Matlab toolstrip – part 8 (galleries) https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries?utm_source=rss&utm_medium=rss&utm_campaign=matlab-toolstrip-part-8-galleries https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries#comments Sun, 03 Feb 2019 17:00:55 +0000 http://undocumentedmatlab.com/?p=8321 Matlab toolstrips can contain customizable gallery panels of items.

The post Matlab toolstrip – part 8 (galleries) appeared first on Undocumented Matlab.

]]>
In previous posts I showed how we can create custom Matlab app toolstrips using various controls (buttons, checkboxes, drop-downs, lists etc.). Today I will show how we can incorporate gallery panels into our Matlab toolstrip.
Toolstrip Gallery (in-line & drop-down)

Toolstrips can be a bit complex to develop so I’m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the Toolstrip miniseries before reading this post.

Also, remember to add the following code snippet at the beginning of your code so that the relevant toolstrip classes will be recognized by Matlab:

import matlab.ui.internal.toolstrip.*

Gallery sub-components

Toolstrip gallery popup components
Toolstrip gallery popup components
Toolstrip galleries are panels of buttons (typically large icons with an attached text label), which are grouped in “categories”. The gallery content can be presented either in-line within the toolstrip (a Gallery control), or as a drop-down button’s popup panel (a DropDownGalleryButton control). In either case, the displayed popup panel is a GalleryPopup object, that is composed of one or more GalleryCategory, each of which has one or more GalleryItem (push-button) and/or ToggleGalleryItem (toggle-button).

  • Gallery or DropDownGalleryButton
    • GalleryPopup
      • GalleryCategory
        • GalleryItem or ToggleGalleryItem
        • GalleryItem or ToggleGalleryItem
      • GalleryCategory


For a demonstration of toolstrip Galleries, see the code files in %matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/, specifically showcaseToolGroup.m and showcaseBuildTab_Gallery.m.

GalleryPopup

We first create the GalleryPopup object, then add to it a few GalleryCategory groups of GalleryItem, ToggleGalleryItem buttons. In the example below, we use a ButtonGroup to ensure that only a single ToggleGalleryItem button is selected:

import matlab.ui.internal.toolstrip.*
popup = GalleryPopup('ShowSelection',true);
% Create gallery categories
cat1 = GalleryCategory('CATEGORY #1 SINGLE'); popup.add(cat1);
cat2 = GalleryCategory('CATEGORY #2 SINGLE'); popup.add(cat2);
cat3 = GalleryCategory('CATEGORY #3 SINGLE'); popup.add(cat3);
% Create a button-group to control item selectability
group = matlab.ui.internal.toolstrip.ButtonGroup;
% Add items to the gallery categories
fpath = [fullfile(matlabroot,'toolbox','matlab','toolstrip','web','image') filesep];  % icons path
item1 = ToggleGalleryItem('Biology', Icon([fpath 'biology_app_24.png']), group);
item1.Description = 'Select the Biology gizmo';
item1.ItemPushedFcn = @(x,y) ItemPushedCallback(x,y);
cat1.add(item1);
item2 = ToggleGalleryItem('Code Generation', Icon([fpath 'code_gen_app_24.png']), group);
cat1.add(item2);
item3 = ToggleGalleryItem('Control', Icon([fpath 'control_app_24.png']), group);
cat1.add(item3);
item4 = ToggleGalleryItem('Database', Icon([fpath 'database_app_24.png']), group);
cat1.add(item4);
...

Single-selection GalleryPopup (icon view)
Single-selection GalleryPopup (icon view)

Note that in a real-world situation, we’d assign a Description, Tag and ItemPushedFcn to all gallery items. This was elided from the code snippet above for readability, but should be part of any actual GUI. The Description only appears as tooltip popup in icon-view (shown above), but appears as a visible label in list-view (see below).

Gallery items selection: push-button action, single-selection toggle, multiple selection toggle

If we use ToggleGalleryItem without a ButtonGroup, multiple gallery items can be selected, rather than just a single selection as shown above:

...
item1 = ToggleGalleryItem('Biology', Icon([fpath 'biology_app_24.png']));
item1.Description = 'Select the Biology gizmo';
item1.ItemPushedFcn = @(x,y) ItemPushedCallback(x,y);
cat1.add(item1);
item2 = ToggleGalleryItem('Code Generation', Icon([fpath 'code_gen_app_24.png']));
cat1.add(item2);
item3 = ToggleGalleryItem('Control', Icon([fpath 'control_app_24.png']));
cat1.add(item3);
item4 = ToggleGalleryItem('Database', Icon([fpath 'database_app_24.png']));
cat1.add(item4);
...

Multiple-selection GalleryPopup (icon view)
Multiple-selection GalleryPopup (icon view)

Alternatively, if we use GalleryItem instead of ToggleGalleryItem, the gallery items would be push-buttons rather than toggle-buttons. This enables us to present a gallery of single-action state-less push-buttons, rather than state-full toggle-buttons. The ability to customize the gallery items as either state-less push-buttons or single/multiple toggle-buttons supports a wide range of application use-cases.

Customizing the GalleryPopup

Properties that affect the GalleryPopup appearance are:

  • DisplayState – initial display mode of gallery items (string; default=’icon_view’, valid values: ‘icon_view’,’list_view’)
  • GalleryItemRowCount – number of rows used in the display of the in-line gallery (integer; default=1, valid values: 0,1,2). A Value of 2 should typically be used with a small icon and GalleryItemWidth (see below)
  • GalleryItemTextLineCount – number of rows used for display of the item label (integer; default=2, valid values: 0,1,2)
  • ShowSelection – whether or not to display the last-selected item (logical; default=false). Needs to be true for Gallery and false for DropDownGalleryButton.
  • GalleryItemWidth – number of pixels to allocate for each gallery item (integer, hidden; default=80)
  • FavoritesEnabled – whether or not to enable a “Favorites” category (logical, hidden; default=false)

All of these properties are defined as private in the GalleryPopup class, and can only be specified during the class object’s construction. For example, instead of the default icon-view, we can display the gallery items as a list, by setting the GalleryPopup‘s DisplayState property to 'list_view' during construction:

popup = GalleryPopup('DisplayState','list_view');

GalleryPopup (list view)
GalleryPopup (list view)

Switching from icon-view to list-view and back can also be done by clicking the corresponding icon near the popup’s top-right corner (next to the interactive search-box).

Now that we have prepared GalleryPopup, let’s integrate it in our toolstrip.
We have two choices — either in-line within the toolstrip section (using Gallery), or as a compact drop-down button (using DropDownGalleryButton):

% Inline gallery
section = hTab.addSection('Multiple Selection Gallery');
column = section.addColumn();
popup = GalleryPopup('ShowSelection',true);
% add the GalleryPopup creation code above
gallery = Gallery(popup, 'MinColumnCount',2, 'MaxColumnCount',4);
column.add(gallery);
% Drop-down gallery
section = hTab.addSection('Drop Down Gallery');
column = section.addColumn();
popup = GalleryPopup();
% add the GalleryPopup creation code above
button = DropDownGalleryButton(popup, 'Examples', Icon.MATLAB_24);
button.MinColumnCount = 5;
column.add(button);

Toolstrip Gallery (in-line & drop-down)

Clicking any of the drop-down (arrow) widgets will display the associated GalleryPopup.
The Gallery and DropDownGalleryButton objects have several useful settable properties:

  • Popup – a GalleryPopup object handle, which is displayed when the user clicks the drop-down (arrow) widget. Only settable in the constructor, not after object creation.
  • MinColumnCount – minimum number of item columns to display (integer; default=1). In Gallery, this property is only settable in the constructor, not after object creation; if not enough width is available to display these columns, the control collapses into a drop-down. In DropDownGalleryButton, this property can be set even after object creation (despite incorrect internal documentation), and controls the width of the popup panel.
  • MaxColumnCount – maximal number of items columns to display (integer; default=10). In Gallery, this property is only settable in the constructor, not after object creation. In DropDownGalleryButton, this property can be set even after object creation but in any case seems to have no visible effect.
  • Description – tooltip text displayed when the mouse hovers over the Gallery area (outside the area of the internal gallery items, which have their own individual Descriptions), or over the DropDownGalleryButton control.
  • TextOverlay – a semi-transparent text label overlaid on top of the gallery panel (string, default=”). Only available in Gallery, not DropDownGalleryButton.

For example:

gallery = Gallery(popup, 'MinColumnCount',2, 'MaxColumnCount',4);
gallery.TextOverlay = 'Select from these items';

Effect of TextOverlay
Effect of TextOverlay

Toolstrip miniseries roadmap

The next post will discuss popup forms. These are similar in concept to galleries, in the sense that when we click the drop-down widget a custom popup panel is displayed. In the case of a popup form, this is a fully-customizable Matlab GUI figure.
Following that, I plan to discuss toolstrip collapsibility, the Toolpack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures – not necessarily in this order.
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, please let me know.

The post Matlab toolstrip – part 8 (galleries) appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries/feed 5
Matlab toolstrip – part 7 (selection controls) https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls?utm_source=rss&utm_medium=rss&utm_campaign=matlab-toolstrip-part-7-selection-controls https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls#comments Sun, 27 Jan 2019 17:00:34 +0000 http://undocumentedmatlab.com/?p=8257 Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries.

The post Matlab toolstrip – part 7 (selection controls) appeared first on Undocumented Matlab.

]]>
In previous posts I showed how we can create custom Matlab app toolstrips using controls such as buttons, checkboxes, sliders and spinners. Today I will show how we can incorporate even more complex selection controls into our toolstrip: lists, drop-downs, popups etc.
Toolstrip SplitButton with dynamic popup and static sub-menu
Toolstrip SplitButton with dynamic popup and static sub-menu

Toolstrips can be a bit complex to develop so I’m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the Toolstrip miniseries before reading this post.

Also, remember to add the following code snippet at the beginning of your code so that the relevant toolstrip classes will be recognized by Matlab:

import matlab.ui.internal.toolstrip.*

There are 4 types of popups in toolstrip controls:

  1. Builtin dropdown (combo-box) selector similar to the familiar uicontrol(‘style’,’popup’,…). In toolstrips, this is implemented using the DropDown control.
  2. A more complex dropdown selector having icons and tooltips, implemented using the DropDownButton and SplitButton toolstrip controls.
  3. An even-more complex drop-down selector, which presents a gallery of options. This will be discussed in detail in the next post.
  4. A fully-customizable form panel (“popup form”). This will be discussed separately, in the following post.

The simple DropDown toolstrip control is very easy to set up and use:

hPopup = DropDown({'Label1';'Label2';'Label3'});
hPopup.Value = 'Label3';
hPopup.ValueChangedFcn = @ValueChangedCallback;

Toolstrip DropDown
Toolstrip DropDown
Note that the drop-down items (labels) need to be specified as a column cell-array (i.e. {a;b;c}) – a row cell-array ({a,b,c}) will result in run-time error.
We can have the control hold a different value for each of the displayed labels, by specifying the input items as an Nx2 cell-array:

items = {'One',   'Label1'; ...
         'Two',   'Label2'; ...
         'Three', 'Label3'}
hPopup = DropDown(items);
hPopup.Value = 'Two';
hPopup.ValueChangedFcn = @ValueChangedCallback;

This drop-down control will display the labels “Label1”, “Label2” (initially selected), and “Label3”. Whenever the selected drop-down item is changed, the corresponding popup Value will change to the corresponding value. For example, when “Label3” is selected in the drop-down, hPopup.Value will change to ‘Three’.
Another useful feature of the toolstrip DropDown control is the Editable property (logical true/false, default=false), which enables the user to modify the entry in the drop-down’s editbox. Any custom text entered within the editbox will update the control’s Value property to that string.

ListBox

We can create a ListBox in a very similarly manner to DropDown. For example, the following code snippet creates a list-box that spans the entire toolstrip column height and has 2 of its items initially selected:

hColumn = hSection.addColumn('Width',100);
allowMultiSelection = true;
items = {'One','Label1'; 'Two','Label2'; 'Three','Label3'; 'Four','Label4'; 'Five','Label5'};
hListBox = ListBox(items, allowMultiSelection);
hListBox.Value = {'One'; 'Three'};
hListBox.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hListBox);

Toolstrip ListBox (multi-selection)
Toolstrip ListBox (multi-selection)

The DropDown and ListBox controls are nearly identical in terms of their properties, methods and events/callbacks, with the following notable exceptions:

  • ListBox controls do not have an Editable property
  • ListBox controls have a MultiSelect property (logical, default=false), which DropDowns do not have. Note that this property can only be set during the ListBox‘s creation, as shown in the code snippet above.

DropDownButton and SplitButton

A more elaborate drop-down selector can be created using the DropDownButton and SplitButton toolstrip controls. For such controls, we create a PopupList object, and add elements to it, which could be any of the following, in whichever order that you wish:

  1. PopupListHeader – a section header (title), non-selectable
  2. ListItem – a selectable list item, with optional Icon, Text, and Description (tooltip string, which for some reason [probably a bug] is not actually shown). For some reason (perhaps a bug), the Description is not shown in a tooltip (no tooltip is displayed). However, it is displayed as a label beneath the list-item’s main label, unless we set ShowDescription to false.
  3. ListItemWithCheckBox – a selectable list item that toggles a checkmark icon based on the list item’s selection Value (on/off). The checkmark icon is not customizable (alas).
  4. ListItemWithPopup – a non-selectable list item, that displays a sub-menu (another PopupList that should be set to the parent list-item’s Popup property).

A simple usage example (adapted from the showcaseToolGroup demo):

Toolstrip PopupList
Toolstrip PopupList

function hPopup = createPopup()
    import matlab.ui.internal.toolstrip.*
    hPopup = PopupList();
    % list header #1
    header = PopupListHeader('List Items');
    hPopup.add(header);
    % list item #1
    item = ListItem('This is item 1', Icon.MATLAB_16);
    item.Description = 'this is the description for item #1';
    item.ShowDescription = true;
    item.ItemPushedFcn = @ActionPerformedCallback;
    hPopup.add(item);
    % list item #2
    item = ListItem('This is item 2', Icon.SIMULINK_16);
    item.Description = 'this is the description for item #2';
    item.ShowDescription = false;
    addlistener(item, 'ItemPushed', @ActionPerformedCallback);
    hPopup.add(item);
    % list header #2
    header = PopupListHeader('List Item with Checkboxes');
    hPopup.add(header);
    % list item with checkbox
    item = ListItemWithCheckBox('This is item 3', true);
    item.ValueChangedFcn = @PropertyChangedCallback;
    hPopup.add(item);
    % list item with popup
    item = ListItemWithPopup('This is item 4',Icon.ADD_16);
    item.ShowDescription = false;
    hPopup.add(item);
    % Sub-popup
    hSubPopup = PopupList();
    item.Popup = hSubPopup;
    % sub list item #1
    sub_item1 = ListItem('This is sub item 1', Icon.MATLAB_16);
    sub_item1.ShowDescription = false;
    sub_item1.ItemPushedFcn = @ActionPerformedCallback;
    hSubPopup.add(sub_item1);
    % sub list item #2
    sub_item2 = ListItem('This is sub item 2', Icon.SIMULINK_16);
    sub_item2.ShowDescription = false;
    sub_item2.ItemPushedFcn = @ActionPerformedCallback;
    hSubPopup.add(sub_item2);
end  % createPopup()

We now have two alternatives for attaching this popup to the DropDownButton or SplitButton:

Toolstrip SplitButton with dynamic popup and static sub-menu
Toolstrip SplitButton with dynamic popup and static sub-menu

  • Static popup – set the Popup property of the button or ListItemWithPopup to the popup-creation function (or hPopup). The popup will be created once and will remain unchanged throughout the program execution. For example:
    hButton = DropDownButton('Vertical', Icon.OPEN_24);
    hButton.Popup = createPopup();
    
  • Dynamic popup – set the DynamicPopupFcn of the button or ListItemWithPopup to the popup creation function. This function will be invoked separately whenever the user clicks on the drop-down selector widget. Inside our popup-creation function we can have state-dependent code that modifies the displayed list items depending on the state of our program/environment. For example:
    hButton = SplitButton('Vertical', Icon.OPEN_24);
    hButton.ButtonPushedFcn = @ActionPerformedCallback;  % invoked when user clicks the main split-button part
    hButton.DynamicPopupFcn = @(h,e) createPopup();      % invoked when user clicks the drop-down selector widget
    


DropDownButton and SplitButton are exactly the same as far as the popup-list is concerned: If it is set via the Popup property then the popup is static (in the sense that it is only evaluated once, when created), and if it is set via DynamicPopupFcn then the popup is dynamic (re-created before display). The only difference between DropDownButton and SplitButton is that in addition to the drop-down control, a SplitButton also includes a regular push-button control (with its corresponding ButtonPushedFcn callback).
In summary:

  • If DynamicPopupFcn is set to a function handle, then the PopupList that is returned by that function will be re-evaluated and displayed whenever the user clicks the main button of a DropDownButton or the down-arrow part of a SplitButton. This happens even if the Popup property is also set i.e., DynamicPopupFcn has precedence over Popup; when both of them are set, Popup is silently ignored (it would be useful for Matlab to display a warning in such cases, hopefully in a future release).
  • If DynamicPopupFcn is not set but Popup is (to a PopupList object handle), then this PopupList will be computed only once (when first created) and then it will be displayed whenever the user clicks the main button of a DropDownButton or the down-arrow part of a SplitButton.
  • Separately from the above, if a SplitButton‘s ButtonPushedFcn property is set to a function handle, then that function will be evaluated whenever the user clicks the main button of the SplitButton. No popup is presented, unless of course the callback function displays a popup programmatically. Note that ButtonPushedFcn is a property of SplitButton; this property does not exist in a DropDownButton.

Important note: whereas DropDown and ListBox have a ValueChangedFcn callback that is invoked whenever the drop-down/listbox Value has changed, the callback mechanism is very different with DropDownButton and SplitButton: here, each menu item has its own individual callback that is invoked when that item is selected (clicked): ItemPushedFcn for ListItem; ValueChangedFcn for ListItemWithCheckBox; and DynamicPopupFcn for ListItemWithPopup. As we shall see later, the same is true for gallery items – each item has its own separate callback.

Galleries

Toolstrip galleries are panels of buttons (typically large icons with an attached text label), which are grouped in “categories”.
The general idea is to first create the GalleryPopup object, then add to it a few GalleryCategory groups, each consisting of GalleryItem (push-buttons) and/or ToggleGalleryItem (toggle-buttons) objects. Once this GalleryPopup is created, we can either integrate it in-line within the toolstrip section (using Gallery), or as a compact drop-down button (using DropDownGalleryButton):

% Inline gallery
section = hTab.addSection('Multiple Selection Gallery');
column = section.addColumn();
popup = GalleryPopup('ShowSelection',true);
% add the GalleryPopup creation code (see next week's post)
gallery = Gallery(popup, 'MaxColumnCount',4, 'MinColumnCount',2);
column.add(gallery);
% Drop-down gallery
section = hTab.addSection('Drop Down Gallery');
column = section.addColumn();
popup = GalleryPopup();
% add the GalleryPopup creation code (see next week's post)
button = DropDownGalleryButton(popup, 'Examples', Icon.MATLAB_24);
button.MinColumnCount = 5;
column.add(button);

Toolstrip Gallery (in-line & drop-down)

I initially planned to include all the relevant Gallery discussion here, but it turned out to require so much space that I decided to devote a separate article for it — this will be the topic of next week’s blog post.

Toolstrip miniseries roadmap

The next post will discuss Galleries in depth, followed by popup forms.
Following that, I plan to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures – not necessarily in this order.
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, please let me know.

The post Matlab toolstrip – part 7 (selection controls) appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls/feed 7
Matlab toolstrip – part 6 (complex controls) https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls?utm_source=rss&utm_medium=rss&utm_campaign=matlab-toolstrip-part-6-complex-controls https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls#comments Mon, 21 Jan 2019 16:00:38 +0000 http://undocumentedmatlab.com/?p=8235 Multiple types of customizable controls can be added to Matlab toolstrips

The post Matlab toolstrip – part 6 (complex controls) appeared first on Undocumented Matlab.

]]>
In previous posts I showed how we can create custom Matlab app toolstrips using simple controls such as buttons and checkboxes. Today I will show how we can incorporate more complex controls into our toolstrip: button groups, edit-boxes, spinners, sliders etc.
Some custom Toolstrip Controls

Toolstrips can be a bit complex to develop so I’m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the Toolstrip miniseries before reading this post.

The first place to search for potential toostrip components/controls is in Matlab’s built-in toolstrip demos. The showcaseToolGroup demo displays a large selection of generic components grouped by function. These controls’ callbacks do little less than simply output a text message in the Matlab console. On the other hand, the showcaseMPCDesigner demo shows a working demo with controls that interact with some docked figures and their plot axes. The combination of these demos should provide plenty of ideas for your own toolstrip implementation. Their m-file source code is available in the %matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/ folder. To see the available toolstrip controls in action and how they could be integrated, refer to the source-code of these two demos.
All toolstrip controls are defined by classes in the %matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+toolstrip/ folder and use the matlab.ui.internal.toolstrip package prefix, for example:

% Alternative 1:
hButton = matlab.ui.internal.toolstrip.Button;
% Alternative 2:
import matlab.ui.internal.toolstrip.*
hButton = Button;

For the remainder of today’s post it is assumed that you are using one of these two alternatives whenever you access any of the toolstrip classes.

Top-level toolstrip controls

Control Description Important properties Callbacks Events
EmptyControl Placeholder (filler) in container column (none) (none) (none)
Label Simple text label (no action) Icon, Text (string) (none) (none)
Button Push-button Icon, Text (string) ButtonPushedFcn ButtonPushed
ToggleButton Toggle (on/off) button Icon, Text (string), Value (logical true/false), ButtonGroup (a ButtonGroup object) ValueChangedFcn ValueChanged
RadioButton Radio-button (on/off) Text (string), Value (logical true/false), ButtonGroup (a ButtonGroup object) ValueChangedFcn ValueChanged
CheckBox Check-box (on/off) Text (string), Value (logical true/false) ValueChangedFcn ValueChanged
EditField Single-line editbox Value (string) ValueChangedFcn ValueChanged, FocusGained, FocusLost
TextArea Multi-line editbox Value (string) ValueChangedFcn ValueChanged, FocusGained, FocusLost
Spinner A numerical spinner control of values between min,max Limits ([min,max]), StepSize (integer), NumberFormat (‘integer’ or ‘double’), DecimalFormat (string), Value (numeric) ValueChangedFcn ValueChanged, ValueChanging
Slider A horizontal slider of values between min,max Limits ([min,max]), Labels (cell-array), Ticks (integer), UseSmallFont (logical true/false, R2018b onward), ShowButton (logical true/false, undocumented), Steps (integer, undocumented), Value (numeric) ValueChangedFcn ValueChanged, ValueChanging
ListBox List-box selector with multiple items Items (cell-array), SelectedIndex (integer), MultiSelect (logical true/false), Value (cell-array of strings) ValueChangedFcn ValueChanged
DropDown Single-selection drop-down (combo-box) selector Items (cell-array), SelectedIndex (integer), Editable (logical true/false), Value (string) ValueChangedFcn ValueChanged
DropDownButton Button that has an associated drop-down selector Icon, Text (string), Popup (a PopupList object) DynamicPopupFcn (none)
SplitButton Split button: main clickable part next to a drop-down selector Icon, Text (string), Popup (a PopupList object) ButtonPushedFcn, DynamicPopupFcn ButtonPushed, DropDownPerformed (undocumented)
Gallery A gallery of selectable options, displayed in-panel MinColumnCount (integer), MaxColumnCount (integer), Popup (a GalleryPopup object), TextOverlay (string) (none) (none)
DropDownGalleryButton A gallery of selectable options, displayed as a drop-down MinColumnCount (integer), MaxColumnCount (integer), Popup (a GalleryPopup object), TextOverlay (string) (none) (none)

In addition to the control properties listed in the table above, all toolstrip controls share some common properties:

  • Description – a string that is shown in a tooltip when you hover the mouse over the control
  • Enabled – a logical value (default: true) that controls whether we can interact with the control. A disabled control is typically grayed-over. Note that the value is a logical true/false, not ‘on’/’off’
  • Tag – a string that can be used to uniquely identify/locate the control via their container’s find(tag) and findAll(tag) methods. Can contain spaces and special symbols – does not need to be a valid Matlab identifier
  • Children – contains a list of sub-component (if any); useful with complex controls
  • Parent – the handle of the container that contains the control
  • Type – the type of control, typically its class-name
  • Mnemonic – an undocumented string property, currently unused (?)
  • Shortcut – an undocumented string property, currently unused (?)

The EmptyControl, Button, ToggleButton and CheckBox controls were discussed in an earlier post of this miniseries. The bottom 6 selection controls (ListBox, DropDown, DropDownButton, SplitButton, Gallery and DropDownGalleryButton) will be discussed in the next post. The rest of the controls are described below.

Button groups

A ButtonGroup binds several CheckBox and ToggleButton components such that only one of them is selected (pressed) at any point in time. For example:

hSection = hTab.addSection('Radio-buttons');
hColumn = hSection.addColumn();
% Grouped RadioButton controls
hButtonGroup = ButtonGroup;
hRadio = RadioButton(hButtonGroup, 'Option choice #1');
hRadio.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hRadio);
hRadio = RadioButton(hButtonGroup, 'Option choice #2');
hRadio.ValueChangedFcn = @ValueChangedCallback;
hRadio.Value = true;
hColumn.add(hRadio);

Toolstrip ButtonGroup
Toolstrip ButtonGroup
Note that unlike the uibuttongroup object in “standard” figure GUI, the toolstrip’s ButtonGroup object does not have a SelectionChangedFcn callback property (or corresponding event). Instead, we need to set the ValueChangedFcn callback property (or listen to the ValueChanged event) separately for each individual control. This is really a shame – I think it would make good design sense to have a SelectionChangedFcn callback at the ButtonGroup level, as we do for uibuttongroup (in addition to the individual control callbacks).
Also note that the internal documentation of ButtonGroup has an error – it provides an example usage with RadioButton that has its constructor inputs switched: the correct constructor is RadioButton(hButtonGroup,labelStr). On the other hand, for ToggleButton, the hButtonGroup input is the [optional] 3rd input arg of the constructor: ToggleButton(labelStr,Icon,hButtonGroup). I think that it would make much more sense for the RadioButton constructor to follow the documentation and the style of ToggleButton and make the hButtonGroup input the last (2nd, optional) input arg, rather than the 1st. In other words, it would make more sense for RadioButton(labelStr,hButtonGroup), but unfortunately this is currently not the case.

Label, EditField and TextArea

A Label control is a simple non-clickable text label with an optional Icon, whose text is controlled via the Text property. The label’s alignment is controlled by the containing column’s HorizontalAlignment property.
An EditField is a single-line edit-box. Its string contents can be fetched/updated via the Value property, and when the user updates the edit-box contents the ValueChangedFcn callback is invoked (upon each modification of the string, i.e. every key-click). This is a pretty simple control actually.
The EditField control has a hidden (undocumentented) settable property called PlaceholderText, which presumably aught to display a gray initial prompt within the editbox. However, as far as I could see this property has no effect (perhaps, as the name implies, it is a place-holder for a future functionality…).
A TextArea is another edit-box control, but enables entering multiple lines of text, unlike EditField which is a single-line edit-box. TextArea too is a very simple control, having a settable Value string property and a ValueChangedFcn callback. Whereas EditField controls, being single-line, would typically be included in 2- or 3-element toolstrip columns, the TextArea would typically be placed in a single-element column, so that it would span the entire column height.
A peculiarity of toolstrip columns is that unless you specify their Width property, the internal controls are displayed with a minimal width (the width is only controllable at the column level, not the control-level). This is especially important with EditField and TextArea controls, which are often empty by default, causing their assigned width to be minimal (only a few pixels). This is corrected by setting their containing column’s Width:

% EditField controls
column1 = hSection.addColumn('HorizontalAlignment','right');
column1.add(Label('Yaba:'))
column1.add(Label('Daba doo:'))
column2 = hSection.addColumn('Width',70);
column2.add(EditField);
column2.add(EditField('Initial text'));
% TextArea control
column3 = hSection.addColumn('Width',90);
hEdit = TextArea;
hEdit.ValueChangedFcn = @ValueChangedCallback;
column3.add(hEdit);

Toolstrip Label, EditField and TextArea
Toolstrip Label, EditField and TextArea

Spinner

Spinner is a single-line numeric editbox that has an attached side-widget where you can increase/decrease the editbox value by a specified amount, subject to predefined min/max values. If you try to enter an illegal value, Matlab will beep and the editbox will revert to its last acceptable value. You can only specify a NumberFormat of ‘integer’ or ‘double’ (default: ‘integer’) and a DecimalFormat which is a string composed of the number of sub-decimal digits to display and the format (‘e’ or ‘f’). For example, DecimalFormat=’4f’ will display 4 digits after the decimal in floating-point format (‘e’ means engineering format). Here is a short usage example (notice the different ways that we can set the callbacks):

hColumn = hSection.addColumn('Width',100);
% Integer spinner (-100 : 10 : 100)
hSpinner = Spinner([-100 100], 0);  % [min,max], initialValue
hSpinner.Description = 'this is a tooltip description';
hSpinner.StepSize = 10;
hSpinner.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hSpinner);
% Floating-point spinner (-10 : 0.0001 : 10)
hSpinner = Spinner([-10 10], pi);  % [min,max], initialValue
hSpinner.NumberFormat = 'double';
hSpinner.DecimalFormat = '4f';
hSpinner.StepSize = 1e-4;
addlistener(hSpinner,'ValueChanged', @ValueChangedCallback);
addlistener(hSpinner,'ValueChanging',@ValueChangingCallback);
hColumn.add(hSpinner);

Toolstrip Spinner
Toolstrip Spinner
A logical extension of the toolstrip spinner implementation would be for non-numeric spinners, as well as custom Value display formatting. Perhaps this will become available at some future Matlab release.

Slider

Slider is a horizontal ruler on which you can move a knob from the left (min Value) to the right (max Value). The ticks and labels are optional and customizable. Here is a simple example showing a plain slider (values between 0-100, initial value 70, ticks every 5, labels every 20, step size 1), followed by a custom slider (notice again the different ways that we can set the callbacks):

hColumn = hSection.addColumn('Width',200);
hSlider = Slider([0 100], 70);  % [min,max], initialValue
hSlider.Description = 'this is a tooltip';
tickVals = 0 : 20 : 100;
hSlider.Labels = [compose('%d',tickVals); num2cell(tickVals)]';  % {'0',0; '20',20; ...}
hSlider.Ticks = 21;  % =numel(0:5:100)
hSlider.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hSlider);
hSlider = Slider([0 100], 40);  % [min,max], initialValue
hSlider.Labels = {'Stop' 0; 'Slow' 20; 'Fast' 50; 'Too fast' 75; 'Crash!' 100};
try hSlider.UseSmallFont = true; catch, end  % UseSmallFont was only added in R2018b
hSlider.Ticks = 11;  % =numel(0:10:100)
addlistener(hSlider,'ValueChanged', @ValueChangedCallback);
addlistener(hSlider,'ValueChanging',@ValueChangingCallback);
hColumn.add(hSlider);

Toolstrip Slider
Toolstrip Slider

Toolstrip miniseries roadmap

The next post will discuss complex selection components, including listbox, drop-down, split-button, and gallery.
Following that, I plan to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures – not necessarily in this order.
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, please let me know.

The post Matlab toolstrip – part 6 (complex controls) appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls/feed 4
Matlab toolstrip – part 5 (icons) https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons?utm_source=rss&utm_medium=rss&utm_campaign=matlab-toolstrip-part-5-icons https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons#comments Sun, 06 Jan 2019 17:00:37 +0000 http://undocumentedmatlab.com/?p=8188 Icons can be specified in various ways for toolstrip controls and the app window itself.

The post Matlab toolstrip – part 5 (icons) appeared first on Undocumented Matlab.

]]>
In a previous post I showed how we can create custom Matlab app toolstrips. Toolstrips can be a bit complex to develop so I’m trying to proceed slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the Toolstrip miniseries before reading this post. Today’s post describes how we can set various icons, based on the toolstrip created in the previous posts:
Toolstrip example (basic controls)
Toolstrip example (basic controls)

Component icons

Many toolstrip controls (such as buttons, but not checkboxes for example) have a settable Icon property. The standard practice is to use a 16×16 icon for a component within a multi-component toolstrip column (i.e., when 2 or 3 components are displayed on top of each other), and a 24×24 icon for a component that spans the entire column height (i.e., when the column contains only a single component).
We can use one of the following methods to specify the icon. Note that you need to import matlab.ui.internal.toolstrip.* if you wish to use the Icon class without the preceding package name.

  • The Icon property value is typically empty ([]) by default, meaning that no icon is displayed.
     
  • We can use one of ~150 standard icons using the format Icon.<icon-name>. For example: icon = Icon.REFRESH_24. These icons typically come in 2 sizes: 16×16 pixels (e.g. Icon.REFRESH_16) that we can use with the small-size components (which are displayed when the column has 2-3 controls), and 24×24 pixels (e.g. REFRESH_24) that we can use with the large-size components (which are displayed when the column contains only a single control). You can see the list of the standard icons by running
    matlab.ui.internal.toolstrip.Icon.showStandardIcons

    Standard toolstrip control Icons
  • We can use the Icon constructor by specifying the full filepath for any PNG or JPG image file. Note that other file type (such as GIF) are not supported by this method. For example:
    icon = Icon(fullfile(matlabroot,'toolbox','matlab','icons','tool_colorbar.png')); % PNG/JPG image file (not GIF!)

    In fact, the ~150 standard icons above use this mechanism under the hood: Icon.REFRESH_24 is basically a public static method of the Icon class, which simply calls Icon('REFRESH_24','Refresh_24') (note the undocumented use of a 2-input Icon constructor). This method in turn uses the Refresh_24.png file in Matlab’s standard toolstrip resources folder: %matlabroot%/toolbox/shared/controllib/general/resources/toolstrip_icons/Refresh_24.png.

  • We can also use the Icon constructor by specifying a PNG or JPG file contained within a JAR file, using the standard jar:file:...jar!/ notation. There are numerous icons included in Matlab’s JAR files – simply open these files in WinZip or WinRar and browse. In addition, you can include images included in any external JAR file. For example:
    icon = Icon(['jar:file:/' matlabroot '/java/jar/mlwidgets.jar!/com/mathworks/mlwidgets/actionbrowser/resources/uparrow.png']);
  • We can also use the Icon constructor by specifying a Java javax.swing.ImageIcon object. Fortunately we can create such objects from a variety of image formats (including GIFs). For example:
    iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','boardicon.gif');
    jIcon = javax.swing.ImageIcon(iconFilename);  % Java ImageIcon from file (inc. GIF)
    icon = Icon(jIcon);
    

    If we need to resize the Java image (for example, from 16×16 to 24×24 or vise versa), we can use the following method:

    % Resize icon to 24x24 pixels
    jIcon = javax.swing.ImageIcon(iconFilename);  % get Java ImageIcon from file (inc. GIF)
    jIcon = javax.swing.ImageIcon(jIcon.getImage.getScaledInstance(24,24,jIcon.getImage.SCALE_SMOOTH))  % resize to 24x24
    icon = Icon(jIcon);
    
  • We can apparently also use a CSS class-name to load images. This is only relevant for the JavaScript-based uifigures, not legacy Java-based figures that I discussed so far. Perhaps I will explore this in some later post that will discuss toolstrip integration in uifigures.

App window icon

The app window’s icon can also be set. By default, the window uses the standard Matlab membrane icon (%matlabroot%/toolbox/matlab/icons/matlabicon.gif). This can be modified using the hToolGroup.setIcon method, which currently [R2018b] expects a Java ImageIcon object as input. For example:

iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','reficon.gif');
jIcon = javax.swing.ImageIcon(iconFilename);
hToolGroup.setIcon(jIcon)

This icon should be set before the toolgroup window is shown (hToolGroup.open).

Custom app window icon
Custom app window icon

An odd caveat here is that the icon size needs to be 16×16 – setting a larger icon results in the icon being ignored and the default Matlab membrane icon used. For example, if we try to set ‘boardicon.gif’ (16×17) instead of ‘reficon.gif’ (16×16) we’d get the default icon instead. If our icon is too large, we can resize it to 16×16, as shown above:

% Resize icon to 16x16 pixels
jIcon = javax.swing.ImageIcon(iconFilename);  % get Java ImageIcon from file (inc. GIF)
jIcon = javax.swing.ImageIcon(jIcon.getImage.getScaledInstance(16,16,jIcon.getImage.SCALE_SMOOTH))  % resize to 16x16
hToolGroup.setIcon(jIcon)

It’s natural to expect that hToolGroup, which is a pure-Matlab MCOS wrapper class, would have an Icon property that accepts Icon objects, just like for controls as described above. For some reason, this is not the case. It’s very easy to fix it though – after all, the Icon class is little more than an MCOS wrapper class for the underlying Java ImageIcon (not exactly, but close enough). Adapting ToolGroup‘s code to accept an Icon is quite easy, and I hope that MathWorks will indeed implement this in a near-term future release. I also hope that MathWorks will remove the 16×16 limitation, or automatically resize icons to 16×16, or at the very least issue a console warning when a larger icon is specified by the user. Until then, we can use the setIcon(jImageIcon) method and take care to send it the 16×16 ImageIcon object that it expects.

Toolstrip miniseries roadmap

The next post will discuss complex components, including button-group, drop-down, listbox, split-button, slider, popup form, gallery etc.
Following that, my plan is to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures – not necessarily in this order. Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, please let me know.

The post Matlab toolstrip – part 5 (icons) appeared first on Undocumented Matlab.

]]>
https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons/feed 2