<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Sun, 09 Mar 2025 15:39:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Speeding-up builtin Matlab functions – part 3</title>
		<link>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=speeding-up-builtin-matlab-functions-part-3</link>
					<comments>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 06 Apr 2020 20:44:07 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Toolbox]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=11059</guid>

					<description><![CDATA[<p>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example.  </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3">Speeding-up builtin Matlab functions – part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>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 (<a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" target="_blank">example1</a>, <a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" target="_blank">example2</a>, <a href="https://undocumentedmatlab.com/articles/tag/performance" target="_blank">many others</a>). </p>
<p>Today I will show another example, this time speeding up the <i><b>mvksdensity</b></i> (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&#215;1024 data mesh. </p>
<p>The builtin <i><b>mvksdensity</b></i> function took <b>76 seconds</b> to run on my machine; I got this down to <b>13 seconds</b>, a <b>6x speedup</b>, without compromising accuracy. Here&#8217;s how I did this:</p>
<h3 id="preparation">Preparing the work files</h3>
<p>While we could in theory modify Matlab&#8217;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.</p>
<p>To see where the builtin files are located, we can use the <b><i>which</i></b> function:</p>
<pre lang="matlab">
>> which('mvksdensity')
C:\Program Files\Matlab\R2020a\toolbox\stats\stats\mvksdensity.m
</pre>
<p>In our case, we copy <i>\toolbox\stats\stats\mvksdensity.m</i> as <i>mvksdensity_.m</i> to our work folder, replace the function name at the top of the file from <code>mvksdensity</code> to <code>mvksdensity_</code>, and modify our code to call <i><b>mvksdensity_</b></i> rather than <i><b>mvksdensity</b></i>. </p>
<p>If we run our code, we get an error telling us that Matlab can&#8217;t find the <i><b>statkscompute</b></i> function (in line #107 of our <i>mvksdensity_.m</i>). So we find <i>statkscompute.m</i> in the <i>\toolbox\stats\stats\private\</i> folder, copy it as <i>statkscompute_.m</i> to our work folder, rename its function name (at the top of the file) to <code>statkscompute_</code>, and modify our <i>mvksdensity_.m</i> to call <i><b>statkscompute_</b></i> rather than <i><b>statkscompute</b></i>:</p>
<pre lang="matlab">[fout,xout,u] = statkscompute_(ftype,xi,xispecified,npoints,u,L,U,weight,cutoff,...</pre>
<p>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 <i>mvksdensity.m</i> and <i>statkscompute.m</i>, we also need to copy <i>statkskernelinfo.m</i>. </p>
<p>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.</p>
<p>Now that we have copied these 3 files, in practice all our attentions will be focused on the <i>dokernel</i> sub-function inside <i>statkscompute_.m</i>, since the profiling report (below) indicates that this is where all of the run-time is spent.</p>
<h3 id="identify">Identifying the hotspots</h3>
<p>Now we run the code through the Matlab Profiler, using the &#8220;Run and Time&#8221; button in the Matlab Editor, or <i><b>profile on/report</b></i> in the Matlab console (Command Window). The results show that 99.8% of <i><b>mvksdensity</b></i>&#8216;s time was spent in the internal <i>dokernel</i> function, 75% of which was spent in self-time (meaning code lines within <i>dokernel</i>):<br />
<center><figure style="width: 640px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/mvksdensity-profile1.png" alt="Initial profiling results - pretty slow..." title="Initial profiling results - pretty slow..." width="640" height="280" /><figcaption class="wp-caption-text">Initial profiling results - pretty slow...</figcaption></figure></center></p>
<p>Let&#8217;s drill into <i>dokernel</i> and see where the problems are:<br />
<center><figure style="width: 764px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/mvksdensity-profile2.png" alt="Initial dokernel profiling results" title="Initial dokernel profiling results" width="764" height="464" /><figcaption class="wp-caption-text">Initial dokernel profiling results</figcaption></figure></center></p>
<h3 id="normal">Evaluating the normal kernel distribution</h3>
<p>We can immediately see from the profiling results that a single line (#386) in <i>statkscompute_.m</i> is responsible for nearly 40% of the total run-time:</p>
<pre lang="matlab">fk = feval(kernel,z);</pre>
<p>In this case, <code>kernel</code> is a function handle to the normal-distribution function in <i>\stats\private\statkskernelinfo&gt;normal</i>, which is evaluated 1,488,094 times. Using <i><b>feval</b></i> incurs an overhead, as can be seen by the difference in run-times: line #386 takes 29.55 secs, whereas the <b><i>normal</i></b> function evaluations only take 18.53 secs. In fact, if you drill into the <b><i>normal</i></b> function in the profiling report, you&#8217;ll see that the actual code line that computes the normal distribution only takes 8-9 seconds &#8211; all the rest (~20 secs, or ~30% of the total) is totally redundant function-call overhead. Let&#8217;s try to remove this overhead by calling the <code>kernel</code> function directly:</p>
<pre lang="matlab">fk = kernel(z);</pre>
<p>Now that we have a local copy of <i>statkscompute_.m</i>, we can safely modify the <i>dokernel</i> sub-function, specifically line #386 as explained above. It turns out that just bypassing the <i><b>feval</b></i> 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&#8217;s a side-issue). </p>
<p>We now recognize that the program only evaluates the normal-distribution kernel, which is the default kernel. So let&#8217;s handle this special case by inlining the kernel&#8217;s one-line code (from <i>statkskernelinfo_.m</i>) directly (note how we move the condition outside of the loop, so that it doesn&#8217;t get recomputed 1 million times):</p>
<pre lang="matlab" highlight="2,31-32,34">
...
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 &#038; 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
...
</pre>
<p>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 <b>45-55</b> seconds (expect some fluctuations from run to run). Not a bad start.</p>
<h3 id="loop-bottom">Main loop &#8211; bottom part</h3>
<p>Now let&#8217;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:</p>
<p><center><figure style="width: 550px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/mvksdensity-profile3.png" alt="Profiling results for bottom part of the main loop" title="Profiling results for bottom part of the main loop" width="550" height="348" /><figcaption class="wp-caption-text">Profiling results for bottom part of the main loop</figcaption></figure></center></p>
<p>The first thing we note is that there&#8217;s an inner loop that runs d=2 times (d is set in line #127 of <i>mvksdensity_.m</i> &#8211; it is the input mesh&#8217;s dimensionality, and also the number of columns in the <code>txi</code> 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. </p>
<p>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:</p>
<pre lang="matlab" highlight="3-8,12-16,34-37,39,45-50">
...
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
...
</pre>
<p>This brings the run-time down to <b>31-32 secs</b>. Not bad at all, but we can still do much better:</p>
<h3 id="loop-top">Main loop &#8211; top part</h3>
<p>Now let&#8217;s take a look at the profiling report&#8217;s top part of the main loop:</p>
<p><center><figure style="width: 550px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/mvksdensity-profile4.png" alt="Profiling results for top part of the main loop" title="Profiling results for to part of the main loop" width="550" height="414" /><figcaption class="wp-caption-text">Profiling results for top part of the main loop</figcaption></figure></center></p>
<p>Again we note is that there&#8217;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 <code>true(n,1)</code> vector, which can easily be hoisted outside the loop:</p>
<pre lang="matlab" highlight="2-3,5-13,30">
...
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) &#038; 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 &#038; 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)
        ...
</pre>
<p>This brings the run-time down to <b>24 seconds</b>. </p>
<p>We next note that instead of using numeric indexes to compute the <code>nearby</code> vector, we could use faster logical indexes:</p>
<pre lang="matlab" highlight="2,9,26,28,31">
...
%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) &#038; 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 &#038; 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)
        ...
</pre>
<p>This brings the run-time down to <b>20 seconds</b>. </p>
<p>We now note that the main loop runs m=1,048,576 (=1024&#215;1024) times over all rows of <code>txi</code>. This is expected, since the loop runs over all the elements of a 1024&#215;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 <code>txi</code>. Therefore, instead of computing the &#8220;closeness&#8221; metric (which leads to the <code>nearby</code> vector) for all 1,048,576 x 2 values of <code>txi</code>, 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:</p>
<pre lang="matlab" highlight="3-10,13-15">
...
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) &#038; currentIdx2(:,idx2);
    else
        ...
</pre>
<p>This brings the run-time down to <b>13 seconds</b>, a total speedup of almost ~6x compared to the original version. Not bad at all.</p>
<p>For reference, here's a profiling summary of the <i>dokernel</i> function again, showing the updated performance hotspots:</p>
<p><center><figure style="width: 550px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/mvksdensity-profile5.png" alt="Profiling results after optimization" title="Profiling results after optimization" width="550" height="201" /><figcaption class="wp-caption-text">Profiling results after optimization</figcaption></figure></center></p>
<p>The 2 vectorized code lines in the bottom part of the main loop now account for 72% of the remaining run-time:</p>
<pre lang="matlab" highlight="4-5">
    ...
    if ~isempty(nearby)
        if isSpecialCase1
            z = txi(i,:) - ty(nearby,:);
            ftemp = exp((z.*z) * expFactor);
        else
            ...
</pre>
<p>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...</p>
<h3 id="resolution">Data density/resolution</h3>
<p>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.</p>
<p>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 <b>~3.5 seconds</b>, 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. </p>
<p>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.</p>
<h3 id="conclusions">Conclusions</h3>
<p>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.</p>
<p>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 <b><a href="https://undocumentedmatlab.com/books/matlab-performance" target="_blank">Accelerating Matlab Performance</a></b>.</p>
<p><a href="https://undocumentedmatlab.com/consulting" target="_blank">Let me know</a> 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.</p>
<p>In the meantime, Happy Easter/Passover everyone, and stay healthy!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3">Speeding-up builtin Matlab functions – part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-3/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Improving graphics interactivity</title>
		<link>https://undocumentedmatlab.com/articles/improving-graphics-interactivity?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=improving-graphics-interactivity</link>
					<comments>https://undocumentedmatlab.com/articles/improving-graphics-interactivity#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 21 Apr 2019 21:03:10 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8723</guid>

					<description><![CDATA[<p>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab release R2018b added the concept of <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">axes-specific toolbars</a> and default <a href="https://www.mathworks.com/help/matlab/creating_plots/control-axes-interactions.html" rel="nofollow" target="_blank">axes mouse interactivity</a>. <span class="alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/speedometer4d_200x200.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="200" height="200" /></span> Plain 2D plot axes have the following default interactions enabled by default: <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.paninteraction.html" rel="nofollow" target="_blank">PanInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.zoominteraction.html" rel="nofollow" target="_blank">ZoomInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.datatipinteraction.html" rel="nofollow" target="_blank">DataTipInteraction</a> and <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.rulerpaninteraction.html" rel="nofollow" target="_blank">RulerPanInteraction</a>.</p>
<p>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:</p>
<ol>
<li><b>Performance</b> &#8211; Matlab&#8217;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 &#8211; it includes a <code>Linger</code> 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.</li>
<li><b>Usability</b> &#8211; In my experience, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.regionzoominteraction.html" rel="nofollow" target="_blank">RegionZoomInteraction</a> (which enables defining a region zoom-box via click-&#038;-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.</li>
</ol>
<p>For these reasons, I typically use the following function whenever I create new axes, to replace the default sluggish DataTipInteraction and PanInteraction with RegionZoomInteraction:<br />
<span id="more-10306"></span></p>
<pre lang="matlab">
function axDefaultCreateFcn(hAxes, ~)
    try
        hAxes.Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
        hAxes.Toolbar = [];
    catch
        % ignore - old Matlab release
    end
end
</pre>
<p>The purpose of these two axes property changes shall become apparent below.<br />
This function can either be called directly (<code>axDefaultCreateFcn(hAxes</code>), or as part of the containing figure&#8217;s creation script to ensure than any axes created in this figure has this fix applied:</p>
<pre lang="matlab">
set(hFig,'defaultAxesCreateFcn',@axDefaultCreateFcn);
</pre>
<h3 id="testing">Test setup</h3>
<p><figure style="width: 268px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Axes_Interactivity.png" alt="Figure with default axes toolbar and interactivity" title="Figure with default axes toolbar and interactivity" width="268" height="200" /><figcaption class="wp-caption-text">Figure with default axes toolbar and interactivity</figcaption></figure> To test the changes, let&#8217;s prepare a figure with 10 tabs, with 10 overlapping panels and a single axes in each tab:</p>
<pre lang="matlab">
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
</pre>
<p style="padding-left: 20px; margin-top: -15px;"><i><font size=-1>p.s. &#8211; there&#8217;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.</font></i></p>
<p>Now let&#8217;s create a run-time test script that simulates 2000 mouse movements using <a href="https://undocumentedmatlab.com/articles/gui-automation-robot" target="_blank">java.awt.Robot</a>:</p>
<pre lang="matlab">
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
</pre>
<p>This takes ~45 seconds to run on my laptop: ~23ms per mouse movement on average, with noticeable &#8220;linger&#8221; when the mouse pointer is near the plotted data line. Note that this figure is extremely simplistic &#8211; 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.</p>
<p>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 <b>Visible</b> property is <code>'on'</code>. Despite this, when the mouse moves within the figure, these other axes unnecessarily process the mouse events.</p>
<h3 id="interactions">Changing the default interactions</h3>
<p>Let&#8217;s modify the axes creation script as I mentioned above, by changing the default interactions (note the highlighted code addition):</p>
<pre lang="matlab" highlight="11">
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
</pre>
<p>The test script now takes only 12 seconds to run &#8211; 4x faster than the default and yet IMHO with better interactivity (using RegionZoomInteraction).</p>
<h3 id="Toolbar">Effects of the axes toolbar</h3>
<p>The axes-specific toolbar, another innovation of R2018b, does not just have interactivity aspects, which are by themselves <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">much-contested</a>. 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&#8217;s transparency, visibility, background color and contents continuously update whenever the mouse moves within the axes area.</p>
<p>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:</p>
<pre lang="matlab" highlight="12">
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
</pre>
<p>This brings the test script&#8217;s run-time down to 6 seconds &#8211; <b>7x faster than the default run-time</b>. 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.</p>
<h3 id="Conclusions">Conclusions</h3>
<p>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 &#8211; 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.</p>
<p>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&#8230;), 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.</p>
<p>If your Matlab program could use a performance boost, I would be happy to assist making your program faster and more responsive. Don&#8217;t hesitate to reach out to me for a consulting quote.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/improving-graphics-interactivity/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Interesting Matlab puzzle &#8211; analysis</title>
		<link>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=interesting-matlab-puzzle-analysis</link>
					<comments>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Tue, 09 Apr 2019 11:52:00 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8664</guid>

					<description><![CDATA[<p>Solution and analysis of a simple Matlab puzzle that leads to interesting insight on Matlab's parser. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis">Interesting Matlab puzzle &#8211; analysis</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle" rel="bookmark" title="Interesting Matlab puzzle">Interesting Matlab puzzle </a> <small>A simple Matlab puzzle that leads to interesting insight on Matlab's parser. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compiler-bug-and-workaround" rel="bookmark" title="Matlab compiler bug and workaround">Matlab compiler bug and workaround </a> <small>Both the Matlab compiler and the publish function have errors when parsing block-comments in Matlab m-code. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>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&#8217;s post, I offer my analysis of the puzzle.<br />
The original code snippet was this:</p>
<pre lang="matlab" highlight="3">
function test
    try
        if (false) or (true)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end
</pre>
<p>With the following variants for the highlighted line #3:</p>
<pre lang="matlab">
        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
</pre>
<p><span id="more-10305"></span></p>
<h3 id="variant-1">Variant #1: if (false) or (true)</h3>
<p>The first thing to note is that <code>or</code> is a function and not an operator, unlike some other programming languages. Since this function immediately follows a condition (<code>true</code>), it is not considered a condition by its own, and is not parsed as a part of the "if" expression.<br />
In other words, as Roger Watt <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-471709" target="_blank">correctly stated</a>, line #3 is actually composed of two separate expressions: <code>if (false)</code> and <code>or(true)</code>. The code snippet can be represented in a more readable format as follows, where the executed lines are highlighted:</p>
<pre lang="matlab" highlight="1,5">
        if (false)
            or (true)
            disp('Yaba');
        else
            disp('Daba');
        end
</pre>
<p>Since the condition (<code>false</code>) 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.<br />
Also note that despite the misleading appearance of line #3 in the original code snippet, the condition only contains a single condition (<code>false</code>) and therefore neither <a href="https://www.mathworks.com/help/matlab/ref/shortcircuitor.html" rel="nofollow" target="_blank">short-circuit evaluation</a> nor eager evaluation are relevant (they only come into play in expressions that contain 2+ conditions).<br />
As Rik Wisselink <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-471713" target="_blank">speculated</a> and Michelle Hirsch <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-472001" target="_blank">later confirmed</a>, 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 <a href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output" target="_blank">Mlint/Code-Analyzer</a>). 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.<br />
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.</p>
<h3 id="variant-2">Variant #2: if (true) or (false)</h3>
<p>In this variant, the "if" condition is always true, causing the top conditional branch to execute. This starts with a call to <code>or(false)</code>, which throws a run-time error because the or() function expects 2 input arguments and only one is supplied (as Chris Luengo was the <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-471677" target="_blank">first to note</a>). Therefore, execution jumps to the "catch" block and 'Doo!' is displayed in the Matlab console.<br />
In a more verbose manner, this is the code (executed lines highlighted):</p>
<pre lang="matlab" highlight="3-4,10">
function test
    try
        if (true)
            or (false)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end
</pre>
<h3 id="variant-3">Variant #3: if (true) or (10< 9.9)</h3>
<p>This is exactly the same as variant #2, since the condition <code>10&lt; 9.9</code> is the same as <code>false</code>. The parentheses around the condition ensure that it is treated as a single logical expression (that evaluates to <code>false</code>) 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.<br />
As Will correctly <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-471920" target="_blank">noted</a>, this variant is simply a red herring whose aim was to lead up to the following variant:</p>
<h3 id="variant-4">Variant #4: if true or 10&lt; 9.9</h3>
<p>At first glance, this variant looks exactly the same as variant #3, because parentheses around conditions are not mandatory in Matlab. In fact, <code>if a || b</code> is equivalent to (and in many cases more readable/maintainable than) <code>if (a) || (b)</code>. However, remember that "or" is not a logical operator but rather a function call (see variant #1 above). For this reason, the <code>if true or 10&lt; 9.9</code> statement is equivalent to the following:</p>
<pre lang="matlab">
        if true
            or 10< 9.9
            ...
</pre>
<p>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:</p>
<pre lang="matlab">
        if true
            or('10<', '9.9')
            ...
</pre>
<p>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 (<code>'1'||'9'</code> and so-on), based on the inputs' ASCII codes. So, the code is basically the same as:</p>
<pre lang="matlab">
        if true
            or([49,48,60], [57,46,57])  % =ASCII values of '10<','9.9'
            disp('Yaba');
</pre>
<p>Which results in the following output in the Matlab console:</p>
<pre lang="matlab">
ans =
  1×3 logical array
   1   1   1
Yaba
</pre>
<p>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 <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comment-472722" target="_blank">noted</a>, 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.</p>
<h3 id="variant-5">Variant #5: if 10&gt; 9.9 or 10&lt; 9.9</h3>
<p>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 <code>10&gt; 9.9</code> is a single scalar condition (that evaluates to <code>true</code>), <code>10&lt; 9.9</code> are in fact 2 separate 3-character string arguments to the "or" function. The end result is exactly the same as in variant #4.<br />
I hope you enjoyed this little puzzle. Back to serious business in the next post!</p>
<h3 id="USA">USA visit</h3>
<p>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.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis">Interesting Matlab puzzle &#8211; analysis</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle" rel="bookmark" title="Interesting Matlab puzzle">Interesting Matlab puzzle </a> <small>A simple Matlab puzzle that leads to interesting insight on Matlab's parser. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compiler-bug-and-workaround" rel="bookmark" title="Matlab compiler bug and workaround">Matlab compiler bug and workaround </a> <small>Both the Matlab compiler and the publish function have errors when parsing block-comments in Matlab m-code. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Interesting Matlab puzzle</title>
		<link>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=interesting-matlab-puzzle</link>
					<comments>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 31 Mar 2019 10:15:06 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8614</guid>

					<description><![CDATA[<p>A simple Matlab puzzle that leads to interesting insight on Matlab's parser. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle">Interesting Matlab puzzle</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis" rel="bookmark" title="Interesting Matlab puzzle &#8211; analysis">Interesting Matlab puzzle &#8211; analysis </a> <small>Solution and analysis of a simple Matlab puzzle that leads to interesting insight on Matlab's parser. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-dde-support" rel="bookmark" title="Matlab DDE support">Matlab DDE support </a> <small>Windows DDE is an unsupported and undocumented feature of Matlab, that can be used to improve the work-flow in the Windows environment...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Here&#8217;s a nice little puzzle that came to me from long-time Matlab veteran <a href="https://apjanke.net" rel="nofollow" target="_blank">Andrew Janke</a>:<br />
Without actually running the following code in Matlab, what do you expect its output to be? &#8216;Yaba&#8217;? &#8216;Daba&#8217;? perhaps &#8216;Doo!&#8217;? or maybe it won&#8217;t run at all because of a parsing error?</p>
<pre lang="matlab">
function test
    try
        if (false) or (true)
            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end
</pre>
<p>To muddy the waters a bit, do you think that <a href="https://www.mathworks.com/help/matlab/ref/logicaloperatorsshortcircuit.html" rel="nofollow" target="_blank">short-circuit evaluation</a> is at work here? or perhaps eager evaluation? or perhaps neither?<br />
Would the results be different if we switched the order of the conditional operands, i.e. <code>(true) or (false)</code> instead of <code>(false) or (true)</code>? if so, how and why?<br />
And does it matter if I used &#8220;<code>false</code>&#8221; or &#8220;<code>10&lt; 9.9</code>&#8221; as the &#8220;or&#8221; conditional?<br />
Are the parentheses around the conditions important? would the results be any different without these parentheses?<br />
In other words, how and why would the results change for the following variants?</p>
<pre lang="matlab">
        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
</pre>
<p>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.<br />
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).<br />
<b><u>Addendum April 9, 2019</u></b>: I have now posted my solution/analysis of this puzzle <a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis" target="_blank">here</a>.</p>
<h3 id="USA">USA visit</h3>
<p>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.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle">Interesting Matlab puzzle</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/interesting-matlab-puzzle-analysis" rel="bookmark" title="Interesting Matlab puzzle &#8211; analysis">Interesting Matlab puzzle &#8211; analysis </a> <small>Solution and analysis of a simple Matlab puzzle that leads to interesting insight on Matlab's parser. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/interesting-uitree-utility" rel="bookmark" title="An interesting uitree utility">An interesting uitree utility </a> <small>ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-dde-support" rel="bookmark" title="Matlab DDE support">Matlab DDE support </a> <small>Windows DDE is an unsupported and undocumented feature of Matlab, that can be used to improve the work-flow in the Windows environment...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/interesting-matlab-puzzle/feed</wfw:commentRss>
			<slash:comments>20</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented plot marker types</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-plot-marker-types</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Mar 2019 11:05:14 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8539</guid>

					<description><![CDATA[<p>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>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 <a href="https://undocumentedmatlab.com/articles/hg2-update" target="_blank">transition to HG2</a> in R2014b and the <a href="https://blogs.mathworks.com/graphics/2015/11/10/memory-consumption/#comment-465" rel="nofollow" target="_blank">implementation of markers using OpenGL primitives</a>. 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 <a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" target="_blank">plot lines</a> and <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">markers</a>, or <a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" target="_blank">various aspects of contour plots</a>.<br />
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 <b>MarkerHandle</b> that we can access. This returns an internal object that enables <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">marker transparency and color gradients</a>. 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:</p>
<pre lang="matlab">
>> 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'}
</pre>
<p>We see that the top-level marker styles directly correspond to the low-level styles, except for the low-level &#8216;vbar&#8217; and &#8216;hbar&#8217; 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&#8217;s <b>MarkerHandle</b> property:</p>
<pre lang="matlab">
hLine.MarkerHandle.Style = 'hbar';
set(hLine.MarkerHandle, 'Style','hbar');  % alternative
</pre>
<p><center><figure style="width: 213px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/plot_hbar.png" alt="hLine.MarkerHandle.Style='hbar'" title="hLine.MarkerHandle.Style='hbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='hbar'</figcaption></figure> <figure style="width: 213px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/plot_vbar.png" alt="hLine.MarkerHandle.Style='vbar'" title="hLine.MarkerHandle.Style='vbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='vbar'</figcaption></figure></center></p>
<h3 id="USA">USA visit</h3>
<p>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.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 9 (popup figures)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-9-popup-figures</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 10 Feb 2019 17:00:10 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8402</guid>

					<description><![CDATA[<p>Custom popup figures can be attached to Matlab GUI toolstrip controls. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures">Matlab toolstrip – part 9 (popup figures)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> 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.<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_popup_figure.png" alt="Popup figure in Matlab toolstrip" title="Popup figure in Matlab toolstrip" width="80%" style="max-width:605px;" /></center><br />
Toolstrips can be a bit complex to develop so I&#8217;m proceeding slowly, with each post in the miniseries building on the previous posts. <span id="more-8402"></span> I encourage you to review the earlier posts in the <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
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:</p>
<pre lang="matlab">import matlab.ui.internal.toolstrip.*</pre>
<h3 id="steps">Main steps and usage example</h3>
<p>To attach a figure popup to a toolstrip control, follow these steps:</p>
<ol>
<li>Create a new figure, using GUIDE or the <i><b>figure</b></i> function. The figure should typically be created modal and non-visible, unless there&#8217;s a good reason to avoid this. Note that the figure needs to be a legacy (Java-based) figure, created with GUIDE or the <i><b>figure</b></i> function &#8212; web-based uifigure (created with AppDesigner or the <i><b>uifigure</b></i> function) is not [currently] supported. </li>
<li>Create a callback function that opens and initializes this figure, and then moves it to the expected screen location using the following syntax: <code>hToolGroup.showFigureDialog(hFig,hAnchor)</code>, where <code>hFig</code> is the figure&#8217;s handle, and <code>hAnchor</code> is the handle for the triggering toolstrip control.</li>
<li>Attach the callback function to the triggering toolstrip control.</li>
</ol>
<p>Here&#8217;s a simple usage example, in which I present a file-selector popup:</p>
<pre lang="matlab">
% 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
</pre>
<p>This leads to the popup figure as shown in the screenshot above.<br />
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.<br />
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 <a href="https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows" target="_blank">undocumented visual illusion</a> &#8211; 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 <a href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget" target="_blank"><code>PopupPanel</code> container</a> that I discussed in another post <i>cannot</i> 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, <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" target="_blank">as explained here</a>).<br />
The astute reader may wonder why I bothered going to all the trouble of displaying a modal popup with a <code>JFileChooser</code>, when I could have simply used the built-in <i><b>uigetfile</b></i> or <i><b>uiputfile</b></i> functions in the button&#8217;s callback. The answer is that (a) this mechanism displays the popup directly beneath the triggering button using <code>hToolGroup.showFigureDialog()</code>, and also (b) enables complex popups (dialogs) that have no direct builtin Matlab function (for example, a <a href="https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations" target="_blank">file-selector with preview</a>, or a <a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" target="_blank">multi-component input form</a>).</p>
<h3 id="compatibility">Compatibility considerations for R2018a or older</h3>
<p>In Matlab releases R2018a or older that do not have the <i>hToolGroup.showFigureDialog()</i> function, you can create it yourself in a separate <i>showFigureDialog.m</i> file, as follows:</p>
<pre lang="matlab">
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<nasgu>
    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
</pre>
<h3 id="showFigureDialog">Under the hood of <i>showFigureDialog()</i></h3>
<p>How does <i>showFigureDialog()</i> know where to place the figure, directly beneath the triggering toolstrip anchor?<br />
The answer is really quite simple, if you look at this method&#8217;s source-code in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/ToolGroup.m</i> (around line 500, depending on the Matlab release).<br />
The function first checks whether the input <code>hFig</code> handle belongs to a figure or uifigure, and issues an error message in case it&#8217;s a uifigures (only legacy figures are currently supported).<br />
Then the function fetches the toolstrip control&#8217;s underlying Java control handle using the following code (slightly modified for clarity), <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization#Java" target="_blank">as explained here</a>:</p>
<pre lang="matlab">jAnchor = hToolGroup.ToolstripSwingService.Registry.getWidgetById(hAnchor.getId());</pre>
<p>Next, it uses the Java control&#8217;s <i>getLocationOnScreen()</i> to get the control&#8217;s onscreen position, accounting for monitor DPI variation that affects the X location.<br />
The figure&#8217;s <b>OuterPosition</b> property is then set so that the figure&#8217;s top-left corner is exactly next to the control&#8217;s bottom-left corner.<br />
Finally, the figure&#8217;s <b>Visible</b> property is set to &#8216;on&#8217; to make the figure visible in its new position.<br />
The popup figure&#8217;s location is recomputed by <i>showFigureDialog()</i> 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.</p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>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.<br />
In a succeeding post, I&#8217;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.<br />
In future posts, I plan to discuss docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures">Matlab toolstrip – part 9 (popup figures)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 8 (galleries)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-8-galleries</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 03 Feb 2019 17:00:55 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8321</guid>

					<description><![CDATA[<p>Matlab toolstrips can contain customizable gallery panels of items. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries">Matlab toolstrip – part 8 (galleries)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> 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.<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Gallery.png" alt="Toolstrip Gallery (in-line &#038; drop-down)" title="Toolstrip Gallery (in-line &#038; drop-down)" width="90%" style="max-width:747px;" height="102" /></center><br />
Toolstrips can be a bit complex to develop so I&#8217;m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
<span id="more-8321"></span><br />
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:</p>
<pre lang="matlab">import matlab.ui.internal.toolstrip.*</pre>
<h3 id="components">Gallery sub-components</h3>
<p><figure style="width: 300px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Gallery_hierarchy.png" alt="Toolstrip gallery popup components" title="Toolstrip gallery popup components" width="300" height="205" /><figcaption class="wp-caption-text">Toolstrip gallery popup components</figcaption></figure> Toolstrip galleries are panels of buttons (typically large icons with an attached text label), which are grouped in &#8220;categories&#8221;. The gallery content can be presented either in-line within the toolstrip (a <code>Gallery</code> control), or as a drop-down button&#8217;s popup panel (a <code>DropDownGalleryButton</code> control). In either case, the displayed popup panel is a <code>GalleryPopup</code> object, that is composed of one or more <code>GalleryCategory</code>, each of which has one or more <code>GalleryItem</code> (push-button) and/or <code>ToggleGalleryItem</code> (toggle-button).</p>
<ul>
<li><code>Gallery</code> or <code>DropDownGalleryButton</code>
<ul>
<li><code>GalleryPopup</code>
<ul>
<li><code>GalleryCategory</code>
<ul>
<li><code>GalleryItem</code> or <code>ToggleGalleryItem</code></li>
<li><code>GalleryItem</code> or <code>ToggleGalleryItem</code></li>
<li>&#8230;</li>
</ul>
</li>
<li><code>GalleryCategory</code></li>
<li>&#8230;</li>
</ul>
</li>
</ul>
</ul>
<p><!-- center>[caption id="" align="aligncenter" width="492" caption="Toolstrip gallery popup components"]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Gallery_hierarchy.png" alt="Toolstrip gallery popup components" title="Toolstrip gallery popup components" width="492" height="337" />[/caption]</center --><br />
For a demonstration of toolstrip Galleries, see the code files in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/</i>, specifically <i>showcaseToolGroup.m</i> and <i>showcaseBuildTab_Gallery.m</i>.</p>
<h3 id="GalleryPopup">GalleryPopup</h3>
<p>We first create the <code>GalleryPopup</code> object, then add to it a few <code>GalleryCategory</code> groups of <code>GalleryItem</code>, <code>ToggleGalleryItem</code> buttons. In the example below, we use a <code>ButtonGroup</code> to ensure that only a single <code>ToggleGalleryItem</code> button is selected:</p>
<pre lang="matlab">
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);
...
</pre>
<p><center><figure style="width: 461px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/GalleryPopup_single_icon_view.png" alt="Single-selection GalleryPopup (icon view)" title="Single-selection GalleryPopup (icon view)" width="461" height="337" /><figcaption class="wp-caption-text">Single-selection GalleryPopup (icon view)</figcaption></figure></center><br />
Note that in a real-world situation, we&#8217;d assign a <b>Description</b>, <b>Tag</b> and <b>ItemPushedFcn</b> to all gallery items. This was elided from the code snippet above for readability, but should be part of any actual GUI. The <b>Description</b> only appears as tooltip popup in icon-view (shown above), but appears as a visible label in list-view (see below).</p>
<h3 id="items">Gallery items selection: push-button action, single-selection toggle, multiple selection toggle</h3>
<p>If we use <code>ToggleGalleryItem</code> without a <code>ButtonGroup</code>, multiple gallery items can be selected, rather than just a single selection as shown above:</p>
<pre lang="matlab" highlight="2,7,10,13">
...
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);
...
</pre>
<p><center><figure style="width: 460px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/GalleryPopup_multiple_icon_view.png" alt="Multiple-selection GalleryPopup (icon view)" title="Multiple-selection GalleryPopup (icon view)" width="460" height="337" /><figcaption class="wp-caption-text">Multiple-selection GalleryPopup (icon view)</figcaption></figure></center><br />
Alternatively, if we use <code>GalleryItem</code> instead of <code>ToggleGalleryItem</code>, 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.</p>
<h3 id="customizing">Customizing the GalleryPopup</h3>
<p>Properties that affect the <code>GalleryPopup</code> appearance are:</p>
<ul>
<li><b>DisplayState</b> &#8211; initial display mode of gallery items (string; default=&#8217;icon_view&#8217;, valid values: &#8216;icon_view&#8217;,&#8217;list_view&#8217;)</li>
<li><b>GalleryItemRowCount</b> &#8211; 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 <b>GalleryItemWidth</b> (see below)</li>
<li><b>GalleryItemTextLineCount</b> &#8211; number of rows used for display of the item label (integer; default=2, valid values: 0,1,2)</li>
<li><b>ShowSelection</b> &#8211; whether or not to display the last-selected item (logical; default=false). Needs to be true for <code>Gallery</code> and false for <code>DropDownGalleryButton</code>.</li>
<li><b>GalleryItemWidth</b> &#8211; number of pixels to allocate for each gallery item (integer, hidden; default=80)</li>
<li><b>FavoritesEnabled</b> &#8211; whether or not to enable a &#8220;Favorites&#8221; category (logical, hidden; default=false)</li>
</ul>
<p>All of these properties are defined as private in the <code>GalleryPopup</code> class, and can only be specified during the class object&#8217;s construction. For example, instead of the default icon-view, we can display the gallery items as a list, by setting the <code>GalleryPopup</code>&#8216;s <b>DisplayState</b> property to <code>'list_view'</code> during construction:</p>
<pre lang="matlab">
popup = GalleryPopup('DisplayState','list_view');
</pre>
<p><center><figure style="width: 460px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/GalleryPopup_single_list_view.png" alt="GalleryPopup (list view)" title="GalleryPopup (list view)" width="460" height="415" /><figcaption class="wp-caption-text">GalleryPopup (list view)</figcaption></figure></center><br />
Switching from icon-view to list-view and back can also be done by clicking the corresponding icon near the popup&#8217;s top-right corner (next to the interactive search-box).</p>
<h3 id="Gallery">Gallery and DropDownGalleryButton</h3>
<p>Now that we have prepared <code>GalleryPopup</code>, let&#8217;s integrate it in our toolstrip.<br />
We have two choices &#8212; either in-line within the toolstrip section (using <code>Gallery</code>), or as a compact drop-down button (using <code>DropDownGalleryButton</code>):</p>
<pre lang="matlab">
% 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);
</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Gallery.png" alt="Toolstrip Gallery (in-line &#038; drop-down)" title="Toolstrip Gallery (in-line &#038; drop-down)" width="90%" style="max-width:747px;" height="102" /></center><br />
Clicking any of the drop-down (arrow) widgets will display the associated <code>GalleryPopup</code>.<br />
The <code>Gallery</code> and <code>DropDownGalleryButton</code> objects have several useful settable properties:</p>
<ul>
<li><b>Popup</b> &#8211; a <code>GalleryPopup</code> object handle, which is displayed when the user clicks the drop-down (arrow) widget. Only settable in the constructor, not after object creation.</li>
<li><b>MinColumnCount</b> &#8211; minimum number of item columns to display (integer; default=1). In <code>Gallery</code>, 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 <code>DropDownGalleryButton</code>, this property can be set even after object creation (despite incorrect internal documentation), and controls the width of the popup panel.</li>
<li><b>MaxColumnCount</b> &#8211; maximal number of items columns to display (integer; default=10). In <code>Gallery</code>, this property is only settable in the constructor, not after object creation. In <code>DropDownGalleryButton</code>, this property can be set even after object creation but in any case seems to have no visible effect.</li>
<li><b>Description</b> &#8211; tooltip text displayed when the mouse hovers over the <code>Gallery</code> area (outside the area of the internal gallery items, which have their own individual Descriptions), or over the <code>DropDownGalleryButton</code> control.</li>
<li><b>TextOverlay</b> &#8211; a semi-transparent text label overlaid on top of the gallery panel (string, default=&#8221;). Only available in <code>Gallery</code>, not <code>DropDownGalleryButton</code>.</li>
</ul>
<p>For example:</p>
<pre lang="matlab">
gallery = Gallery(popup, 'MinColumnCount',2, 'MaxColumnCount',4);
gallery.TextOverlay = 'Select from these items';
</pre>
<p><center><figure style="width: 310px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_TextOverlay.png" alt="Effect of TextOverlay" title="Effect of TextOverlay" width="310" height="74" /><figcaption class="wp-caption-text">Effect of TextOverlay</figcaption></figure></center></p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>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.<br />
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 &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries">Matlab toolstrip – part 8 (galleries)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 7 (selection controls)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-7-selection-controls</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 27 Jan 2019 17:00:34 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8257</guid>

					<description><![CDATA[<p>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls">Matlab toolstrip – part 7 (selection controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> 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.<br />
<center><figure style="width: 371px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_SplitButton.png" alt="Toolstrip SplitButton with dynamic popup and static sub-menu" title="Toolstrip SplitButton with dynamic popup and static sub-menu" width="371" height="184" /><figcaption class="wp-caption-text">Toolstrip SplitButton with dynamic popup and static sub-menu</figcaption></figure></center><br />
Toolstrips can be a bit complex to develop so I&#8217;m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
<span id="more-8257"></span><br />
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:</p>
<pre lang="matlab">import matlab.ui.internal.toolstrip.*</pre>
<p>There are 4 types of popups in toolstrip controls:</p>
<ol>
<li>Builtin dropdown (combo-box) selector similar to the familiar <i><b>uicontrol</b>(&#8216;style&#8217;,&#8217;popup&#8217;,&#8230;)</i>. In toolstrips, this is implemented using the <code>DropDown</code> control.</li>
<li>A more complex dropdown selector having icons and tooltips, implemented using the <code>DropDownButton</code> and <code>SplitButton</code> toolstrip controls.</li>
<li>An even-more complex drop-down selector, which presents a gallery of options. This will be discussed in detail in the next post.</li>
<li>A fully-customizable form panel (&#8220;popup form&#8221;). This will be discussed separately, in the following post.</li>
</ol>
<h3 id="DropDown">DropDown</h3>
<p>The simple <code>DropDown</code> toolstrip control is very easy to set up and use:</p>
<pre lang="matlab">
hPopup = DropDown({'Label1';'Label2';'Label3'});
hPopup.Value = 'Label3';
hPopup.ValueChangedFcn = @ValueChangedCallback;
</pre>
<p><center><figure style="width: 100px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_DropDown.png" alt="Toolstrip DropDown" title="Toolstrip DropDown" width="56" height="64" /><figcaption class="wp-caption-text">Toolstrip DropDown</figcaption></figure></center> Note that the drop-down items (labels) need to be specified as a column cell-array (i.e. {a;b;c}) &#8211; a row cell-array ({a,b,c}) will result in run-time error.<br />
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:</p>
<pre lang="matlab">
items = {'One',   'Label1'; ...
         'Two',   'Label2'; ...
         'Three', 'Label3'}
hPopup = DropDown(items);
hPopup.Value = 'Two';
hPopup.ValueChangedFcn = @ValueChangedCallback;
</pre>
<p>This drop-down control will display the labels &#8220;Label1&#8221;, &#8220;Label2&#8221; (initially selected), and &#8220;Label3&#8221;. Whenever the selected drop-down item is changed, the corresponding popup <b>Value</b> will change to the corresponding value. For example, when &#8220;Label3&#8221; is selected in the drop-down, <code>hPopup.Value</code> will change to &#8216;Three&#8217;.<br />
Another useful feature of the toolstrip <code>DropDown</code> control is the <b>Editable</b> property (logical true/false, default=false), which enables the user to modify the entry in the drop-down&#8217;s editbox. Any custom text entered within the editbox will update the control&#8217;s <b>Value</b> property to that string.</p>
<h3 id="ListBox">ListBox</h3>
<p>We can create a <code>ListBox</code> in a very similarly manner to <code>DropDown</code>. 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:</p>
<pre lang="matlab">
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);
</pre>
<p><center><figure style="width: 102px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_ListBox.png" alt="Toolstrip ListBox (multi-selection)" title="Toolstrip ListBox (multi-selection)" width="102" height="75" /><figcaption class="wp-caption-text">Toolstrip ListBox (multi-selection)</figcaption></figure></center><br />
The <code>DropDown</code> and <code>ListBox</code> controls are nearly identical in terms of their properties, methods and events/callbacks, with the following notable exceptions:</p>
<ul>
<li><code>ListBox</code> controls do not have an <b>Editable</b> property</li>
<li><code>ListBox</code> controls have a <b>MultiSelect</b> property (logical, default=false), which <code>DropDown</code>s do not have. Note that this property can only be set during the <code>ListBox</code>&#8216;s creation, as shown in the code snippet above.</li>
</ul>
<h3 id="PopupList">DropDownButton and SplitButton</h3>
<p>A more elaborate drop-down selector can be created using the <code>DropDownButton</code> and <code>SplitButton</code> toolstrip controls. For such controls, we create a <code>PopupList</code> object, and add elements to it, which could be any of the following, in whichever order that you wish:</p>
<ol>
<li><code>PopupListHeader</code> &#8211; a section header (title), non-selectable</li>
<li><code>ListItem</code> &#8211; a selectable list item, with optional <b>Icon</b>, <b>Text</b>, and <b>Description</b> (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&#8217;s main label, unless we set <b>ShowDescription</b> to false.</li>
<li><code>ListItemWithCheckBox</code> &#8211; a selectable list item that toggles a checkmark icon based on the list item&#8217;s selection <b>Value</b> (on/off). The checkmark icon is not customizable (alas).</li>
<li><code>ListItemWithPopup</code> &#8211; a non-selectable list item, that displays a sub-menu (another <code>PopupList</code> that should be set to the parent list-item&#8217;s <b>Popup</b> property).</li>
</ol>
<p>A simple usage example (adapted from the <code>showcaseToolGroup</code> demo):<br />
<figure style="width: 303px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_PopupList.png" alt="Toolstrip PopupList" title="Toolstrip PopupList" width="303" height="289" /><figcaption class="wp-caption-text">Toolstrip PopupList</figcaption></figure></p>
<pre lang="matlab">
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()
</pre>
<p>We now have two alternatives for attaching this popup to the <code>DropDownButton</code> or <code>SplitButton</code>: <figure style="width: 371px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_SplitButton.png" alt="Toolstrip SplitButton with dynamic popup and static sub-menu" title="Toolstrip SplitButton with dynamic popup and static sub-menu" width="371" height="184" /><figcaption class="wp-caption-text">Toolstrip SplitButton with dynamic popup and static sub-menu</figcaption></figure></p>
<ul>
<li><i>Static popup</i> &#8211; set the <b>Popup</b> property of the button or <code>ListItemWithPopup</code> to the popup-creation function (or <code>hPopup</code>). The popup will be created once and will remain unchanged throughout the program execution. For example:
<pre lang="matlab">
hButton = DropDownButton('Vertical', Icon.OPEN_24);
hButton.Popup = createPopup();
</pre>
</li>
<li><i>Dynamic popup</i> &#8211; set the <b>DynamicPopupFcn</b> of the button or <code>ListItemWithPopup</code> 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:
<pre lang="matlab">
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
</pre>
</li>
</ul>
<p><!-- center>[caption id="" align="aligncenter" width="371" caption="Toolstrip SplitButton with dynamic popup and static sub-menu"]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_SplitButton.png" alt="Toolstrip SplitButton with dynamic popup and static sub-menu" title="Toolstrip SplitButton with dynamic popup and static sub-menu" width="371" height="184" />[/caption]</center --><br />
<code>DropDownButton</code> and <code>SplitButton</code> are exactly the same as far as the popup-list is concerned: If it is set via the <b>Popup</b> property then the popup is static (in the sense that it is only evaluated once, when created), and if it is set via <b>DynamicPopupFcn</b> then the popup is dynamic (re-created before display). The only difference between <code>DropDownButton</code> and <code>SplitButton</code> is that in addition to the drop-down control, a <code>SplitButton</code> also includes a regular push-button control (with its corresponding <b>ButtonPushedFcn</b> callback).<br />
In summary:</p>
<ul>
<li>If <b>DynamicPopupFcn</b> is set to a function handle, then the <code>PopupList</code> that is returned by that function will be re-evaluated and displayed whenever the user clicks the main button of a <code>DropDownButton</code> or the down-arrow part of a <code>SplitButton</code>. This happens even if the <b>Popup</b> property is also set i.e., <b>DynamicPopupFcn</b> has precedence over <b>Popup</b>; when both of them are set, <b>Popup</b> is silently ignored (it would be useful for Matlab to display a warning in such cases, hopefully in a future release).</li>
<li>If <b>DynamicPopupFcn</b> is not set but <b>Popup</b> is (to a <code>PopupList</code> object handle), then this <code>PopupList</code> will be computed only once (when first created) and then it will be displayed whenever the user clicks the main button of a <code>DropDownButton</code> or the down-arrow part of a <code>SplitButton</code>.</li>
<li>Separately from the above, if a <code>SplitButton</code>&#8216;s <b>ButtonPushedFcn</b> property is set to a function handle, then that function will be evaluated whenever the user clicks the main button of the <code>SplitButton</code>. No popup is presented, unless of course the callback function displays a popup programmatically. Note that <b>ButtonPushedFcn</b> is a property of <code>SplitButton</code>; this property does not exist in a <code>DropDownButton</code>. </li>
</ul>
<p>Important note: whereas <code>DropDown</code> and <code>ListBox</code> have a <b>ValueChangedFcn</b> callback that is invoked whenever the drop-down/listbox <b>Value</b> has changed, the callback mechanism is very different with <code>DropDownButton</code> and <code>SplitButton</code>: here, each menu item has its own individual callback that is invoked when that item is selected (clicked): <b>ItemPushedFcn</b> for <code>ListItem</code>; <b>ValueChangedFcn</b> for <code>ListItemWithCheckBox</code>; and <b>DynamicPopupFcn</b> for <code>ListItemWithPopup</code>. As we shall see later, the same is true for gallery items &#8211; each item has its own separate callback.</p>
<h3 id="Galleries">Galleries</h3>
<p>Toolstrip galleries are panels of buttons (typically large icons with an attached text label), which are grouped in &#8220;categories&#8221;.<br />
The general idea is to first create the <code>GalleryPopup</code> object, then add to it a few <code>GalleryCategory</code> groups, each consisting of <code>GalleryItem</code> (push-buttons) and/or <code>ToggleGalleryItem</code> (toggle-buttons) objects. Once this <code>GalleryPopup</code> is created, we can either integrate it in-line within the toolstrip section (using <code>Gallery</code>), or as a compact drop-down button (using <code>DropDownGalleryButton</code>):</p>
<pre lang="matlab">
% 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);
</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Gallery.png" alt="Toolstrip Gallery (in-line &#038; drop-down)" title="Toolstrip Gallery (in-line &#038; drop-down)" width="90%" style="max-width:747px;" height="102" /></center><br />
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 &#8212; this will be the topic of next week&#8217;s blog post.</p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss Galleries in depth, followed by popup forms.<br />
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 &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls">Matlab toolstrip – part 7 (selection controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 6 (complex controls)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-6-complex-controls</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 21 Jan 2019 16:00:38 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8235</guid>

					<description><![CDATA[<p>Multiple types of customizable controls can be added to Matlab toolstrips</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls">Matlab toolstrip – part 6 (complex controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> 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.<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Controls.png" alt="Some custom Toolstrip Controls" title="Some custom Toolstrip Controls" width="80%" style="max-width:727px;"/></center><br />
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 <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
<span id="more-8235"></span><br />
The first place to search for potential toostrip components/controls is in <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">Matlab&#8217;s built-in toolstrip demos</a>. The <code>showcaseToolGroup</code> demo displays a large selection of generic components grouped by function. These controls&#8217; callbacks do little less than simply output a text message in the Matlab console. On the other hand, the <code>showcaseMPCDesigner</code> 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 <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/</i> folder. To see the available toolstrip controls in action and how they could be integrated, refer to the source-code of these two demos.<br />
All toolstrip controls are defined by classes in the <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+toolstrip/</i> folder and use the <code>matlab.ui.internal.toolstrip</code> package prefix, for example:</p>
<pre lang="matlab">
% Alternative 1:
hButton = matlab.ui.internal.toolstrip.Button;
% Alternative 2:
import matlab.ui.internal.toolstrip.*
hButton = Button;
</pre>
<p>For the remainder of today&#8217;s post it is assumed that you are using one of these two alternatives whenever you access any of the toolstrip classes.</p>
<h3 id="controls">Top-level toolstrip controls</h3>
<table>
<tbody>
<tr>
<th>Control</th>
<th>Description</th>
<th>Important properties</th>
<th>Callbacks</th>
<th>Events</th>
</tr>
<tr>
<td><code>EmptyControl</code></td>
<td>Placeholder (filler) in container column</td>
<td>(none)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>Label</code></td>
<td>Simple text label (no action)</td>
<td><b>Icon</b>, <b>Text</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>Button</code></td>
<td>Push-button</td>
<td><b>Icon</b>, <b>Text</b> (string)</td>
<td><b>ButtonPushedFcn</b></td>
<td>ButtonPushed</td>
</tr>
<tr>
<td><code>ToggleButton</code></td>
<td>Toggle (on/off) button</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Value</b> (logical true/false), <b>ButtonGroup</b> (a <code>ButtonGroup</code> object)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>RadioButton</code></td>
<td>Radio-button (on/off)</td>
<td><b>Text</b> (string), <b>Value</b> (logical true/false), <b>ButtonGroup</b> (a <code>ButtonGroup</code> object)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>CheckBox</code></td>
<td>Check-box (on/off)</td>
<td><b>Text</b> (string), <b>Value</b> (logical true/false)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>EditField</code></td>
<td>Single-line editbox</td>
<td><b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, FocusGained, FocusLost</td>
</tr>
<tr>
<td><code>TextArea</code></td>
<td>Multi-line editbox</td>
<td><b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, FocusGained, FocusLost</td>
</tr>
<tr>
<td><code>Spinner</code></td>
<td>A numerical spinner control of values between min,max</td>
<td><b>Limits</b> ([min,max]), <b>StepSize</b> (integer), <b>NumberFormat</b> (&#8216;integer&#8217; or &#8216;double&#8217;), <b>DecimalFormat</b> (string), <b>Value</b> (numeric)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, ValueChanging</td>
</tr>
<tr>
<td><code>Slider</code></td>
<td>A horizontal slider of values between min,max</td>
<td><b>Limits</b> ([min,max]), <b>Labels</b> (cell-array), <b>Ticks</b> (integer), <b>UseSmallFont</b> (logical true/false, R2018b onward), <b>ShowButton</b> (logical true/false, undocumented), <b>Steps</b> (integer, undocumented), <b>Value</b> (numeric)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, ValueChanging</td>
</tr>
<tr>
<td><code>ListBox</code></td>
<td>List-box selector with multiple items</td>
<td><b>Items</b> (cell-array), <b>SelectedIndex</b> (integer), <b>MultiSelect</b> (logical true/false), <b>Value</b> (cell-array of strings)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>DropDown</code></td>
<td>Single-selection drop-down (combo-box) selector</td>
<td><b>Items</b> (cell-array), <b>SelectedIndex</b> (integer), <b>Editable</b> (logical true/false), <b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>DropDownButton</code></td>
<td>Button that has an associated drop-down selector</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Popup</b> (a <code>PopupList</code> object)</td>
<td><b>DynamicPopupFcn</b></td>
<td>(none)</td>
</tr>
<tr>
<td><code>SplitButton</code></td>
<td>Split button: main clickable part next to a drop-down selector</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Popup</b> (a <code>PopupList</code> object)</td>
<td><b>ButtonPushedFcn</b>, <b>DynamicPopupFcn</b></td>
<td>ButtonPushed, DropDownPerformed (undocumented)</td>
</tr>
<tr>
<td><code>Gallery</code></td>
<td>A gallery of selectable options, displayed in-panel</td>
<td><b>MinColumnCount</b> (integer), <b>MaxColumnCount</b> (integer), <b>Popup</b> (a <code>GalleryPopup</code> object), <b>TextOverlay</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>DropDownGalleryButton</code></td>
<td>A gallery of selectable options, displayed as a drop-down</td>
<td><b>MinColumnCount</b> (integer), <b>MaxColumnCount</b> (integer), <b>Popup</b> (a <code>GalleryPopup</code> object), <b>TextOverlay</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
</tbody>
</table>
<p>In addition to the control properties listed in the table above, all toolstrip controls share some common properties:</p>
<ul>
<li><b>Description</b> &#8211; a string that is shown in a tooltip when you hover the mouse over the control</li>
<li><b>Enabled</b> &#8211; 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 &#8216;on&#8217;/&#8217;off&#8217;</li>
<li><b>Tag</b> &#8211; a string that can be used to uniquely identify/locate the control via their container&#8217;s <i>find(tag)</i> and <i>findAll(tag)</i> methods. Can contain spaces and special symbols &#8211; does not need to be a valid Matlab identifier</li>
<li><b>Children</b> &#8211; contains a list of sub-component (if any); useful with complex controls</li>
<li><b>Parent</b> &#8211; the handle of the container that contains the control</li>
<li><b>Type</b> &#8211; the type of control, typically its class-name</li>
<li><b>Mnemonic</b> &#8211; an undocumented string property, currently unused (?)</li>
<li><b>Shortcut</b> &#8211; an undocumented string property, currently unused (?)</li>
</ul>
<p>The <code>EmptyControl</code>, <code>Button</code>, <code>ToggleButton</code> and <code>CheckBox</code> controls were discussed in an <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization#example" target="_blank">earlier post</a> of this miniseries. The bottom 6 selection controls (<code>ListBox</code>, <code>DropDown</code>, <code>DropDownButton</code>, <code>SplitButton</code>, <code>Gallery</code> and <code>DropDownGalleryButton</code>) will be discussed in the next post. The rest of the controls are described below.</p>
<h3 id="ButtonGroup">Button groups</h3>
<p>A ButtonGroup binds several <code>CheckBox</code> and <code>ToggleButton</code> components such that only one of them is selected (pressed) at any point in time. For example:</p>
<pre lang="matlab">
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);
</pre>
<p><center><figure style="width: 119px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_RadioButton.png" alt="Toolstrip ButtonGroup" title="Toolstrip ButtonGroup" width="119" height="82" /><figcaption class="wp-caption-text">Toolstrip ButtonGroup</figcaption></figure></center> Note that unlike the <i><b>uibuttongroup</b></i> object in &#8220;standard&#8221; figure GUI, the toolstrip&#8217;s <code>ButtonGroup</code> object does not have a SelectionChangedFcn callback property (or corresponding event). Instead, we need to set the <b>ValueChangedFcn</b> callback property (or listen to the ValueChanged event) separately for each individual control. This is really a shame &#8211; I think it would make good design sense to have a SelectionChangedFcn callback at the <code>ButtonGroup</code> level, as we do for <i><b>uibuttongroup</b></i> (in addition to the individual control callbacks).<br />
Also note that the internal documentation of <code>ButtonGroup</code> has an error &#8211; it provides an example usage with <code>RadioButton</code> that has its constructor inputs switched: the correct constructor is <code>RadioButton(hButtonGroup,labelStr)</code>. On the other hand, for <code>ToggleButton</code>, the hButtonGroup input is the [optional] 3rd input arg of the constructor: <code>ToggleButton(labelStr,Icon,hButtonGroup)</code>. I think that it would make much more sense for the <code>RadioButton</code> constructor to follow the documentation and the style of <code>ToggleButton</code> 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.</p>
<h3 id="Edit">Label, EditField and TextArea</h3>
<p>A <code>Label</code> control is a simple non-clickable text label with an optional <b>Icon</b>, whose text is controlled via the <b>Text</b> property. The label&#8217;s alignment is controlled by the containing column&#8217;s <b>HorizontalAlignment</b> property.<br />
An <code>EditField</code> is a single-line edit-box. Its string contents can be fetched/updated via the <b>Value</b> property, and when the user updates the edit-box contents the <b>ValueChangedFcn</b> callback is invoked (upon each modification of the string, i.e. every key-click). This is a pretty simple control actually.<br />
The <code>EditField</code> control has a hidden (undocumentented) settable property called <b>PlaceholderText</b>, 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&#8230;).<br />
A <code>TextArea</code> is another edit-box control, but enables entering multiple lines of text, unlike <code>EditField</code> which is a single-line edit-box. <code>TextArea</code> too is a very simple control, having a settable <b>Value</b> string property and a <b>ValueChangedFcn</b> callback. Whereas <code>EditField</code> controls, being single-line, would typically be included in 2- or 3-element toolstrip columns, the <code>TextArea</code> would typically be placed in a single-element column, so that it would span the entire column height.<br />
A peculiarity of toolstrip columns is that unless you specify their <b>Width</b> 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 <code>EditField</code> and <code>TextArea</code> 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&#8217;s <b>Width</b>:</p>
<pre lang="matlab">
% 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);
</pre>
<p><center><figure style="width: 233px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Editboxes.png" alt="Toolstrip Label, EditField and TextArea" title="Toolstrip Label, EditField and TextArea" width="233" height="100" /><figcaption class="wp-caption-text">Toolstrip Label, EditField and TextArea</figcaption></figure></center></p>
<h3 id="Spinner">Spinner</h3>
<p><code>Spinner</code> 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 <b>NumberFormat</b> of &#8216;integer&#8217; or &#8216;double&#8217; (default: &#8216;integer&#8217;) and a <b>DecimalFormat</b> which is a string composed of the number of sub-decimal digits to display and the format (&#8216;e&#8217; or &#8216;f&#8217;). For example, <b>DecimalFormat</b>=&#8217;4f&#8217; will display 4 digits after the decimal in floating-point format (&#8216;e&#8217; means engineering format). Here is a short usage example (notice the different ways that we can set the callbacks):</p>
<pre lang="matlab">
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);
</pre>
<p><center><figure style="width: 110px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Spinner.png" alt="Toolstrip Spinner" title="Toolstrip Spinner" width="110" height="95" /><figcaption class="wp-caption-text">Toolstrip Spinner</figcaption></figure></center> A logical extension of the toolstrip spinner implementation would be for <a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" target="_blank">non-numeric spinners</a>, as well as custom <b>Value</b> display formatting. Perhaps this will become available at some future Matlab release.</p>
<h3 id="Slider">Slider</h3>
<p><code>Slider</code> is a horizontal ruler on which you can move a knob from the left (min <b>Value</b>) to the right (max <b>Value</b>). 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):</p>
<pre lang="matlab">
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);
</pre>
<p><center><figure style="width: 217px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Slider.png" alt="Toolstrip Slider" title="Toolstrip Slider" width="217" height="95" /><figcaption class="wp-caption-text">Toolstrip Slider</figcaption></figure></center></p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss complex selection components, including listbox, drop-down, split-button, and gallery.<br />
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 &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls">Matlab toolstrip – part 6 (complex controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 5 (icons)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-5-icons</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 06 Jan 2019 17:00:37 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8188</guid>

					<description><![CDATA[<p>Icons can be specified in various ways for toolstrip controls and the app window itself. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons">Matlab toolstrip – part 5 (icons)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" target="_blank">previous post</a> 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 <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">the Toolstrip miniseries</a> before reading this post. Today&#8217;s post describes how we can set various icons, based on the toolstrip created in the previous posts:<br />
<center><figure style="width: 440px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_basic_controls.png" alt="Toolstrip example (basic controls)" title="Toolstrip example (basic controls)" width="100%" style="max-width:553px; margin:0" /><figcaption class="wp-caption-text">Toolstrip example (basic controls)</figcaption></figure></center><br />
<span id="more-8188"></span></p>
<h3 id="components">Component icons</h3>
<p>Many toolstrip controls (such as buttons, but not checkboxes for example) have a settable <b>Icon</b> property. The standard practice is to use a 16&#215;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&#215;24 icon for a component that spans the entire column height (i.e., when the column contains only a single component).<br />
We can use one of the following methods to specify the icon. Note that you need to <code>import matlab.ui.internal.toolstrip.*</code> if you wish to use the <code>Icon</code> class without the preceding package name.</p>
<ul>
<li>The <b>Icon</b> property value is typically empty (<code>[]</code>) by default, meaning that no icon is displayed.<br />
&nbsp;
</li>
<li>We can use one of ~150 standard icons using the format <code>Icon.&lt;icon-name&gt;</code>. For example: <code>icon = Icon.REFRESH_24</code>. These icons typically come in 2 sizes: 16&#215;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&#215;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
<pre lang="matlab">matlab.ui.internal.toolstrip.Icon.showStandardIcons</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_standard_icons.png" alt="Standard toolstrip control Icons" title="Standard toolstrip control Icons" width="50%" style="max-width:658px;" /></center></li>
<li>We can use the <code>Icon</code> 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:
<pre lang="matlab">icon = Icon(fullfile(matlabroot,'toolbox','matlab','icons','tool_colorbar.png')); % PNG/JPG image file (not GIF!)</pre>
<p>In fact, the ~150 standard icons above use this mechanism under the hood: <code>Icon.REFRESH_24</code> is basically a public static method of the <code>Icon</code> class, which simply calls <code>Icon('REFRESH_24','Refresh_24')</code>  (note the undocumented use of a 2-input <code>Icon</code> constructor). This method in turn uses the <i>Refresh_24.png</i> file in Matlab&#8217;s standard toolstrip resources folder: <i>%matlabroot%/toolbox/shared/controllib/general/resources/toolstrip_icons/Refresh_24.png</i>.</p>
<li>We can also use the <code>Icon</code> constructor by specifying a PNG or JPG file contained within a JAR file, using the standard <code>jar:file:...jar!/</code> notation. There are numerous icons included in Matlab&#8217;s JAR files &#8211; simply open these files in WinZip or WinRar and browse. In addition, you can include images included in any external JAR file. For example:
<pre lang="matlab">icon = Icon(['jar:file:/' matlabroot '/java/jar/mlwidgets.jar!/com/mathworks/mlwidgets/actionbrowser/resources/uparrow.png']);</pre>
</li>
<li>We can also use the <code>Icon</code> constructor by specifying a Java <code>javax.swing.ImageIcon</code> object. Fortunately we can create such objects from a variety of image formats (including GIFs). For example:
<pre lang="matlab">
iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','boardicon.gif');
jIcon = javax.swing.ImageIcon(iconFilename);  % Java ImageIcon from file (inc. GIF)
icon = Icon(jIcon);
</pre>
<p>If we need to resize the Java image (for example, from 16&#215;16 to 24&#215;24 or vise versa), we can use the following method:</p>
<pre lang="matlab">
% 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);
</pre>
</li>
<li>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.</li>
</ul>
<h3 id="app">App window icon</h3>
<p>The app window&#8217;s icon can also be set. By default, the window uses the standard Matlab membrane icon (<i>%matlabroot%/toolbox/matlab/icons/matlabicon.gif</i>). This can be modified using the <code>hToolGroup.setIcon</code> method, which currently [R2018b] expects a Java <code>ImageIcon</code> object as input. For example:</p>
<pre lang="matlab">
iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','reficon.gif');
jIcon = javax.swing.ImageIcon(iconFilename);
hToolGroup.setIcon(jIcon)
</pre>
<p>This icon should be set before the toolgroup window is shown (<code>hToolGroup.open</code>).<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_app_icon.gif" alt="Custom app window icon" title="Custom app window icon" width="400" height="230" /><figcaption class="wp-caption-text">Custom app window icon</figcaption></figure></center><br />
An odd caveat here is that the icon size needs to be 16&#215;16 &#8211; setting a larger icon results in the icon being ignored and the default Matlab membrane icon used. For example, if we try to set &#8216;boardicon.gif&#8217; (16&#215;17) instead of &#8216;reficon.gif&#8217; (16&#215;16) we&#8217;d get the default icon instead. If our icon is too large, we can resize it to 16&#215;16, as shown above:</p>
<pre lang="matlab">
% 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)
</pre>
<p>It&#8217;s natural to expect that <code>hToolGroup</code>, which is a pure-Matlab MCOS wrapper class, would have an <b>Icon</b> property that accepts <code>Icon</code> objects, just like for controls as described above. For some reason, this is not the case. It&#8217;s very easy to fix it though &#8211; after all, the <code>Icon</code> class is little more than an MCOS wrapper class for the underlying Java <code>ImageIcon</code> (not exactly, but close enough). Adapting <code>ToolGroup</code>&#8216;s code to accept an <code>Icon</code> 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&#215;16 limitation, or automatically resize icons to 16&#215;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 <code>setIcon(jImageIcon)</code> method and take care to send it the 16&#215;16 <code>ImageIcon</code> object that it expects.</p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss complex components, including button-group, drop-down, listbox, split-button, slider, popup form, gallery etc.<br />
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 &#8211; 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.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons">Matlab toolstrip – part 5 (icons)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
