<?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>Pure Matlab &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/pure-matlab/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>Reverting axes controls in figure toolbar</title>
		<link>https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=reverting-axes-controls-in-figure-toolbar</link>
					<comments>https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 23 Dec 2018 19:52:19 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8171</guid>

					<description><![CDATA[<p>In R2018b the axes controls were removed from the figure toolbar, but this can be reverted. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar">Reverting axes controls in figure toolbar</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/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I planned to post a new article in my toolstrip mini-series, but then I came across something that I believe has a much greater importance and impacts many more Matlab users: the change in Matlab R2018b&#8217;s figure toolbar, where the axes controls (zoom, pan, rotate etc.) were moved to be next to the axes, which remain hidden until you move your mouse over the axes. Many users have complained about this unexpected change in the user interface of such important data exploration functionality:<br />
<center><figure style="width: 402px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/R2018a_toolbar2.gif" alt="R2018a (standard toolbar)" title="R2018a (standard toolbar)" width="402" height="359" /><figcaption class="wp-caption-text">R2018a (standard toolbar)</figcaption></figure> <figure style="width: 402px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/R2018b_toolbar_animated.gif" alt="R2018b (integrated axes toolbar)" title="R2018b (integrated axes toolbar)" width="402" height="409" /><figcaption class="wp-caption-text">R2018b (integrated axes toolbar)</figcaption></figure> </center><br />
Luckily, we can revert the change, <span id="more-8171"></span> as was recently explained in <a href="https://www.mathworks.com/matlabcentral/answers/419036-what-happened-to-the-figure-toolbar-in-r2018b-why-is-it-an-axes-toolbar-how-can-i-put-the-buttons" rel="nofollow" target="_blank">this Answers thread</a>:</p>
<pre lang="matlab">
addToolbarExplorationButtons(gcf) % Add the axes controls back to the figure toolbar
hAxes.Toolbar.Visible = 'off'; % Hide the integrated axes toolbar
%or:
hAxes.Toolbar = []; % Remove the axes toolbar data
</pre>
<p>And if you want to make these changes permanent (in other words, so that they would happen automatically whenever you open a new figure or create a new axes), then add the following code snippet to your <i>startup.m</i> file (in your Matlab startup folder):</p>
<pre lang="matlab">
try %#ok
    if ~verLessThan('matlab','9.5')
        set(groot,'defaultFigureCreateFcn',@(fig,~)addToolbarExplorationButtons(fig));
        set(groot,'defaultAxesCreateFcn',  @(ax,~)set(ax.Toolbar,'Visible','off'));
    end
end
</pre>
<p>MathWorks is taking a lot of heat over this change, and I agree that it could have done a better job of communicating the workaround in placing it as settable configurations in the Preferences panel or elsewhere. Whenever an existing functionality is broken, certainly one as critical as the basic data-exploration controls, MathWorks should take extra care to enable and communicate workarounds and settable configurations that would enable users a gradual smooth transition. Having said this, MathWorks does communicate the workaround in its <a href="https://www.mathworks.com/help/matlab/release-notes.html#mw_f6529119-5b24-43ff-b030-c649b2bf9600" rel="nofollow" target="_blank">release notes</a> (I&#8217;m not sure whether this was there from the very beginning or only recently added, but it&#8217;s there now).<br />
In my opinion the change was *not* driven by the marketing guys (as was the Desktop change from toolbars to toolstrip back in 2012 which <a href="https://www.mathworks.com/matlabcentral/answers/48070-experiences-with-release-2012b" rel="nofollow" target="_blank">received similar backlash</a>, and despite the heated accusations in the above-mentioned Answers thread). Instead, I believe that this change was technically-driven, as part of MathWorks&#8217; ongoing infrastructure changes to make Matlab increasingly web-friendly. The goal is that eventually all the figure functionality could transition to Java-script -based uifigures, replacing the current (&#8220;legacy&#8221;) Java-based figures, and enabling Matlab to work remotely, via any browser-enabled device (mobiles included), and not be tied to desktop operating systems. In this respect, toolbars do not transition well to webpages/Javascript, but the integrated axes toolbar does. Like it or not, eventually all of Matlab&#8217;s figures will become web-enabled content, and this is simply one step in this long journey. There will surely be other painful steps along the way, but hopefully MathWorks would learn a lesson from this change, and would make the transition smoother in the future.<br />
Once you regain your composure and take the context into consideration, you might wish to let MathWorks know what you think of the toolbar redesign <a href="https://www.mathworks.com/matlabcentral/answers/419036-what-happened-to-the-figure-toolbar-in-r2018b-why-is-it-an-axes-toolbar-how-can-i-put-the-buttons" rel="nofollow" target="_blank">here</a>. Please don&#8217;t complain to me &#8211; I&#8217;m only the messenger&#8230;<br />
Merry Christmas everybody!<br />
p.s. One of the complaints against the new axes toolbar is that it hurts productivity by forcing users to wait for the toolbar to fade-in and become clickable. Apparently the axes toolbar has a hidden private property called FadeGroup that presumably controls the fade-in/out effect. This can be accessed as follows:</p>
<pre lang="matlab">hFadeGroup = struct(hAxes.Toolbar).FadeGroup  % hAxes is the axes handle</pre>
<p>I have not [yet] discovered if and how this object can be customized to remove the fade animation or control its duration, but perhaps some smart hack would discover and post the workaround here (or let me know in a private message that I would then publish anonymously).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar">Reverting axes controls in figure toolbar</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/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Plot legend customization</title>
		<link>https://undocumentedmatlab.com/articles/plot-legend-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plot-legend-customization</link>
					<comments>https://undocumentedmatlab.com/articles/plot-legend-customization#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 12 Jul 2018 14:11:40 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7744</guid>

					<description><![CDATA[<p>Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</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/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</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/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I <a href="/articles/plot-legend-title" target="_blank">explained</a> how we can use a couple of undocumented hidden properties of the legend in order to add a legend title (the legend object had no <b>Title</b> property back then &#8211; this was only added in a later Matlab release, perhaps as a result of my post). Today I will expand on that article by explaining the plot legend&#8217;s internal graphics hierarchy, how we can access each of these components, and then how this information could be used to customize the separate legend components. Note that the discussion today is only relevant for HG2 legends (i.e. R2014b or newer).<br />
Let&#8217;s start with a simple Matlab plot with a legend:</p>
<pre lang="matlab">
hold all;
hLine1 = plot(1:5);
hLine2 = plot(2:6);
hLegend = legend([hLine1,hLine2], 'Location','SouthEast');
hLegend.Title.String = 'MyLegend';
</pre>
<p><center><figure style="width: 210px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_1.gif" alt="Standard Matlab legend" title="Standard Matlab legend" width="210" height="145" /><figcaption class="wp-caption-text">Standard Matlab legend</figcaption></figure></center> This legend is composed of the following visible internal components, which can be customized separately:<br />
<center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center><br />
<span id="more-7744"></span><br />
<!-- center>[caption id="" align="aligncenter" width="150" caption="Matlab legend components"]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" />[/caption]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center --><br />
<!-- span class="alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></span --></p>
<table>
<tr>
<th align="left">Id in screenshot</th>
<th align="left">Accessed via</th>
<th align="left">Object type</th>
<th align="left">Description</th>
<th align="left">Important properties</th>
</tr>
<tr>
<td>1</td>
<td><code>hLegend.Title</code></td>
<td><code>Text</code></td>
<td>Title of the legend</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b>.</td>
</tr>
<tr>
<td>2</td>
<td><code>hLegend.TitleSeparator</code></td>
<td><code>LineStrip</code></td>
<td>Separator line between title and legend entries. Only appears when title is set.</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td>
</tr>
<tr>
<td>3</td>
<td><code>hLegend.BoxEdge</code></td>
<td><code>LineLoop</code></td>
<td>Box (border) line around the entire legend (including title)</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td</td>
</tr>
<tr>
<td>4</td>
<td><code>hLegend.EntryContainer.NodeChildren(2)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine1</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>5</td>
<td><code>hLegend.EntryContainer.NodeChildren(1)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine2</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>6</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Label</code></td>
<td><code>Text</code></td>
<td>Label of legend entry</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b></td>
</tr>
<tr>
<td>7</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Icon</code></td>
<td><code>LegendIcon</code></td>
<td>Icon/marker of legend entry</td>
<td><b>Visible</b>, <b>Transform.Children.Children</b> (<code>LineStrip</code> object)</td>
</tr>
</table>
<p>A pivotal object of the legend group are the <code>LegendEntry</code> items, one per legend row:</p>
<pre lang="matlab">
>> hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
>> get(hLegendEntry)
              Children: [3×1 Graphics]
                 Color: [0 0 0]
                 Dirty: 0
             FontAngle: 'normal'
              FontName: 'Helvetica'
              FontSize: 8
            FontWeight: 'normal'
      HandleVisibility: 'on'
               HitTest: 'on'
                  Icon: [1×1 LegendIcon]
                 Index: 0
           Interpreter: 'tex'
                 Label: [1×1 Text]
            LayoutInfo: [1×1 matlab.graphics.illustration.legend.ItemLayoutInfo]
                Legend: [1×1 Legend]
              Listener: [1×1 event.listener]
                Object: [1×1 Line]
               Overlay: [1×1 TriangleStrip]
          OverlayAlpha: 0.65
                Parent: [1×1 Group]
           PeerVisible: 'on'
         PickableParts: 'visible'
              Selected: 'off'
    SelectionHighlight: 'on'
               Visible: 'on'
       VisibleListener: [1×1 event.proplistener]
</pre>
<p>Each <code>LegendEntry</code> contains a back-reference to the original graphics object. In my example above, <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>, and <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>. Note how the default legend entries order is the reverse of the order of creation of the original graphics objects. Naturally, we can modify this order by creating the legend py passing it an array of handles that is ordered differently (see the documentation of the <i><b>legend</b></i> function).<br />
To get all the original graphic objects together, in a single array, we could use one of two mechanisms (note the different order of the returned objects):</p>
<pre lang="matlab">
% Alternative #1
>> [hLegend.EntryContainer.NodeChildren.Object]'
ans =
  2×1 Line array:
  Line    (data2)
  Line    (data1)
% Alternative #2
>> hLegend.PlotChildren
ans =
  2×1 Line array:
  Line    (data1)
  Line    (data2)
</pre>
<p>For some reason, accessing the displayed graphic line in <code>LegendEntry</code>&#8216;s <b>Icon</b> is not simple. For example, the <code>LineStrip</code> object that corresponds to <code>hLine2</code> can be gotten via:</p>
<pre lang="matlab">
hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
hLegendIconLine = hLegendEntry.Icon.Transform.Children.Children;  % a LineStrip object in our example
</pre>
<p>I assume that this was done to enable non-standard icons for patches and other complex objects (in which case the displayed icon would not necessarily be a <code>LineStrip</code> object). In the case of a line with markers, for example, <code>hLegendIconLine</code> would be an array of 2 objects: a <code>LineStrip</code> object and a separate <code>Marker</code> object. Still, I think that a direct reference in a <code>hLegend.EntryContainer.NodeChildren(1).Icon</code> property would have helped in 99% of all cases, so that we wouldn&#8217;t need to pass through the <code>Transform</code> object.<br />
Anyway, once we have this object reference(s), we can modify its/their properties. In the case of a <code>LineStrip</code> this includes <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8), and <b>VertexData</b> (which controls position/length):</p>
<pre lang="matlab">
>> get(hLegendIconLine(end))  % LineStrip
          AlignVertexCenters: 'on'
             AmbientStrength: 0.3
                ColorBinding: 'object'
                   ColorData: [4×1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
                     LineCap: 'none'
                    LineJoin: 'round'
                   LineStyle: 'solid'
                   LineWidth: 0.5
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1×1 Group]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: []
                     Texture: [0×0 GraphicsPlaceholder]
                  VertexData: [3×2 single]
               VertexIndices: []
                     Visible: 'on'
       WideLineRenderingHint: 'software'
</pre>
<p>and in the presense of markers:</p>
<pre lang="matlab">
>> get(hLegendIconLine(1))  % Marker
    EdgeColorBinding: 'object'
       EdgeColorData: [4×1 uint8]
       EdgeColorType: 'truecolor'
    FaceColorBinding: 'object'
       FaceColorData: []
       FaceColorType: 'truecolor'
    HandleVisibility: 'on'
             HitTest: 'off'
               Layer: 'middle'
           LineWidth: 0.5
              Parent: [1×1 Group]
       PickableParts: 'visible'
                Size: 6
         SizeBinding: 'object'
               Style: 'circle'
          VertexData: [3×1 single]
       VertexIndices: []
             Visible: 'on'
</pre>
<p>An additional undocumented legend property that is of interest is <b>ItemTokenSize</b>. This is a 2-element numeric array specifying the minimal size of the legend entries&#8217; icon and label. By default <code>hLegend.ItemTokenSize == [30,18]</code>, but we can either expand or shrink the icons/labels by setting different values. For example:</p>
<pre lang="matlab">hLegend.ItemTokenSize == [10,1];  % shrink legend icons and labels</pre>
<p>Note that regardless of the amount that we specify, the actual amount that will be used will be such that all legend labels appear.<br />
Fun: try playing with negative values for the icon and the label and see what happens 🙂<br />
Have you come across any other interesting undocumented aspect of Matlab legends? If so, then please share it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</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/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</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/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plot-legend-customization/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Sliders in Matlab GUI &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sliders-in-matlab-gui-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 05 Jul 2018 11:40:56 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7728</guid>

					<description><![CDATA[<p>Matlab contains a variety of ways to define/display slider controls in GUI windows. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</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/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Exactly 3 years ago I posted about various <a href="/articles/sliders-in-matlab-gui" target="_blank">alternatives for embedding sliders in Matlab GUI</a>. Today I will follow up on that post with a description of yet another undocumented builtin alternative &#8211; <i><b>controllib.widget.Slider</b></i>. A summary of the various alternatives can be seen in the following screenshot:<br />
<center><figure style="width: 344px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/sliders.gif" alt="Slider alternatives in Matlab GUI" title="Slider alternatives in Matlab GUI" width="344" height="303" /><figcaption class="wp-caption-text">Slider alternatives in Matlab GUI</figcaption></figure></center><br />
The <i><b>controllib.widget.Slider</b></i> component is a class in Matlab&#8217;s internal <code>controllib</code> package (last week I discussed a different utility function in this package, <a href="/articles/string-char-compatibility" target="_blank"><i><b>controllib.internal.util.hString2Char</b></i></a>).<br />
<span id="more-7728"></span><br />
<i><b>controllib.widget.Slider</b></i> accepts 3 input arguments: containing figure handle, position in pixels, and data values. For example:</p>
<pre lang="matlab">
>> hSlider = controllib.widget.Slider(gcf, [10,10,100,50], 5:25)
hSlider =
  Slider with properties:
        Data: [6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25]
       Index: 11
       Value: 15
    FontSize: 8
    Position: [10 10 100 50]
</pre>
<p>This creates an invisible axes at the specified figure location and displays graphic axes objects that provide the appearance of the slider. When you move the slider&#8217;s knob, or click its centerline or arrows (&#8220;Steppers&#8221;), the slider&#8217;s value changes accordingly.<br />
You can attach a callback function to the slider as follows:</p>
<pre lang="matlab">
myCallback = @(h,e) disp(h.Value);  % as an example
addlistener(hSlider, 'ValueChanged', myCallback);
</pre>
<p>Note that <i><b>controllib.widget.Slider</b></i> is based on pure-Matlab code and fully-supported functionality. The Matlab source code is available (<i>%matlabroot%/toolbox/shared/controllib/graphics/+controllib/+widget/Slider.m</i>) and quite readable. So while it does not actually work with the new web-based uifigures, is should be relatively easy to adapt the code so that this component could be displayed in such uifigures.<br />
Below is a script to recreate the screenshot above. Note the two alternative mechanisms for setting properties (Java setter-method notation, and HG set notation):</p>
<pre lang="matlab">
hFig = figure('Color','w');

% 1. controllib.widget.Slider
hSlider1 = controllib.widget.Slider(hFig, [10,10,100,50], 1:20);
hSlider1.Value = 12;

% 2. uicontrol
hSlider2 = uicontrol('style','slider', 'units','pixels', 'pos',[10,80,100,20], 'Min',0', 'Max',20, 'Value',12);

% 3. JScrollBar
jSlider3 = javaObjectEDT(javax.swing.JScrollBar);
jSlider3.setOrientation(jSlider3.HORIZONTAL);  % Java setter-method notation
set(jSlider3, 'VisibleAmount',1, 'Minimum',0, 'Maximum',20, 'Value',12);  % HG set notation
[hSlider3, hContainer3] = javacomponent(jSlider3, [10,130,100,20], hFig);

% 4. JSlider #1
jSlider4 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider4.setBackground(java.awt.Color.white);  % Java setter-method notation
set(jSlider4, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider4, hContainer4] = javacomponent(jSlider4, [10,180,100,30], hFig);

% 5. JSlider #2
jSlider5 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider5.setBackground(java.awt.Color.white);  % Java setter-method notation
jSlider5.setPaintTicks(true);
set(jSlider5, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider5, hContainer5] = javacomponent(jSlider5, [10,230,100,40], hFig);
</pre>
<p>For additional details regarding the other slider alternatives, please refer to <a href="/articles/sliders-in-matlab-gui" target="_blank">my earlier post</a> on this subject.<br />
Have you ever used another interesting utility or class in Matlab&#8217;s builtin packages? If so, please tell us about it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</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/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>String/char compatibility</title>
		<link>https://undocumentedmatlab.com/articles/string-char-compatibility?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=string-char-compatibility</link>
					<comments>https://undocumentedmatlab.com/articles/string-char-compatibility#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 28 Jun 2018 12:57:59 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7710</guid>

					<description><![CDATA[<p>Backward compatibility of strings in function inputs is a challenge, that can be assisted with an undocumented builtin  function. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/string-char-compatibility">String/char compatibility</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/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<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/ismembc-undocumented-helper-function" rel="bookmark" title="ismembc &#8211; undocumented helper function">ismembc &#8211; undocumented helper function </a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In numerous functions that I wrote over the years, some input arguments were expected to be strings in the old sense, i.e. char arrays for example, <code>'on'</code> or <code>'off'</code>. Matlab release R2016b introduced the concept of <a href="https://www.mathworks.com/help/matlab/characters-and-strings.html" rel="nofollow" target="_blank">string objects</a>, which can be created using the <i><b>string</b></i> function or [starting in R2017a] double quotes (<code>"on"</code>).<br />
The problem is that I have numerous functions that supported the old char-based strings but not the new string objects. If someone tries to enter a string object (<code>"on"</code>) as input to a function that expects a char-array (<code>'on'</code>), in many cases Matlab will error. This by itself is very unfortunate &#8211; I would have liked everything to be fully backward-compatible. But unfortunately this is not the case: MathWorks did invest effort in making the new strings backward-compatible to some degree (for example, graphic object property names/values and many internal functions that now accept either form as input). However, backward compatibility of strings is not 100% perfect.<br />
In such cases, the only solution is to make the function accept both forms (char-arrays and string objects), for example, by type-casting all such inputs as char-arrays using the builtin <i><b>char</b></i> function. If we do this at the top of our function, then the rest of the function can remain unchanged. For example:<br />
<span id="more-7710"></span></p>
<pre lang="matlab" highlight="2-4">
function test(stage)
   if isa(stage,'string')
      stage = char(stage);
   end
   % from this point onward, we don't need to worry about string inputs - any such strings will become plain-ol' char-arrays
   switch stage
      case 'stage 1', ...
      case 'stage 2', ...
      ...
   end
end
</pre>
<p>That was simple enough. But what if our function expects complex inputs (cell-arrays, structs etc.) that may contain strings in only some of their cells/fields?<br />
Luckily, Matlab contains an internal utility function that can help us: <i><b>controllib.internal.util.hString2Char</b></i>. This function, whose Matlab source-code is available (<i>%matlabroot%/toolbox/shared/controllib/general/+controllib/+internal/+util/hString2Char.m</i>) recursively scans the input value and converts any string object into the corresponding char-array, leaving all other data-types unchanged. For example:</p>
<pre lang="matlab">
>> controllib.internal.util.hString2Char({123, 'char-array', "a string"})
ans =
  1×3 cell array
    {[123]}    {'char-array'}    {'a string'}
>> controllib.internal.util.hString2Char(struct('a',"another string", 'b',pi))
ans =
  struct with fields:
    a: 'another string'
    b: 3.14159265358979
</pre>
<p>In order to keep our code working not just on recent releases (that support strings and <i><b>controllib.internal.util.hString2Char</b></i>) but also on older Matlab releases (where they did not exist), we simply wrap the call to <i><b>hString2Char</b></i> within a <i><b>try</b></i>&#8211;<i><b>catch</b></i> block. The adaptation of our function might then look as follows:</p>
<pre lang="matlab" highlight="2">
function test(varargin)
   try varargin = controllib.internal.util.hString2Char(varargin); catch, end
   % from this point onward, we don't need to worry about string inputs - any such strings will become plain-ol' char-arrays
   ...
end
</pre>
<p>Note that <i><b>controllib.internal.util.hString2Char</b></i> is a semi-documented function: it contains a readable internal help section (accessible via <code>help controllib.internal.util.hString2Char</code>), but not a doc-page. Nor is this function mentioned anywhere in Matlab&#8217;s official documentation. I think that this is a pity, because it&#8217;s such a useful little helper function.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/string-char-compatibility">String/char compatibility</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/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<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/ismembc-undocumented-helper-function" rel="bookmark" title="ismembc &#8211; undocumented helper function">ismembc &#8211; undocumented helper function </a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/string-char-compatibility/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
		<item>
		<title>Speeding-up builtin Matlab functions &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=speeding-up-builtin-matlab-functions-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 06 May 2018 16:26:19 +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=7533</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-2">Speeding-up builtin Matlab functions &#8211; part 2</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-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>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions" rel="bookmark" title="Undocumented mouse pointer functions">Undocumented mouse pointer functions </a> <small>Matlab contains several well-documented functions and properties for the mouse pointer. However, some very-useful functions have remained undocumented and unsupported. This post details their usage....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week <a href="/articles/speeding-up-builtin-matlab-functions-part-1" target="_blank">I showed</a> how we can speed-up built-in Matlab functions, by creating local copies of the relevant m-files and then optimizing them for improved speed using a variety of techniques.<span class="alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/speedometer3b3_200x200.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="200" height="200" /></span> Today I will show another example of such speed-up, this time of the Financial Toolbox&#8217;s <i><b><a href="https://www.mathworks.com/help/finance/maxdrawdown.html" rel="nofollow" target="_blank">maxdrawdown</a></b></i> function, which is <a href="https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp" rel="nofollow" target="_blank">widely used</a> to estimate the relative risk of a trading strategy or asset. One might think that such a basic indicator would be optimized for speed, but experience shows otherwise. In fact, this function turned out to be the main run-time performance hotspot for one of my clients. The vast majority of his code was optimized for speed, and he naturally assumed that the built-in Matlab functions were optimized as well, but this was not the case. Fortunately, I was able to create an equivalent version that was 30-40 times faster (!), and my client remains a loyal Matlab fan.<br />
In today&#8217;s post I will show how I achieved this speed-up, using different methods than the ones I showed last week. A combination of these techniques can be used in a wide range of other Matlab functions. Additional speed-up techniques can be found in other <a href="/articles/tag/performance" target="_blank">performance-related posts</a> on this website, as well in my book <a href="/books/matlab-performance" target="_blank"><b>Accelerating MATLAB Performance</b></a>.<br />
<span id="more-7533"></span></p>
<h3 id="profiling">Profiling</h3>
<p>As I explained last week, the first step in speeding up any function is to profile its current run-time behavior using Matlab&#8217;s builtin <a href="https://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html" rel="nofollow" target="_blank">Profiler tool</a>, which can either be started from the Matlab Editor toolstrip (&#8220;Run and Time&#8221;) or via the <a href="https://www.mathworks.com/help/matlab/ref/profile.html" rel="nofollow" target="_blank"><i><b>profile</b></i></a> function.<br />
The profile report for the client&#8217;s function showed that it had two separate performance hotspots:</p>
<ol>
<li>Code that checks the drawdown format (optional 2nd input argument) against a set of allowed formats</li>
<li>Main code section that iteratively loops over the data-series values to compute the maximal drawdown</li>
</ol>
<p>In order top optimize the code, I copied <i>%matlabroot%/toolbox/finance/finance/maxdrawdown.m</i> to a local folder on the Matlab path, renaming the file (and the function) <i>maxdrawdn</i>, in order to avoid conflict with the built-in version.</p>
<h3 id="strings">Optimizing input args pre-processing</h3>
<p>The main problem with the pre-processing of the optional format input argument is the string comparisons, which are being done even when the default format is used (which is by far the most common case). String comparison are often more expensive than numerical computations. Each comparison by itself is very short, but when <i><b>maxdrawdown</b></i> is run in a loop (as it often is), the run-time adds up.<br />
Here&#8217;s a snippet of the original code:</p>
<pre lang="matlab">
if nargin < 2 || isempty(Format)
    Format = 'return';
end
if ~ischar(Format) || size(Format,1) ~= 1
    error(message('finance:maxdrawdown:InvalidFormatType'));
end
choice = find(strncmpi(Format,{'return','arithmetic','geometric'},length(Format)));
if isempty(choice)
    error(message('finance:maxdrawdown:InvalidFormatValue'));
end
</pre>
<p>An equivalent code, which avoids any string processing in the common default case, is faster, simpler and more readable:</p>
<pre lang="matlab">
if nargin < 2 || isempty(Format)
    choice = 1;
elseif ~ischar(Format) || size(Format,1) ~= 1
    error(message('finance:maxdrawdown:InvalidFormatType'));
else
    choice = find(strncmpi(Format,{'return','arithmetic','geometric'},length(Format)));
    if isempty(choice)
        error(message('finance:maxdrawdown:InvalidFormatValue'));
    end
end
</pre>
<p>The general rule is that whenever you have a common case, you should check it first, avoiding unnecessary processing downstream. Moreover, for improved run-time performance (although not necessarily maintainability), it is generally preferable to work with numbers rather than strings (<code>choice</code> rather than <code>Format</code>, in our case).</p>
<h3 id="vectorizing">Vectorizing the main loop</h3>
<p>The main processing loop uses a very simple yet inefficient iterative loop. I assume that the code was originally developed this way in order to assist debugging and to ensure correctness, and that once it was ready nobody took the time to also optimize it for speed. It looks something like this:</p>
<pre lang="matlab">
MaxDD = zeros(1,N);
MaxDDIndex = ones(2,N);
...
if choice == 1   % 'return' format
    MaxData = Data(1,:);
    MaxIndex = ones(1,N);
    for i = 1:T
        MaxData = max(MaxData, Data(i,:));
        q = MaxData == Data(i,:);
        MaxIndex(1,q) = i;
        DD = (MaxData - Data(i,:)) ./ MaxData;
        if any(DD > MaxDD)
            p = DD > MaxDD;
            MaxDD(p) = DD(p);
            MaxDDIndex(1,p) = MaxIndex(p);
            MaxDDIndex(2,p) = i;
        end
    end
else             % 'arithmetic' or 'geometric' formats
    ...
</pre>
<p>This loop can relatively easily be vectorized, making the code much faster, and arguably also simpler, more readable, and more maintainable:</p>
<pre lang="matlab">
if choice == 3
    Data = log(Data);
end
MaxDDIndex = ones(2,N);
MaxData = cummax(Data);
MaxIndexes = find(MaxData==Data);
DD = MaxData - Data;
if choice == 1	% 'return' format
    DD = DD ./ MaxData;
end
MaxDD = cummax(DD);
MaxIndex2 = find(MaxDD==DD,1,'last');
MaxIndex1 = MaxIndexes(find(MaxIndexes<=MaxIndex2,1,'last'));
MaxDDIndex(1,:) = MaxIndex1;
MaxDDIndex(2,:) = MaxIndex2;
MaxDD = MaxDD(end,:);
</pre>
<p>Let's make a short run-time and accuracy check - we can see that we achieved a 31-fold speedup (YMMV), and received the exact same results:</p>
<pre lang="matlab">
>> data = rand(1,1e7);
>> tic, [MaxDD1, MaxDDIndex1] = maxdrawdown(data); toc  % builtin Matlab function
Elapsed time is 7.847140 seconds.
>> tic, [MaxDD2, MaxDDIndex2] = maxdrawdn(data); toc  % our optimized version
Elapsed time is 0.253130 seconds.
>> speedup = round(7.847140 / 0.253130)
speedup =
    31
>> isequal(MaxDD1,MaxDD2) && isequal(MaxDDIndex1,MaxDDIndex2)  % check accuracy
ans =
  logical
   1
</pre>
<p><b><u>Disclaimer</u></b>: The code above seems to work (quite well in fact) for a 1D data vector. You'd need to modify it a bit to handle 2D data - the returned maximal drawdown are still computed correctly but not the returned indices, due to their computation using the <i><b>find</b></i> function. This modification is left as an exercise for the reader...</p>
<h3 id="related">Related functions</h3>
<p>Very similar code could be used for the corresponding <i>maxdrawup</i> function. Although this function is used much less often than <i><b>maxdrawdown</b></i>, it is in fact widely used and very similar to <i><b>maxdrawdown</b></i>, so it is surprising that it is missing in the Financial Toolbox. Here is the corresponding code snippet:</p>
<pre lang="matlab">
% Code snippet for maxdrawup (similar to maxdrawdn)
MaxDUIndex = ones(2,N);
MinData = cummin(Data);
MinIndexes = find(MinData==Data);
DU = Data - MinData;
if choice == 1	% 'return' format
    DU = DU ./ MinData;
end
MaxDU = cummax(DU);
MaxIndex = find(MaxDD==DD,1,'last');
MinIndex = MinIndexes(find(MinIndexes<=MaxIndex,1,'last'));
MaxDUIndex(1,:) = MinIndex;
MaxDUIndex(2,:) = MaxIndex;
MaxDU = MaxDU(end,:);
</pre>
<p>Similar vectorization could be applied to the <i><b><a href="https://www.mathworks.com/help/finance/emaxdrawdown.html" rel="nofollow" target="_blank">emaxdrawdown</a></b></i> function. This too is left as an exercise for the reader...</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 sometimes takes a back-seat. Make no mistake about this: code accuracy is almost always more important than speed (an exception are cases where some accuracy may be sacrificed for improved run-time performance). So I'm not complaining about the current state of affairs.<br />
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 limiting the target accuracy, etc.), or optimize these functions in our own local copy, as I've shown last week and 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.<br />
<a href="/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. I will be visiting Boston and New York in early June and would be happy to meet you in person to discuss your specific needs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2">Speeding-up builtin Matlab functions &#8211; part 2</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-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>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions" rel="bookmark" title="Undocumented mouse pointer functions">Undocumented mouse pointer functions </a> <small>Matlab contains several well-documented functions and properties for the mouse pointer. However, some very-useful functions have remained undocumented and unsupported. This post details their usage....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
	</channel>
</rss>
