<?xml version="1.0"?>
<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007" xmlns:atom="http://www.w3.org/2005/Atom">
   <channel>
      <title>MATLAB Central Blogs</title>
      <description>Pipes Output</description>
      <link>http://pipes.yahoo.com/pipes/pipe.info?_id=e72c9f53f10ba5cad505dbbed8d501cb</link>
      <atom:link rel="next" href="http://pipes.yahoo.com/pipes/pipe.run?_id=e72c9f53f10ba5cad505dbbed8d501cb&amp;_render=rss&amp;page=2"/>
      <pubDate>Tue, 18 Jun 2013 04:53:47 +0000</pubDate>
      <generator>http://pipes.yahoo.com/pipes/</generator>
      <item>
         <title>Lake Arrowhead Coauthor Graph Photos</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/terphDo6cL4/</link>
         <description>Nick Trefethen has framed the original flip chart that I described in my Lake Arrowhead Coauthor Graph blog earlier this week and has it on the wall of his office at Oxford University. His colleage Nick Hale has taken these photos. (The faded name in the cell at the lower left just northwest of mine [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=699</guid>
         <pubDate>Sat, 15 Jun 2013 18:09:35 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Nick Trefethen has framed the original flip chart that I described in my <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/cleve/2013/06/10/lake-arrowhead-coauthor-graph/">Lake Arrowhead Coauthor Graph</a> blog earlier this week and has it on the wall of his office at Oxford University.  His colleage Nick Hale has taken these photos.  (The faded name in the cell at the lower left just northwest of mine is Tony Chan.)</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/mg4858.jpg" alt=""> </p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/mg4869.jpg" alt=""> </p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/mg4872.jpg" alt=""> </p><p>Let's repeat John Gilbert's social network analysis of this data.</p><pre class="codeinput">load <span class="string">housegraph</span>
r = symrcm(A(2:end,2:end));
prcm = [1 r+1];
drawit
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/arrowhead_photos_01.png" alt=""> <p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/terphDo6cL4" height="1" width="1"/>]]></content:encoded>
         <category>History</category>
      </item>
      <item>
         <title>Combinatorics</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/CCNdS4lf4rQ/</link>
         <description>I was asked recently how to generate all the combinations from two possible outcomes. It reminded me of a recent post on Flowing Data about the sum of two dice. This is a nice little function, combvec, that not everyone knows about.</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1131</guid>
         <pubDate>Fri, 14 Jun 2013 13:13:34 +0000</pubDate>
         <content:encoded><![CDATA[I was asked recently how to generate all the combinations from two possible outcomes.  It reminded me of a <a rel="nofollow" target="_blank" href="http://www.datagenetics.com/blog/june12013/index.html">recent post on Flowing Data</a> about the sum of two dice.

This is a nice little function, combvec, that not everyone knows about.

<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate309" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/CCNdS4lf4rQ" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Change Your Mask, Change Your Look!</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/5Vc4VdE-Tic/</link>
         <description>Greg's pick this week is Dynamic Mask Field Changing From Selected Pulldown Menu by David Manegold.Ever wanted to change how your Simulink block mask appears depending on certain parameter conditions of the mask? David has a nice example.I selected this submission because it demonstrates an advanced Simulink development technique in a straight-forward manner.ContentsChange Thy Appearance, [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4628</guid>
         <pubDate>Fri, 14 Jun 2013 13:00:53 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/32620">Greg's</a> pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/36018-dynamic-mask-field-changing-from-selected-pulldown-menu">Dynamic Mask Field Changing From Selected Pulldown Menu</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/142770">David Manegold</a>.</p><p>Ever wanted to change how your Simulink block mask appears depending on certain parameter conditions of the mask?  David has a nice example.</p><p>I selected this submission because it demonstrates an advanced Simulink development technique in a straight-forward manner.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#0d5a9004-ad3d-4549-993a-3542907d813f">Change Thy Appearance, and Quick!</a></li><li><a rel="nofollow" href="#b67db82d-392e-4da2-8c88-2eebbc28bd30">What Doest Thou Hide Behind the Mask?</a></li><li><a rel="nofollow" href="#83f28952-8b24-42c9-9ccc-b6f39b628847">Mask, Reveal Thy Magic!</a></li></ul></div><h4>Change Thy Appearance, and Quick!<a rel="nofollow" name="0d5a9004-ad3d-4549-993a-3542907d813f"></a></h4><p>Masks have the ability to change what parameters are available depending on which parameters have been selected. In this example, if the value of the "Selector" parameters is "A" then the set of parameters associated with "A" appears in the mask. But if you select "C" instead, then a new set of parameters is displayed. Also option "C" has a subset of parameters that can also change depending on what you choose for "C alt field type 3".</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/greg/Dynamic_Masks/maskSelectorA.png" alt=""> </p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/greg/Dynamic_Masks/maskSelectorC.png" alt=""> </p><h4>What Doest Thou Hide Behind the Mask?<a rel="nofollow" name="b67db82d-392e-4da2-8c88-2eebbc28bd30"></a></h4><p>The mask is a dialog box that appears when you double-click on a block in Simulink. It provides a means to enter parameters for a Simulink block or subsystem to affect its functionality. This means you can have two instances of a block or subsystem in the same model that exhibit different behavior depending on the parameter values entered in the mask. You can create your own masks for subsystems or blocks by right-clicking on the block and select</p><p><i>Mask -&gt; Create mask...</i></p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/greg/Dynamic_Masks/createMask.png" alt=""> </p><p>For more information on creating masks see <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/create-mask-documentation.html">Create Mask Documentation</a>.</p><h4>Mask, Reveal Thy Magic!<a rel="nofollow" name="83f28952-8b24-42c9-9ccc-b6f39b628847"></a></h4><p>David leverages two capabilities to enable this behavior in a block mask.</p><div><ol><li>Mask parameter callback function</li><li>The MaskVisibilities property of the block</li></ol></div><p>In the mask editor, if you select a parameter to edit, you can populate the "Dialog callback" field to execute MATLAB functions that get executed when the parameter is changed in the block mask.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/greg/Dynamic_Masks/maskParameterCallback.png" alt=""> </p><p>Within the callback function ChangeMaskFields, David changes the visibility of specific parameters based on the value of the "Selector" parameter. He defaults the parameter visibilities to "off":</p><pre class="language-matlab">[M{:}]=deal(<span class="string">'off'</span>);
</pre><p>except for the first parameter (which is the Selector parameter):</p><pre class="language-matlab">M{1}=<span class="string">'on'</span>;
</pre><p>Then he enables specific parameters based on the value of the "Selector" parameter:</p><pre class="language-matlab">[M{i0:ie}]=deal(<span class="string">'on'</span>);
</pre><p><b>Comments</b></p><p>If you would like to leave any comments regarding this post, please click <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4628#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div> Create mask..._
%  
% &lt; &gt;
% 
% For more information on creating masks see
%
 .
% 
%% Mask, Reveal Thy Magic!
% David leverages two capabilities to enable this behavior in a block mask.
%
% # Mask parameter callback function
% # The MaskVisibilities property of the block
% 
% In the mask editor, if you select a parameter to edit, you can populate
% the "Dialog callback" field to execute MATLAB functions that get executed
% when the parameter is changed in the block mask.
% 
% 
% &lt; &gt;
% 
% Within the callback function ChangeMaskFields, David changes the
% visibility of specific parameters based on the value of the "Selector"
% parameter. He defaults the parameter visibilities to "off":
% 
%   [M{:}]=deal('off');
% 
% except for the first parameter (which is the Selector parameter):
% 
%   M{1}='on';
% 
% Then he enables specific parameters based on the value of the "Selector"
% parameter:
%
%   [M{i0:ie}]=deal('on');
% 
%%
% *Comments*
%
% If you would like to leave any comments regarding this post, please click 
% . 


##### SOURCE END ##### 8d643d9cf06049f496e991a2a37dfd69
--&gt;<img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/5Vc4VdE-Tic" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Printing Math</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/S7Qf24P3-k0/</link>
         <description>What is this shape? Can you guess? It may look like a dirty sock, but I promise that it&amp;#8217;s not. Paul Kassebaum, who recently told us about the Battlebots competition, made this with a 3D printer. One of the cool things about 3D printing is that you can start with a shape that exists only [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2263</guid>
         <pubDate>Thu, 13 Jun 2013 22:19:20 +0000</pubDate>
         <content:encoded><![CDATA[<p>What is this shape? Can you guess?</p>
<p><img src="http://blogs.mathworks.com/community/files/shape1.jpg" alt="shape1" width="500" height="314" class="alignnone size-full wp-image-2264"/></p>
<p>It may look like a dirty sock, but I promise that it&#8217;s not.</p>
<p>Paul Kassebaum, who recently told us about the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2013/04/04/design-challenge-autonomous-battlebots-with-simulink/">Battlebots competition</a>, made this with a 3D printer. One of the cool things about 3D printing is that you can start with a shape that exists only in an abstract mathematical sense, and then you can extrude it onto the palm of your hand.</p>
<p>So here&#8217;s a hint. The shape above is related to another shape that Paul printed.</p>
<p><img src="http://blogs.mathworks.com/community/files/shape2.png" alt="shape2" width="500" height="389" class="alignnone size-full wp-image-2265"/></p>
<p>Maybe you already figured that out. But what is the relationship between the two shapes? Over the next couple of posts, Paul is going to tell us the story of these two shapes: how they were generated as abstract objects, and how they were given physical form in the real world.<a rel="nofollow">
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/S7Qf24P3-k0" height="1" width="1"/></a>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Making a line visible over an image in MATLAB</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/zosI0qyMrZ0/</link>
         <description>It can be difficult to see a line that is drawn over an image. The line is often lost in the background colors. That is why cursors are colored as they are, so that they are visible on any background. I demonstrate some code that makes a line more visible with the same technique. function [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1123</guid>
         <pubDate>Mon, 10 Jun 2013 19:12:57 +0000</pubDate>
         <content:encoded><![CDATA[It can be difficult to see a line that is drawn over an image.  The line is often lost in the background colors.  That is why cursors are colored as they are, so that they are visible on any background.  I demonstrate some code that makes a line more visible with the same technique.

<code><pre>
function h = cursorLine(x,y,innerThickness, outerThickness)

if nargin == 2
    innerThickness = 2;
    outerThickness = 4;
end

h.thick = line(x,y);
h.thin  = line(x,y);

set(h.thick, 'color', [1 1 1]);
set(h.thin , 'color', [0 0 0]);

set(h.thick, 'linewidth', outerThickness);
set(h.thin , 'linewidth', innerThickness);
</pre></code>

<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate308" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/zosI0qyMrZ0" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Lake Arrowhead Coauthor Graph</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/0X1BljbESUc/</link>
         <description>Twenty years ago, during the Householder Symposium at the Lake Arrowhead conference center , John Gilbert carried out one of the world's first computational social network analyses.ContentsHouseholder XIIJohn Gilbert RemembersCoauthor MatrixMost ProlificReorder the AuthorsReverse Cuthill McKeeCoauthor GraphMy ConnectivityArrowheadHouseholder XIITwenty years ago, in June, 1993, the UCLA Lake Arrowhead Conference Center in the San Bernardino Mountains, [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=688</guid>
         <pubDate>Mon, 10 Jun 2013 17:48:46 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Twenty years ago, during the Householder Symposium at the Lake Arrowhead conference center , John Gilbert carried out one of the world's first computational social network analyses.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#9f7001e9-5ac7-4ea5-b959-7877b19e22ac">Householder XII</a></li><li><a rel="nofollow" href="#1cc01ee1-1d78-45f9-b93e-c829caa37255">John Gilbert Remembers</a></li><li><a rel="nofollow" href="#71394432-39d6-4743-8887-1652bb678be0">Coauthor Matrix</a></li><li><a rel="nofollow" href="#795aad32-9a4f-4652-98c6-9036487d5300">Most Prolific</a></li><li><a rel="nofollow" href="#20fe731d-494e-40bd-bb5e-2996b68ed295">Reorder the Authors</a></li><li><a rel="nofollow" href="#9a7d7140-bf22-471a-97da-3fdeed08f7f7">Reverse Cuthill McKee</a></li><li><a rel="nofollow" href="#95747658-b5ad-4892-8675-c59edbb8f193">Coauthor Graph</a></li><li><a rel="nofollow" href="#6d8175a8-b5fd-40f0-bdf9-30e37b577c00">My Connectivity</a></li><li><a rel="nofollow" href="#452e0423-b532-4021-a9fa-5af47cc8de03">Arrowhead</a></li></ul></div><h4>Householder XII<a rel="nofollow" name="9f7001e9-5ac7-4ea5-b959-7877b19e22ac"></a></h4><p>Twenty years ago, in June, 1993, the UCLA Lake Arrowhead Conference Center in the San Bernardino Mountains, 90 miles east of Los Angeles, was the site of the Householder XII Symposium on Numerical Linear Algebra, organized by Gene Golub and Tony Chan.</p><h4>John Gilbert Remembers<a rel="nofollow" name="1cc01ee1-1d78-45f9-b93e-c829caa37255"></a></h4><p>John Gilbert is now a Professor at U. C. Santa Barbara. A couple of years before the Lake Arrowhead meeting, in 1990 and 1991, John, Rob Schreiber, and I had developed the initial implementation of sparse matrices in MATLAB.  John's research activities now include sparse matrix techniques for graph and social network problems.  He recently wrote to me in an email, "It was at Householder 1993 in Lake Arrowhead that we used MATLAB's sparse matrices to do the first computational social network analysis I ever saw."</p><p>John used to be at PARC, the Xerox Palo Alto Research Center.  A file containing his work from 1993 is still archived at PARC, <a rel="nofollow" target="_blank" href="ftp://ftp.parc.xerox.com/pub/gilbert/graph.html">&lt;ftp://ftp.parc.xerox.com/pub/gilbert/graph.html</a>&gt;. Most of this blog post is derived from that archived work.</p><h4>Coauthor Matrix<a rel="nofollow" name="71394432-39d6-4743-8887-1652bb678be0"></a></h4><p>Nick Trefethen posted a flip chart with Gene Golub's name in the center. He invited everyone present to add their name to the chart and draw lines connecting their name with the names of all their coauthors.  The diagram grew denser throughout the week.  At the end it was a graph with 104 vertices (or people) and 211 edges. We entered the names and coauthor connections into MATLAB, creating an adjacency matrix <tt>A</tt>.  Let's retrieve the names and matrix as they are stored in the PARC archive.</p><pre class="codeinput">load <span class="string">housegraph</span>
size(A)
</pre><pre class="codeoutput">ans =
   104   104
</pre><p>The matrix <tt>A</tt> is 104-by-104 and symmetric. Elements <tt>A(i,j)</tt> and <tt>A(j,i)</tt> are both equal to one if <tt>i</tt> and <tt>j</tt> are the indices of coauthors and equal to zero otherwise.  Most of the elements are zero because most pairs of attendees are not coauthors. So the matrix is sparse.  In fact, the sparsity, the fraction of nonzero elements, is less that five percent.</p><pre class="codeinput">format <span class="string">short</span>
sparsity = nnz(A)/prod(size(A))
</pre><pre class="codeoutput">sparsity =
    0.0486
</pre><p>Here is a picture of the matrix, a <tt>spy</tt> plot that shows the location of the nonzeros, with Golub in the first column and the other authors in the fairly arbitrary order in which they appeared on Trefethen's flip chart.</p><pre class="codeinput">spy(A);
title(<span class="string">'Coauthor matrix'</span>);
snapnow
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/arrowhead_01.png" alt=""> <h4>Most Prolific<a rel="nofollow" name="795aad32-9a4f-4652-98c6-9036487d5300"></a></h4><p>As the adjacency matrix is loaded from the archive, the most prolific coauthor is already in the first column. It was not a surprise to those of us at the conference to find that the most prolific coauthor is Gene Golub.</p><pre class="codeinput">m = find(sum(A) == max(sum(A)))
name(m,:)
</pre><pre class="codeoutput">m =
     1
ans =
Golub               
</pre><h4>Reorder the Authors<a rel="nofollow" name="20fe731d-494e-40bd-bb5e-2996b68ed295"></a></h4><p>We want to create a circular plot with Golub in the center, the other authors around the circumference, and edges connecting the coauthors. If we were to place the authors around the circumference in the order we retrieve them from the chart, the edges would cross the circle pretty much randomly.  We want to rearrange the authors so that the coauthor connections are as close as possible to the circumference of the circle. This corresponds to a symmetric permutation of the matrix that minimizes, or at least reduces, its bandwidth.</p><h4>Reverse Cuthill McKee<a rel="nofollow" name="9a7d7140-bf22-471a-97da-3fdeed08f7f7"></a></h4><p>The Reverse Cuthill McKee algorithm is the only algorithm I know that is usually used backwards.  In 1969 Elizabeth Cuthill and J. McKee described a heuristic for reordering the rows and columns of a matrix to reduce its bandwidth.  In 1991 J. Alan George pointed out that reversing the Cuthill McKee ordering almost always leads to fewer arithmetic operations in Gaussian elimination.  The algorithm applies to symmetric matrices, so MATLAB has a <tt>symrcm</tt> function, but no <tt>symcm</tt> function. Here we are reducing bandwidth; we are not doing any arithmetic, so the difference between Cuthill-McKee and Reverse-Cuthill-McKee is purely cosmetic.</p><h4>Coauthor Graph<a rel="nofollow" name="95747658-b5ad-4892-8675-c59edbb8f193"></a></h4><pre class="codeinput">r = symrcm(A(2:end,2:end));
prcm = [1 r+1];
spy(A(prcm,prcm))
title(<span class="string">'Coauthor matrix with reduced bandwidth'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/arrowhead_02.png" alt=""> <p>Now we are were able to actually plot the coauthor graph.  Fortunately, plotting text at arbitrary angles had just been provided in MATLAB.</p><pre class="codeinput">drawit;
snapnow
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/arrowhead_03.png" alt=""> <h4>My Connectivity<a rel="nofollow" name="6d8175a8-b5fd-40f0-bdf9-30e37b577c00"></a></h4><p>You will find my name at about 5 o'clock on the coauthor graph.  There is no edge connecting me to Golub because Gene and I were (not yet) coauthors. But how many coauthors do we have in common? Taking the second power of the connectivity matrix gives the paths of length two.</p><pre class="codeinput">A2 = A^2;
count = A2(Golub,Moler)
</pre><pre class="codeoutput">count =
   (1,1)        2
</pre><p>And who are those common coauthors?</p><pre class="codeinput">twos = name( find ( A(:,Golub) .* A(:,Moler) ), : )
</pre><pre class="codeoutput">twos =
Wilkinson           
VanLoan             
</pre><h4>Arrowhead<a rel="nofollow" name="452e0423-b532-4021-a9fa-5af47cc8de03"></a></h4><p>Finally, we find a minimum degree reordering of the matrix and discover its true nature as, of course, ....</p><pre class="codeinput">pmd = amd(A);
spy(A(pmd,pmd))
title(<span class="string">'The (Lake) Arrowhead Matrix'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/arrowhead_04.png" alt=""> <p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/0X1BljbESUc" height="1" width="1"/>]]></content:encoded>
         <category>History</category>
      </item>
      <item>
         <title>From Symbolic Differential Equations to Their Numeric Solution</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/15UdnsWsxu8/</link>
         <description>Once more, I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years mainly working on features for the Symbolic Math Toolbox. He has a background in mathematics and computer science and already contributed to my blog in the past.ContentsIn a Nutshell: What Is [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=704</guid>
         <pubDate>Mon, 10 Jun 2013 14:16:24 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Once more, I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years mainly working on features for the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic">Symbolic Math Toolbox</a>. He has a background in mathematics and computer science and already contributed to my blog in the past.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#49aefc25-b542-4261-b085-85c7e6c19ec4">In a Nutshell: What Is This Article About?</a></li><li><a rel="nofollow" href="#12eed599-056f-4291-a9cc-4ba7f9a03c3f">Defining a Differential Equation in Symbolic Form</a></li><li><a rel="nofollow" href="#9ee15bce-87b2-4719-8473-95374cf15dc9">From Scalar ODE to Coupled First-Order System</a></li><li><a rel="nofollow" href="#7f81baed-cf96-416f-bfd4-15926c98735e">From Coupled First-Order System to Function Handle Representation</a></li><li><a rel="nofollow" href="#e6e9eb80-9bc0-4cf7-9e3a-a396fc41bb42">From Function Handle Representation to Numeric Solution</a></li><li><a rel="nofollow" href="#a1a41aee-1694-4025-85ac-d2b2dff0b486">Have You Tried This Worklfow?</a></li></ul></div><h4>In a Nutshell: What Is This Article About?<a rel="nofollow" name="49aefc25-b542-4261-b085-85c7e6c19ec4"></a></h4><p>In the article <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2010/04/08/odes-from-symbolic-to-numeric-code">ODEs, from Symbolic to Numeric Code</a>, Loren demonstrated how you can</p><div><ul><li>Compute a symbolic solution of an ordinary differential equation (ODE) using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/dsolve.html"><tt>dsolve</tt></a></li><li>Convert the symbolic solution to a MATLAB function handle using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/matlabfunction.html"><tt>matlabFunction</tt></a></li><li>Plot the solution using MATLAB's <a rel="nofollow" target="_blank" href="http://www.mathworks.de/de/help/matlab/ref/plot.html"><tt>plot</tt></a>.</li></ul></div><p>In this article, we consider a slightly different scenario. Suppose that we have defined an ODE. First, we try to solve it symbolically. But we find that the symbolic ODE solver cannot find a closed form solution (something which is likely to happen, because only particular classes of ODEs can be solved in closed symbolic form).</p><p>Since we cannot solve the ODE symbolically, we must switch to a numeric ODE solver. But numeric solvers require a particular form and type of arguments, which often differ from the arguments of a symbolic solver. Symbolic solvers require a scalar symbolic (= "textbook-like") representation of an ODE. Numeric solvers usually require them to be transformed to a coupled first-order system.</p><p>This article demonstrates the following workflow of transforming a symbolic representation of an ODE to a form accepted by the MATLAB numeric ODE solver <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/techdoc/ref/ode45.html"><tt>ode45</tt></a>.</p><div><ul><li>Define an ODE in a symbolic form using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/symfun.html">symbolic functions</a></li><li>Convert it to a coupled first-order system using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/odetovectorfield.html"><tt>odeToVectorField</tt></a></li><li>Create a function handle for the coupled first-order system using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/matlabfunction.html"><tt>matlabFunction</tt></a></li><li>Solve the differential equation numerically using the MATLAB numeric ODE solver <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/techdoc/ref/ode45.html"><tt>ode45</tt></a></li><li>Plot the solution using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/techdoc/ref/plot.html"><tt>plot</tt></a>.</li></ul></div><h4>Defining a Differential Equation in Symbolic Form<a rel="nofollow" name="12eed599-056f-4291-a9cc-4ba7f9a03c3f"></a></h4><p>We start with the second-order non-linear ODE with two given initial values:</p><p>$$y'' = (y - y^2) &#92;cdot y' - y, &#92;qquad y = y(t), &#92;qquad y(0) = 2, &#92;qquad y'(0) = 0.$$</p><p>We define it in a symbolic form using a symbolic function <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/symfun.html">symfun</a> <tt>y(t)</tt>:</p><pre class="codeinput">syms <span class="string">y(t)</span>;
ode = diff(y,2) == (y-y^2)*diff(y) - y;
</pre><p>When trying to compute a solution of this ODE using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/dsolve.html"><tt>dsolve</tt></a>, we see that the symbolic ODE solver does not find an explicit closed form solution:</p><pre class="codeinput">dsolve(ode)
</pre><pre class="codeoutput">Warning: Explicit solution could not be found. 
ans =
[ empty sym ]
</pre><p>Adding the initial values does not help:</p><pre class="codeinput">Dy = diff(y); dsolve(ode,y(0) == 2,Dy(0) == 0)
</pre><pre class="codeoutput">Warning: Explicit solution could not be found. 
ans =
[ empty sym ]
</pre><p>So we must use a numeric ODE solver to be able to plot the solution. But before we can convert the symbolic form of the ODE to a function handle accepted by <tt>ode45</tt>, we must convert the scalar form of the ODE to a coupled first-order ODE system.</p><h4>From Scalar ODE to Coupled First-Order System<a rel="nofollow" name="9ee15bce-87b2-4719-8473-95374cf15dc9"></a></h4><p>The Symbolic Math Toolbox function <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/odetovectorfield.html"><tt>odeToVectorField</tt></a> converts a scalar ODE to a first-order ODE system:</p><pre class="codeinput">V = odeToVectorField(ode)
</pre><pre class="codeoutput">V =
                          Y[2]
 - (Y[1]^2 - Y[1])*Y[2] - Y[1]
</pre><p>For details about the algorithm used to convert a general n-th order scalar ODE to a first-order coupled ODE system, see the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/odetovectorfield.html"><tt>odeToVectorField</tt></a> documentation page.</p><p>The next step is to convert the system representation <tt>V</tt> of the ODE to a function handle accepted by <tt>ode45</tt>.</p><h4>From Coupled First-Order System to Function Handle Representation<a rel="nofollow" name="7f81baed-cf96-416f-bfd4-15926c98735e"></a></h4><p>To convert the expression <tt>V</tt> to a MATLAB <a rel="nofollow" target="_blank" href="http://www.mathworks.de/de/help/matlab/ref/function_handle.html">function handle</a> we use <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/matlabfunction.html"><tt>matlabFunction</tt></a>:</p><pre class="codeinput">F = matlabFunction(V,<span class="string">'vars'</span>,{<span class="string">'t'</span>,<span class="string">'Y'</span>})
</pre><pre class="codeoutput">F = 
    @(t,Y)[Y(2);-(Y(1).^2-Y(1)).*Y(2)-Y(1)]
</pre><p>We are almost done. We only need to call the numeric ODE solver <tt>ode45</tt> for the function handle <tt>F</tt>, and then plot the result.</p><h4>From Function Handle Representation to Numeric Solution<a rel="nofollow" name="e6e9eb80-9bc0-4cf7-9e3a-a396fc41bb42"></a></h4><p>Now we solve the differential equation converted to the function handle <tt>F</tt>:</p><pre class="codeinput">sol = ode45(F,[0 10],[2 0]);
</pre><p>Here, <tt>[0 10]</tt> lets us compute the numerical solution on the interval from <tt>0</tt> to <tt>10</tt>. Another additional parameter, <tt>[2 0]</tt>, corresponds to the initial values: $y(0) = 2$ and $y'(0) = 0$.</p><p>Before plotting the solution, we use <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/techdoc/ref/linspace.html"><tt>linspace</tt></a> to create 100 points in the interval <tt>[0,10]</tt> and <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/techdoc/ref/deval.html"><tt>deval</tt></a> to evaluate the solution at each of these points:</p><pre class="codeinput">x = linspace(0,10,100);
y = deval(sol,x,1);
</pre><p>Now we plot the solution:</p><pre class="codeinput">plot(x,y)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/SymbolicNumericWorkflow_01.png" alt=""> <h4>Have You Tried This Worklfow?<a rel="nofollow" name="a1a41aee-1694-4025-85ac-d2b2dff0b486"></a></h4><p>Have you tried using <tt>odeToVectorField</tt> and <tt>matlabFunction</tt> or creating symbolic functions with <tt>symfun</tt>? Let me know <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=704#respond">here</a>. If you find Kai's article interesting, take a look at his other posts on my blog:</p><div><ul><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2011/10/25/simplifying-symbolic-results">Simplifying Symbolic Results</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2012/07/27/using-symbolic-equations-and-symbolic-functions-in-matlab">Using Symbolic Equations And Symbolic Functions In MATLAB</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2013/04/26/using-symbolic-math-toolbox-to-compute-area-moments-of-inertia">Using Symbolic Math Toolbox to Compute Area Moments of Inertia</a></li></ul></div><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/15UdnsWsxu8" height="1" width="1"/>]]></content:encoded>
         <category>Symbolic</category>
      </item>
      <item>
         <title>Plot (real) Big</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/JNdzQdWzpQc/</link>
         <description>Jiro's pick this week is Plot (Big) by my co-worker Tucker McClure.&quot;Big data&quot;That seems to be the buzz lately. But when people say &quot;big data&quot;, it could mean a lot of things.Storing big dataLoading big dataSaving big dataVisualizing big dataAnalyzing big dataManipulating big dataetc.This entry by Tucker is all about &quot;visualizing&quot; big data. This was [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4613</guid>
         <pubDate>Fri, 07 Jun 2013 13:00:31 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/15007">Jiro</a>'s pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/40790">Plot (Big)</a> by my co-worker <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/225094">Tucker McClure</a>.</p><p>"Big data"</p><p>That seems to be the buzz lately. But when people say "big data", it could mean a lot of things.</p><div><ul><li>Storing big data</li><li>Loading big data</li><li>Saving big data</li><li>Visualizing big data</li><li>Analyzing big data</li><li>Manipulating big data</li><li>etc.</li></ul></div><p>This entry by Tucker is all about "visualizing" big data. This was a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2013/05/31/nominate-your-favorite-new-file-exchange-submission/#comment-22726">recommendation</a> from another one of my co-workers, Adam.</p><p><b>Visualizing Big Datasets</b></p><p>One of the issues with visualizing big datasets is that you have so many points displayed on the screen, and exploring (zooming and panning) may become sluggish. It's nice that you have all of those points available, but your screen has only so many pixels, and you don't get additional information by putting more points than what the screen is able to display.</p><p>So what can you do? Well, you can choose to display fewer points, just enough to give you a sense of what the dataset looks like. But then, you'd like to be able to see the details if you zoom in. It's sort of like Google Maps, for instance; when you're zoomed out, you see a rough outline of the city and some major highways. When you zoom in, you start to see some of the local roads.</p><p>Can we do something like this with MATLAB plots? I created something like that for <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/15850">line plots</a>. <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/videos/">Doug</a> even wrote a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2007/08/06/downsampling-data-for-faster-plotting/">Pick</a> on it. However, that was more of a proof-of-concept that worked for only 2D line plots. Tucker went all the way. He implemented this using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/object-oriented-programming.html">MATLAB Classes</a>, and it could be applied to other plot types. You could also call it with additional arguments that you might pass into these plotting commands. Here are some additional things I like about Tucker's entry:</p><div><ul><li>Nice documentation for the class</li><li>An extensive set of examples</li><li>A convenience function <tt>reduce_plot</tt> which allows you to use this class like a function, returning handles to the plot</li><li>A companion class for converting your figure to an interactive explorer, which allows you to zoom and pan by using your scroll wheel and left-click dragging, respectively</li></ul></div><p>Here's a quick animation of <tt>reduce_plot</tt> in action, compared to a regular plot. You can see the difference in responsiveness of the plot when I am trying to pan the plot.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_plotbig/potw_plotbig_animation.gif" alt=""> </p><p>Thanks for an awesome entry, Tucker. And thanks for the recommendation, Adam. Some swag going to both of you!</p><p><b>Comments</b></p><p>We'd like to hear from you if you do, or are interested in, big data visualization. What kind of visualization do you use? Do you use any special techniques to deal with your big data? Give this a try and let us know what you think <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4613#respond">here</a> or leave a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/40790#comments">comment</a> for Tucker.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/JNdzQdWzpQc" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>R2013a – image processing and computer vision</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/N0-a7pawBiE/</link>
         <description>I've mentioned the R2013a release in two previous posts (15-May-2013 and 12-Mar-2013). Today I want to point out that R2013a is a pretty significant release in terms of new features related to image processing and computer vision.Here's the quick summary of what's new in Image Processing Toolbox, Computer Vision System Toolbox, and Image Acquisition Toolbox.Image [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=846</guid>
         <pubDate>Wed, 05 Jun 2013 16:47:27 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>I've mentioned the R2013a release in two previous posts (<a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/05/15/r2013a-looking-around-in-matlab/">15-May-2013</a> and <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/12/matlab-software-testing-tools-old-and-new-r2013a/">12-Mar-2013</a>). Today I want to point out that R2013a is a pretty significant release in terms of new features related to image processing and computer vision.</p><p>Here's the quick summary of what's new in Image Processing Toolbox, Computer Vision System Toolbox, and Image Acquisition Toolbox.</p><p><b>Image Processing Toolbox version 8.2</b></p><div><ul><li>Image segmentation using active contours</li><li>Classes and functions for representing and applying 2-D and 3-D geometric transformations</li><li>Classes for defining the world coordinate system of an image</li><li>Code generation for <tt>conndef</tt>, <tt>imcomplement</tt>, <tt>imfill</tt>, <tt>imhmax</tt>, <tt>imhmin</tt>, <tt>imreconstruct</tt>, <tt>imregionalmax</tt>, <tt>imregionalmin</tt>, <tt>iptcheckconn</tt>, and <tt>padarray</tt> functions (using MATLAB Coder)</li><li>GPU acceleration for <tt>imrotate</tt>, <tt>imfilter</tt>, <tt>imdilate</tt>, <tt>imerode</tt>, <tt>imopen</tt>, <tt>imclose</tt>, <tt>imtophat</tt>, <tt>imbothat</tt>, <tt>imshow</tt>, <tt>padarray</tt>, and <tt>bwlookup</tt> functions (using Parallel Computing Toolbox)</li><li>Unsharp mask filtering</li></ul></div><p><b>Computer Vision System Toolbox version 5.2</b></p><div><ul><li>Cascade object detector training using Haar, Histogram of Oriented Gradients (HOG), and Local Binary Patterns (LBP) features</li><li>Fast Retina Keypoint (FREAK) algorithm for feature extraction</li><li>Hamming distance method for matching features</li><li>Multicore support in <tt>matchFeatures</tt> function and Foreground Detector System object</li><li>Functions for corner detection, geometric transformation estimation, and text and graphics overlay, augmenting similar System objects</li></ul></div><p><b>Image Acquisition Toolbox version 4.5</b></p><div><ul><li>Kinect for Windows sensor support for acquiring images, depth maps, skeleton data, and related metadata</li></ul></div><p>I've written extensively here in the past about geometric transformations (the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/category/spatial-transforms/">spatial transformations category</a> includes 21 different posts over a three-year period). Now there is much more to say. The new geometric transformation functionality represents a ground-up redesign, based partially on customer response and feedback to the functionality (such as <tt>imtransform</tt>) added way back in 2001. I hope to recruit a developer on the Image Processing Toolbox team to post here soon about the changes.</p><p>In the meantime, here's an example from the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/images/ref/imsharpen.html">documentation for the new function <tt>imsharpen</tt></a>.</p><pre class="codeinput">a = imread(<span class="string">'hestain.png'</span>);
imshow(a)
title(<span class="string">'Original Image'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/r2013a_ipcv_01.jpg" alt=""> <pre class="codeinput">b = imsharpen(a);
imshow(b)
title(<span class="string">'Sharpened Image'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/r2013a_ipcv_02.jpg" alt=""> <p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/N0-a7pawBiE" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Model Explorer or Command Line?</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/FJl0Qzy4TVw/</link>
         <description>Today I would like to ask you a question. This week I received a large model where I wanted to find all the Lookup Table blocks and modify their Index Search Method parameter. Since the model was quite large and I was not familiar with it, manually navigating to each block, opening its dialog and [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2265</guid>
         <pubDate>Sat, 01 Jun 2013 12:05:48 +0000</pubDate>
         <content:encoded><![CDATA[<p>Today I would like to ask you a question.</p>

<p>This week I received a large model where I wanted to find all the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/ndlookuptable.html">Lookup Table</a> blocks and modify their <tt>Index Search Method</tt> parameter. Since the model was quite large and I was not familiar with it, manually navigating to each block, opening its dialog and modifying it was not an option.</p>

<p>So my question is: <em>How would you accomplish this task?</em></p>

<p>Here are two options I considered.</p>

<p><strong>Using functions at the MATLAB command prompt</strong></p>

<p>For a long time, when I needed to find or modify blocks in a large Simulink model, I used the command prompt and functions like <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/find_system.html">find_system</a></tt>, <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/hilite_system.html">hilite_system</a></tt> and <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/set_param.html">set_param</a></tt>.</p>

<p>For the example described above, I can find the blocks using <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/find_system.html">find_system</a></tt> and see how they are connected in the model using <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/hilite_system.html">hilite_system</a></tt>:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/cmdLineFind.png" alt="Finding blocks from command line"/></p>

<p>To change the <tt>Index Search Method</tt>, I can use <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/set_param.html">set_param</a></tt> on the previous results:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/cmdLineSet.png" alt="Configuring blocks from command line"/></p>

<p><strong>Using the Model Explorer</strong></p>

<p>Recently, I started using the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/the-model-explorer-overview.html">Model Explorer</a> for this type of task and I think it is very efficient.</p>

<p>For the same task as above, I can easily search by block type. One thing I like is that I do not need to remember the exact string for the block type. The drop down looks at my model and offers me a list based on the blocks in my model.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/modelExplorerBlkType.png" alt="Finding blocks using the Model Explorer"/></p>

<p>In the list of results, the Path column is a hyperlink I can click to immediately see where the block is in the model.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/modelExplorerHilite.png" alt="Finding blocks using the Model Explorer"/></p>

<p>To edit the <tt>Index Search Method</tt> for all the blocks found, I:
<ul>
<li>Add a column for this property</li>
<li>Select all the blocks using "shitf+Click"</li>
<li>Set the value for one instance, and it applies to all selected blocks</li>
</ul></p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/modelExplorerSet.png" alt="Finding blocks using the Model Explorer"/></p>

<p><strong>Now it's your turn</strong></p>

<p>What is your workflow to find and edit blocks in a large model? Let us know by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2265&#comment">comment here</a>.</p>
<img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/FJl0Qzy4TVw" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Nominate your favorite NEW File Exchange submission</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/uoQtypZVr4c/</link>
         <description>So, it's been just over a year since I last asked readers to nominate their favorite (formerly unrecognized) File Exchange submissions. (My, how time has flown!)Since mid-April, when I issued that challenge, MATLABbers around the world have shared approximately 3100 new files--and that doesn't include files that were simply modified in that timeframe. That means [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4600</guid>
         <pubDate>Fri, 31 May 2013 13:00:14 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>So, it's been just over a year since I last <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2012/04/13/what-is-your-favorite-unrecognized-file-exchange-submission/">asked readers</a> to nominate their favorite (formerly unrecognized) File Exchange submissions. (My, how time has flown!)</p><p>Since mid-April, when I issued that challenge, MATLABbers around the world have shared approximately 3100 <i>new</i> files--and that doesn't include files that were simply modified in that timeframe. That means that more than 22% of the 14000 files currently on the Exchange didn't exist a year ago. And there's some great new stuff out there. Heck, there's even a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/38037-flatulence-sound-generator">"flatulence simulator."</a> (I think I'll send <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/49003">Maxim</a> some swag just for having posted that!)</p><p>So...time to reissue the challenge, but this time with a twist:</p><p>Nominate your favorite new submission--let's say, with a submission date (not <i>modification</i> date) of April 12, 2012 or later. If we agree, and if we feature your nomination in this blog, we'll send both you and the file's author some cool MATLAB swag.</p><p><b>The same ground rules apply:</b></p><div><ul><li>Please don't steer to your own file.</li><li>Please only suggest files that are covered under the BSD!</li><li>Submissions should be exemplary for some reason that you   can point out. Is it just beautifully written? Have you   found it exceptionally useful? Great use of visual   elements? (Tell us what it was that led you to select   a particular file. We may even quote you!)</li><li>Your nomination constitutes your acknowledgment that we may quote you, and your permission to do so.</li><li>Please don't suggest any files that have already been Picked. (All previous Picks of the Week are tagged on their entries with a POTW stamp.)</li><li>Please consider files that do not feature capabilities undocumented in MATLAB. (We know they can be useful, but then they just might break with the next release!)</li><li>Remember: cool MATLAB swag to anyone who steers us to a file we use!</li><li>Please direct your correspondences to the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=3445#respond">comments</a> section of this post.</li></ul></div><p>I think we'll make this an annual event. <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4600#respond">Thoughts?</a></p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/MATLAB_logo_medium.png" alt=""> </p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/uoQtypZVr4c" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Quick Tip: Speeding up debugging iterations</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/b9Cqo_pRh7I/</link>
         <description>This week&amp;#8217;s video is a quick tip to help speed up iterations when debugging MATLAB code. If your code requires user interactivity, such as selecting a file or folder from a dialog box, consider hardcoding a representative input value into your file while debugging. This eliminates for you to perform the interactive steps every time [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1115</guid>
         <pubDate>Thu, 30 May 2013 16:49:44 +0000</pubDate>
         <content:encoded><![CDATA[This week&#8217;s video is a quick tip to help speed up iterations when debugging MATLAB code. If your code requires user interactivity, such as selecting a file or folder from a dialog box, consider hardcoding a representative input value into your file while debugging.  This eliminates for you to perform the interactive steps every time you run the code.

<p>

The video shows a couple of different approaches for switching between your debugging code and the code for the final version. 

<p>

<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate307" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/b9Cqo_pRh7I" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Golden Spiral</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/KRDKuJf70-E/</link>
         <description>A Golden Spiral is simulated by a continuously expanding sequence of golden rectangles and inscribed quarter circles. ContentsGolden RectanglesTrue Golden Spiralgolden_spiral.mGolden RectanglesWe begin with an animated .gif of an imitation Golden Spiral. You can see that removing a square from a golden rectangle leaves a smaller rectangle with the same shape. Connecting inscribed quarter circles [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=674</guid>
         <pubDate>Mon, 27 May 2013 17:00:12 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>A Golden Spiral is simulated by a continuously expanding sequence of golden rectangles and inscribed quarter circles.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/golden_spiral.gif" alt=""> </p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#32e60c03-e48d-4e9d-bb5e-83a7a5f6258e">Golden Rectangles</a></li><li><a rel="nofollow" href="#567cdd9d-3d73-4366-803d-23b5126f196d">True Golden Spiral</a></li><li><a rel="nofollow" href="#266d9089-851d-4554-84a2-ae9494431a41"><tt>golden_spiral.m</tt></a></li></ul></div><h4>Golden Rectangles<a rel="nofollow" name="32e60c03-e48d-4e9d-bb5e-83a7a5f6258e"></a></h4><p>We begin with an animated .gif of an imitation Golden Spiral. You can see that removing a square from a golden rectangle leaves a smaller rectangle with the same shape.  Connecting inscribed quarter circles produces a continuously expanding spiral. The aspect ratio of the rectangles is the golden ratio.</p><p>$$ &#92;phi = &#92;frac{1 + &#92;sqrt{5}}{2} $$</p><p>A MATLAB function for generating these expanding golden rectangles and quarter circles is given at the end of this blog post, but this is not a true Golden Spiral.</p><h4>True Golden Spiral<a rel="nofollow" name="567cdd9d-3d73-4366-803d-23b5126f196d"></a></h4><p>A logarithmic spiral is a curve given in polar coordinates by</p><p>$$ r = &#92;alpha e^{&#92;lambda &#92;theta} $$</p><p>The angular coordinate $&#92;theta$ must be multi-valued as the point circles around the origin multiple times.  We get the particular logarithmic spiral known as the <i>Golden Spiral</i> by involving the golden ratio and setting</p><p>$$ &#92;lambda = &#92;frac{2}{&#92;pi}{&#92;ln{&#92;phi}} $$</p><p>Then the radius is scaled powers of $&#92;phi$, with integer powers as $&#92;theta$ crosses the cartesian axes.</p><p>$$ r = &#92;alpha &#92;phi^{&#92;frac{2}{&#92;pi} &#92;theta} $$</p><p>Here is the plot for $0 &#92;le &#92;theta &#92;le 2 &#92;pi$.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/spiral_pic.jpeg" alt=""> </p><p>I do not see any obvious analytic way to specify the scale factor $&#92;alpha$.  By taking $&#92;alpha$ = 1.48699214 the numeric values generated by the logarithmic Golden Spiral approach those generated by golden rectangles and inscribed quarter circles as the angle $&#92;theta$ gets large.</p><h4><tt>golden_spiral.m</tt><a rel="nofollow" name="266d9089-851d-4554-84a2-ae9494431a41"></a></h4><pre>function golden_spiral
% GOLDEN_SPIRAL  Explosion of golden rectangles.
%    GOLDEN_SPIRAL  Constructs a continuously expanding sequence
%    of golden rectangles and inscribed quarter circles.</pre><pre>%   Copyright 2013 Cleve Moler
%   Copyright 2013 The MathWorks, Inc.</pre><pre>   % Initialize_variables</pre><pre>   % Golden ratio
   phi = (1+sqrt(5))/2;</pre><pre>   % Control speed of zoom
   n = 256;
   f = phi^(1/n);</pre><pre>   % Scaling
   a = 1;
   s = phi;
   t = 1/(phi+1);</pre><pre>   % Centers
   x = 0;
   y = 0;</pre><pre>   % A square
   us = [-1 1 1 -1 -1];
   vs = [-1 -1 1 1 -1];</pre><pre>   % Four quarter circles
   theta = 0:pi/20:pi/2;
   u1 = 2*cos(theta) - 1;
   v1 = 2*sin(theta) - 1;
   u2 = 2*cos(theta+pi/2) + 1;
   v2 = 2*sin(theta+pi/2) - 1;
   u3 = 2*cos(theta+pi) + 1;
   v3 = 2*sin(theta+pi) + 1;
   u4 = 2*cos(theta-pi/2) - 1;
   v4 = 2*sin(theta-pi/2) + 1;</pre><pre>   initialize_graphics</pre><pre>   % Loop</pre><pre>   k = 0;
   while get(klose,'value') == 0
      if mod(k,n) == 0
         power
         switch mod(k/n,4)
            case 0, right
            case 1, up
            case 2, left
            case 3, down
         end
      end
      zoom
      k = k+1;
   end
   pause(1)
   close(gcf)</pre><pre>% ------------------------------------</pre><pre>   function power
      a = s;
      s = phi*s;
      t = phi*t;
   end % power</pre><pre>% ------------------------------------</pre><pre>   function zoom
      axis(f*axis)
      drawnow
   end % zoom</pre><pre>% ------------------------------------</pre><pre>   function right
      x = x + s;
      y = y + t;
      line(x+a*us,y+a*vs,'color','black')
      line(x+a*u4,y+a*v4)
   end % right</pre><pre>% ------------------------------------</pre><pre>   function up
      y = y + s;
      x = x - t;
      line(x+a*us,y+a*vs,'color','black')
      line(x+a*u1,y+a*v1)
   end % up</pre><pre>% ------------------------------------</pre><pre>   function left
      x = x - s;
      y = y - t;
      line(x+a*us,y+a*vs,'color','black')
      line(x+a*u2,y+a*v2)
   end % left</pre><pre>% ------------------------------------</pre><pre>   function down
      y = y - s;
      x = x + t;
      line(x+a*us,y+a*vs,'color','black')
      line(x+a*u3,y+a*v3)
   end % down</pre><pre>% ------------------------------------</pre><pre>   function initialize_graphics
      clf reset
      set(gcf,'color','white','menubar','none','numbertitle','off', ...
          'name','Golden Spiral')
      shg
      axes('position',[0 0 1 1])
      axis(3.5*[-1 1 -1 1])
      axis square
      axis off
      line(us,vs,'color','black')
      line(u3,v3)
      klose = uicontrol('units','normal','position',[.04 .04 .12 .04], ...
         'style','toggle','string','close','vis','on');
      drawnow
   end % initialize graphics</pre><pre>end % golden_spiral</pre><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/KRDKuJf70-E" height="1" width="1"/>]]></content:encoded>
         <category>Fun</category>
      </item>
      <item>
         <title>Delta Sigma Toolbox</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/RW5V47paVNI/</link>
         <description>Idin's pick for this week is the Delta Sigma Toolbox by Richard Schreier.Delta-Sigma (or sigma-delta) modulators are commonly found in electronic components such as analog-to-digital and digital-to-analog converters (ADCs and DACs), and increasingly in [fractional-N] frequency synthesizers (PLLs), and switch-mode power supplies. Generally speaking, a delta-sigma modulator produces a highly over-sampled binary signal at its [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4593</guid>
         <pubDate>Fri, 24 May 2013 13:00:03 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/29096">Idin</a>'s pick for this week is the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/19-delta-sigma-toolbox">Delta Sigma Toolbox</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/735">Richard Schreier</a>.</p><p><a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Delta-sigma_modulation">Delta-Sigma</a> (or sigma-delta) modulators are commonly found in electronic components such as analog-to-digital and digital-to-analog converters (ADCs and DACs), and increasingly in [fractional-N] frequency synthesizers (PLLs), and switch-mode power supplies.  Generally speaking, a delta-sigma modulator produces a highly over-sampled binary signal at its output (0/1) which can be low-pass filtered to reproduce the input signal. Figure 1 below shows an example input &amp; output signal. To read more about delta-sigma modulators, go <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Delta-sigma_modulation">here</a>, <a rel="nofollow" target="_blank" href="http://skywired.net/blog/2011/05/introducing-the-delta-sigma-modulator/">here</a>, and <a rel="nofollow" target="_blank" href="http://www.eetimes.com/electronics-news/4144361/Tutorial-on-Designing-Delta-Sigma-Modulators-Part-1">here</a>. Richard&#8217;s textbook is also a good resource: "Understanding Delta-Sigma Data Converters" by Schreier and Temes (ISBN 0-471-46585-2).</p><p>There is a large body of literature dedicated to analysis and design of delta-sigma modulators, and the Delta Sigma Toolbox provides a great tool for analyzing these components in MATLAB. The toolbox contains a fairly complete list of well documented functions to construct, analyze, and simulate delta-sigma modulators of arbitrary order. The full documentation for the toolbox is provided in DSToolbox.pdf (part of the download).</p><p>To start using the toolbox, I highly recommend studying the provided example and demo files (<tt>dsdemo1-8.m</tt> and <tt>dsexample1-4.m</tt>). I like dsdemo2.m as a starting tutorial.  It begins by creating a noise transfer function (NTF), and then simulates the modulator with an example sinusoidal input:</p><pre class="language-matlab">OSR = 32;
H = synthesizeNTF(5,OSR,1);
N = 8192;
fB = ceil(N/(2*OSR)); ftest=floor(2/3*fB);
u = 0.5*sin(2*pi*ftest/N*[0:N-1]);  <span class="comment">% half-scale sine-wave input</span>
v = simulateDSM(u,H);
</pre><p>The time domain output shows the sinusoidal input (red) and the binary output (green).</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/idin/potw_deltasigma/sigma_delta_fig1.png" alt=""> </p><p>The spectrum of the output can also be easily computed using MATLAB's FFT function:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/idin/potw_deltasigma/sigma_delta_fig2.png" alt=""> </p><p>This figure looks like the superposition of two signals: the spike at ftest/N (0.0104 in this case) which represents the input sinusoid, and some high frequency "noise". The high-pass noise is in fact one of the desirable properties of delta-sigma converters; these converters shift the quantization noise to high frequencies, i.e., away from our signal/carrier of interest. It should be self-evident from Figure 2 that a simple low-pass filter of this output signal would yield the original sinusoidal input.</p><p>The next few lines in dsdemo2.m compute the SNR on the output signal, and also use Delta Sigma Toolbox functions to compute and display the expected (theoretical) response of the modulator (shown in pink blow).</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/idin/potw_deltasigma/sigma_delta_fig3.png" alt=""> </p><p>The next section of the code computes the expected and simulated signal-to-quantization-noise ( <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Signal-to-quantization-noise_ratio">SQNR</a>), which is a figure of merit when analyzing analog-to-digital converters.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/idin/potw_deltasigma/sigma_delta_fig4.png" alt=""> </p><p>The remainder of this demo essentially repeats the same process, but for a band-pass signal. That is, instead of using a low frequency sinusoid as the input, it uses a carrier signal, which makes our output spectrum look as in Figure 5 (the carrier here is at Fs/8 or 0.125 on the normalized frequency axis).</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/idin/potw_deltasigma/sigma_delta_fig5.png" alt=""> </p><p>I encourage you to download the toolbox and run through the demos.  Even if you do not use the toolbox for any simulations of your own, these demos can serve as a great learning tool (along with freely available online resources mentioned above).</p><p><b>Other MathWorks resources:</b></p><p>If you are interested in delta-sigma modulators (and other mixed-signal components), consider downloading the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/programs/mixed-signal/index.html">Mixed-Signal Library for Simulink</a>. Also, take a look at the MathWorks <a rel="nofollow" target="_blank" href="http://www.mathworks.com/mixed-signal-systems/index.html">Mixed-Signal page</a>, particularly the ADC section.</p><p><b>Delta-Sigma Toolbox Usage notes:</b></p><div><ul><li>A few C files are provided in the Toolbox that the user needs to compile to MEX (e.g., simulateDSM.c). This is generally done as:</li></ul></div><pre class="language-matlab">mex <span class="string">simulateDSM.c</span>
</pre><p>But as noted in the comments on File Exchange, this fails on some systems. Simply defining the <tt><i>_STDC</i>_</tt> symbol should resolve the issue:</p><pre class="language-matlab">mex <span class="string">simulateDSM.c</span> <span class="string">&#8211;D__STDC__</span>
</pre><p>Note that you will need a C compiler for this step. Run <tt>mex &#8211;setup</tt> at the MATLAB command prompt to setup your C compiler.</p><div><ul><li>If you plan on using the Delta Sigma Toolbox frequently, you should probably add the toolbox folder to your MATLAB path:</li></ul></div><pre class="language-matlab">addpath(<span class="string">'&lt;your_intall_path&gt;&#92;delsig'</span>)
savepath
</pre><p><b>Suggestions for improvements</b></p><div><ul><li>A great addition to the provided example/demo files would be the use of <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab_prog/run-sections-of-programs.html">sections</a>, and perhaps the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/publish.html">publish</a> feature to include a full write-up and description for each file.</li><li>Providing an Install script would be great (to take care of MATLAB path and compiling MEX files).</li></ul></div><p><b>Comments</b></p><p>As always, your thoughts and comments <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4593#respond">here</a> are greatly appreciated.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/RW5V47paVNI" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Duality Between Function and Command Syntax</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/lD3TCB3JZOE/</link>
         <description>A long time ago, I covered the topic of the duality between command and function syntax.ContentsWhat is Command-Function Duality?Checking Directory ContentsDiscussion of ResultsDefault MATLAB BehaviorOverriding Default BehaviorWhat About You?What is Command-Function Duality?For calling functions with only literal string input values, i.e., strings delimited by the usual single quote ('), you can avoid the overhead of [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=695</guid>
         <pubDate>Wed, 22 May 2013 15:02:36 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>A long time ago, I <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2006/05/03/command-and-function-syntaxes-in-matlab/">covered</a> the topic of the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab_prog/command-vs-function-syntax.html">duality</a> between command and function syntax.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#95e9bd41-0a2d-4841-b33b-a58702bfa68a">What is Command-Function Duality?</a></li><li><a rel="nofollow" href="#ed67cca9-63fb-4e7b-9feb-e92003842b2f">Checking Directory Contents</a></li><li><a rel="nofollow" href="#fa6036a0-d510-41aa-bd3e-b32fadd81cbc">Discussion of Results</a></li><li><a rel="nofollow" href="#5e24fab1-aece-4f0f-80b7-fdefdfbc94ca">Default MATLAB Behavior</a></li><li><a rel="nofollow" href="#a3749eef-1b2d-43ff-b5fa-ec186a5307ec">Overriding Default Behavior</a></li><li><a rel="nofollow" href="#8719954b-322c-4274-9618-d7cf3d37defd">What About You?</a></li></ul></div><h4>What is Command-Function Duality?<a rel="nofollow" name="95e9bd41-0a2d-4841-b33b-a58702bfa68a"></a></h4><p>For calling functions with only literal string input values, i.e., strings delimited by the usual single quote ('), you can avoid the overhead of using parentheses and comma separators to invoke the function, especially if you want either no output or only one output. Let me show you an example.</p><h4>Checking Directory Contents<a rel="nofollow" name="ed67cca9-63fb-4e7b-9feb-e92003842b2f"></a></h4><p>Suppose I want to see the MATLAB code files in my directory beginning with the letter 'q'.  Here are three ways to do such a query.</p><p>First way:</p><pre class="codeinput">dir <span class="string">q*.m</span>
</pre><pre class="codeoutput">
qichen31.m  quadvec.m   quantum.m   

</pre><p>Second Way:</p><pre class="codeinput">dir(<span class="string">'q*.m'</span>)
</pre><pre class="codeoutput">
qichen31.m  quadvec.m   quantum.m   

</pre><p>Third Way:</p><pre class="codeinput">out = dir(<span class="string">'q*.m'</span>)
</pre><pre class="codeoutput">out = 
3x1 struct array with fields:
    name
    date
    bytes
    isdir
    datenum
</pre><h4>Discussion of Results<a rel="nofollow" name="fa6036a0-d510-41aa-bd3e-b32fadd81cbc"></a></h4><p>From these three methods, you can see that the first two give the same output, a list of the names of matching files.  When using the command syntax (the first way), you can't store the output in a named variable. In this case, the decision was to print something out in a useful format, but not to place the information into a variable for further programmatic use.</p><p>The second result is equivalent to the first.  You can see the duality looking at these two statements.  The first and second are equivalent. Simply replace the space and following string (or strings) into a comma-separated list of the same string(s) inside parentheses.  This means that the statement <tt>myfun A B c</tt> is equivalent <tt>myfun('A','B','c')</tt>.</p><p>And now for the third statement.  Clearly it is different than the first two.  First, you can see that something is returned in the output variable <tt>out</tt>.  Second, you can see that <tt>out</tt> is not simply a list of names, but a <tt>struct</tt> containing several fields with information, including <tt>name</tt>, <tt>date</tt>, etc.</p><h4>Default MATLAB Behavior<a rel="nofollow" name="5e24fab1-aece-4f0f-80b7-fdefdfbc94ca"></a></h4><p>MATLAB functions often return at least one output, even if the user does not supply an output variable. If the function does return an output when the user does not specify one, the result goes into a variable named <tt>ans</tt>.</p><h4>Overriding Default Behavior<a rel="nofollow" name="a3749eef-1b2d-43ff-b5fa-ec186a5307ec"></a></h4><p>It is possible to override default behavior for your function outputs. To do so, we take advantage of the function <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/nargout.html"><tt>nargout</tt></a>.  This function allows us to query how many output variables the function is called with. In the case of the function <tt>dir</tt>, you can imagine the logic of the code goes something like this:</p><div><ol><li>check nargout</li><li>if nargout is 0, get and print the list of matching files/directories</li><li>if nargout is greater than 0, collect the relevant directory information and place it into a structure</li></ol></div><p>With the command form for calling a MATLAB function, the value for <tt>nargout</tt> is 0.  Despite this, some functions are designed to return a value, though without a specified output, <tt>ans</tt> is created or updated.</p><h4>What About You?<a rel="nofollow" name="8719954b-322c-4274-9618-d7cf3d37defd"></a></h4><p>Do you take advantage of command-function duality?  In functions you create?  At the MATLAB prompt or in application code your write?  Let me know <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=695#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/lD3TCB3JZOE" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Configuring Models for Linear Analysis</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/S2ykgQkc29M/</link>
         <description>One of the benefits of Model-Based Design is the ability to perform linear analysis on your non-linear model and design controllers using classical controls techniques. In R2013a, configuring your model for linear analysis with Simulink Control Design have been greatly improved. Let's take a look at how useful Linear Analysis Points are when performing control [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2219</guid>
         <pubDate>Mon, 20 May 2013 14:14:14 +0000</pubDate>
         <content:encoded><![CDATA[<p>One of the benefits of Model-Based Design is the ability to perform linear analysis on your non-linear model and design controllers using classical controls techniques.  In R2013a, configuring your model for linear analysis with <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/simcontrol/">Simulink Control Design</a> have been greatly improved. Let's take a look at how useful Linear Analysis Points are when performing control related tasks in Simulink.</p>

<p><strong>Why using Linear Analysis Points?</strong></p>

<p>Those doing linear analysis with Simulink for a long time are probably familiar with the <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/linmod.html">linmod</a></tt> function. With <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/linmod.html">linmod</a></tt>, the inputs and outputs of the linearization are the root-level Inport and Outport blocks of your model. This means that your model needs to be built in a specific way to accommodate linear analysis.</p>

<p>With Simulink Control Design, you can use Linear Analysis Points to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/ug/specify-model-portion-to-linearize.html">specify which portion of a model to linearize</a>.</p>

<p>To see all the advantages of Simulink Control Design compared to <tt>linmod</tt>, I recommend going through this documentation page: <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/ug/linearizing-nonlinear-models.html#bsp453g-4">Linearization Using Simulink Control Design Versus Simulink</a>.</p>

<p><strong>Specifying Linear Analysis Points in a model</strong></p>

<p>Let's take this model as example.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/magball_default.png" alt="Example model to be linearized"/></p>

<p>To design a controller, the first thing I am interested in is linearizing the plant. For that, I can right click on the signals entering and exiting the plant, and mark them as Open-loop Input and Open-loop Output. For those already familiar with Simulink Control Design, notice the new improved menu in R2013a.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/newSCDMenu2.png" alt="Linear Analysis Points Menu"/></p>

<p>Once this is done, you will see markers in your model for the marked signals.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/model_with_linear_analysis_points.png" alt="model With Linear Analysis Points"/></p>


<p><strong>Specifying Multiple sets of Linear Analysis Points</strong></p>

<p>When developing controllers for your model, you will very likely need to accomplish linear analysis multiple times for different parts of your model, open and closed loop, with different inputs and outputs. For that, you can click on <strong>Create new linearization I/Os...</strong> in the Linear Analysis Tool.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/createNewPoints.png" alt="Create new linearization I/Os..."/></p>

<p>This will launch a window where you can define multiple sets of points for your different tasks.</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q2/create_linearization_oi_large.png"><img src="http://blogs.mathworks.com/images/seth/2013Q2/create_linearization_oi_small.png" alt="Creating new linearization I/Os"/></a></p>

<p>Once you are done, you can select the set of points to be used for linearization.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/using_existingIO.png" alt="Using existing linear analysis points"/></p>

<p><strong>Now it's your turn</strong></p>

<p>For those familiar with the earlier version of this menu, I recommend looking at the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/release-notes.html">R2013a release notes</a> to find a table describing the mapping between the previous and current Linear Analysis Points menu. Hopefully, this new menu will help avoid confusion when specifying linear analysis points, especially with the open and closed loop concept.</p>

<p>If you prefer, all the above is also available from the command line with functions like <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/ug/linio.html"><tt>linio</tt></a>, <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/ug/getlinio.html"><tt>getlinio</tt></a>, and <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/slcontrol/ug/setlinio.html"><tt>setlinio</tt></a>.</p>

<p>Give that a try and let us know what you think by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2219&#comment">comment here</a>.</p><img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/S2ykgQkc29M" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Recap of the UK Student Robot Challenge</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/ZNQp08evNr8/</link>
         <description>Robot competitions are in the air these days, what with the recent Battlebots competition in Massachusetts and the earlier Student Robot Challenge in the UK. Here&amp;#8217;s an update from Tanya Morton, who ran the event in England. A few weeks ago, MathWorks hosted a Student Robot Challenge at our new office building in Cambridge. The [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2250</guid>
         <pubDate>Mon, 20 May 2013 14:12:48 +0000</pubDate>
         <content:encoded><![CDATA[<p>Robot competitions are in the air these days, what with the recent <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2013/04/04/design-challenge-autonomous-battlebots-with-simulink/">Battlebots competition in Massachusetts</a> and the earlier Student Robot Challenge in the UK. Here&#8217;s an update from Tanya Morton, who ran the event in England.</p>
<blockquote><p>
A few weeks ago, MathWorks hosted a Student Robot Challenge at our new office building in Cambridge. The event was a great success. The students had fun and learned plenty about modelling, simulation, control design, code generation, and teamwork. I wrote a blog about the event here: </p>
<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2013/03/25/fun-learning-and-drama-at-the-mathworks-student-robot-challenge/">Fun, learning, and drama at the MathWorks Student Robot Challenge</a></p>
<p>We’ve compiled a brand-new video with the highlights of the day, which explains more about the contest and shows the LEGO MINDSTORM NXT robots in action!
</p></blockquote>
<p></p>
<div style="display:none;"> </div>
<p>          <br />
          <br />
          <br />
          <br />
          <br />
          </p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/ZNQp08evNr8" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Polar surface plot in MATLAB</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/E0uFRpqILfk/</link>
         <description>MATLAB does not have a polar surface plot built in. You can use a normal surface plot if you convert your polar data into Cartesian with the pol2cart command. We also cover how to get rid of the edges on dense surface plots like this one by setting &amp;#8216;edgecolor&amp;#8217; to &amp;#8216;none&amp;#8217;.</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1103</guid>
         <pubDate>Fri, 17 May 2013 18:14:27 +0000</pubDate>
         <content:encoded><![CDATA[MATLAB does not have a polar surface plot built in.  You can use a normal surface plot if you convert your polar data into Cartesian with the pol2cart command.
<p>
We also cover how to get rid of the edges on dense surface plots like this one by setting &#8216;edgecolor&#8217; to &#8216;none&#8217;.
<p>
<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate306" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div><img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/E0uFRpqILfk" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Benchmarking your GPU</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/EDh7AjHiI8k/</link>
         <description>Jiro's pick this week is GPUBench by Ben Tordoff.Some of you may know of the bench function. It allows you to benchmark your MATLAB on your machine and compare it against other machines. It performs some mathematical computation tests, as well as graphics tests. Note, as mentioned in the documentation, that bench is for comparing [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4583</guid>
         <pubDate>Fri, 17 May 2013 13:00:14 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/15007">Jiro</a>'s pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/34080">GPUBench</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/80363">Ben Tordoff</a>.</p><p>Some of you may know of the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/bench.html"><tt>bench</tt></a> function. It allows you to benchmark your MATLAB on your machine and compare it against other machines. It performs some mathematical computation tests, as well as graphics tests. <i>Note, as mentioned in the documentation, that <tt>bench</tt> is for comparing a particular version of MATLAB on different machines, not comparing different versions of MATLAB on a single machine.</i></p><p><tt>GPUBench</tt> is <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Graphics_Processing_Unit">GPU</a> version of <tt>bench</tt>. With <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/parallel-computing/">Parallel Computing Toolbox</a>, you can perform MATLAB computations on NVIDIA CUDA GPUs with <a rel="nofollow" target="_blank" href="https://developer.nvidia.com/cuda-gpus">Compute Capability</a> of 1.3 or greater. But your mileage may vary depending on the hardware you have. Sometimes, looking at just the Compute Capability may not be enough to see if one card is better than another for MATLAB computations. <tt>GPUBench</tt> will test your card and compare with other common GPU cards. Here's a sample table that gets generated from the benchmark. It reports in <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/FLOPS">gigaFLOPS</a>, so higher the number, the better the performance.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_gpubench/potw_gpubench_chart.png" alt=""> </p><p>When I bought a MacBookPro last year and noticed that it had a supported GPU card, I ran the benchmark on it and got the following result. <i>Note that this was done with an older version, so the list of cards is a bit old.</i></p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_gpubench/potw_gpubench_mac_chart.png" alt=""> </p><p>The "Host PC" refers to the CPU on my Mac, and "GeForce GT 650M" is the GPU that's equipped. We can see that the GPU seems to outperform the CPU on single-precision computations but not so much on double-precision computations.</p><p>Ben periodically updates the data files to include the newer GPU models that have come out. As of the writing of this post, the version includes benchmark data for K20.</p><p><b>Comments</b></p><p>Do you use GPUs, or are you interested in using GPUs for your work? Let us know about it <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4583#respond">here</a>. If you do GPU computing in MATLAB, give this App a try and leave a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/34080#comments">comment</a> for Ben.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/EDh7AjHiI8k" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>R2013a – Looking around in MATLAB</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/HCWwUcnJwls/</link>
         <description>The first MathWorks general product release of the year, R2013a, shipped a couple of months ago. I've already mentioned it once here in my 12-Mar-2013 post about the new MATLAB unit test framework.With each new release, I peruse the release notes for MATLAB to see what things I find particularly interesting. (This helps me remember [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=840</guid>
         <pubDate>Wed, 15 May 2013 17:55:36 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>The first MathWorks general product release of the year, <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/new_products/latest_features.html">R2013a</a>, shipped a couple of months ago. I've already mentioned it once here in my <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/12/matlab-software-testing-tools-old-and-new-r2013a/">12-Mar-2013 post</a> about the new MATLAB unit test framework.</p><p>With each new release, I peruse the release notes for MATLAB to see what things I find particularly interesting. (This helps me remember which product features have actually been released, as opposed to still being in development. My memory needs all the help it can get.)</p><p>The first thing to note is the reappearance of the table of contents for navigating in the Help Browser and in the online <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/index.html">Documentation Center</a>. This is a direct result of helpful feedback we received from many of you about the R2012b release.</p><p>My favorite "make-it-go-faster-without-sacrificing-accuracy" people (the MATLAB Math Team, that is) have been busy again. People with computers based on Intel or AMD chips using the AVX instruction set should see their calls to <tt>fft</tt> speed up. Anybody running <tt>permute</tt> on 3-D or higher-dimensional arrays should also get a nice boost. I've done a lot of development work related to image and scientific format support, so I know that a fast <tt>permute</tt> can be pretty useful when reading image and scientific data. That's because most of these formats store array elements in the file in a different order than MATLAB uses in memory.</p><p>In the small-but-nice category, the MATLAB Math Team also simplified a common programming pattern in my own neck of the woods (image processing). Specifically, it's a bit easier to initial an array of 0s or 1s whose type is based on existing array. Here's an example to illustrate:</p><pre class="codeinput">clear  <span class="comment">% Let's start with a fresh workspace.</span>
rgb = imread(<span class="string">'peppers.png'</span>);
imshow(rgb)
title(<span class="string">'Obligatory image screenshot'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/r2013a_matlab_01.jpg" alt=""> <p>Now I want a 100-by-100 matrix of 0s with the same data type as <tt>rgb</tt>.</p><pre class="codeinput">A = zeros(100,100,<span class="string">'like'</span>,rgb); <span class="comment">% Make a 100-by-100 matrix that's "like" rgb.</span>
whos
</pre><pre class="codeoutput">  Name        Size                Bytes  Class    Attributes

  A         100x100               10000  uint8              
  rgb       384x512x3            589824  uint8              

</pre><p>My developer friend Tom Bryan really "likes" this (ahem) because it enables much easier solutions to some common programming tasks for users of Fixed-Point Designer.</p><p>I have occasionally done a little web scripting in MATLAB, so it's nice to see <tt>urlread</tt> and <tt>urlwrite</tt> get a little love. These functions can now handle basic authentication via the <tt>'Authentication'</tt>, <tt>'Username'</tt>, and <tt>'Password'</tt> parameters.</p><p>Do you use a Mac? You can now write MPEG-4 H.264 files using <tt>VideoWriter</tt> (requires Mac OS 10.7 or later).</p><p>A couple of handy new string functions have appeared, <tt>strsplit</tt> and <tt>strjoin</tt>. Based on how often users have submitted their own versions to the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/">MATLAB Central File Exchange</a>, I'm sure these will be popular.</p><pre class="codeinput">out = strsplit(pwd,<span class="string">'&#92;'</span>)
</pre><pre class="codeoutput">
out = 

    'B:'    'published'    '2013'

</pre><p>You can now do extrapolation with both scattered and gridded interpolation. For extrapolation with scattered interpolation, use the new <tt>scatteredInterpolant</tt>. Here's an example I lifted from the doc.</p><p>Query the interpolant at a single point outside the convex hull using nearest neighbor extrapolation.</p><p>Define a matrix of 200 random points.</p><pre class="codeinput">P = -2.5 + 5*gallery(<span class="string">'uniformdata'</span>,[200 2],0);
</pre><p>Sample an exponential function. These are the sample values for the interpolant.</p><pre class="codeinput">x = P(:,1);
y = P(:,2);
v = x.*exp(-x.^2-y.^2);
</pre><p>Create the interpolant, specifying linear interpolation and nearest neighbor extrapolation.</p><pre class="codeinput">F = scatteredInterpolant(P,v,<span class="string">'linear'</span>,<span class="string">'nearest'</span>)
</pre><pre class="codeoutput">
F = 

  scatteredInterpolant with properties:

                 Points: [200x2 double]
                 Values: [200x1 double]
                 Method: 'linear'
    ExtrapolationMethod: 'nearest'

</pre><p>Evaluate the interpolant outside the convex hull.</p><pre class="codeinput">vq = F(3.0,-1.5)
</pre><pre class="codeoutput">
vq =

    0.0031

</pre><p>Disable extrapolation and evaluate F at the same point.</p><pre class="codeinput">F.ExtrapolationMethod = <span class="string">'none'</span>;
vq = F(3.0,-1.5)
</pre><pre class="codeoutput">
vq =

   NaN

</pre><p>I encourage you to wander over to the R2013a release notes for <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/release-notes.html">MATLAB</a> or any other product that you use and see what's new that might be helpful to you.</p><p>There are also lots of new things in the image processing and computer vision worlds, of course. I'll look at those next time.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/HCWwUcnJwls" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Pentium Division Bug Affair</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/IpKOsTyKdMM/</link>
         <description>In my previous blog post I reprinted the Cleve's Corner article from the 1995 issues of MATLAB News and Notes and SIAM News about the Pentium division bug. In today's post I would like to describe some of the effects that affair had on the emerging Internet, the MathWorks, and the Intel Corporation,Contents1994 InternetInitial ActivityIntel's [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=662</guid>
         <pubDate>Mon, 13 May 2013 17:00:04 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>In my previous blog post I reprinted the Cleve's Corner article from the 1995 issues of MATLAB News and Notes and SIAM News about the Pentium division bug. In today's post I would like to describe some of the effects that affair had on the emerging Internet, the MathWorks, and the Intel Corporation,</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#de4e99d4-ba14-4447-a07a-fc6ec6ef0ee0">1994 Internet</a></li><li><a rel="nofollow" href="#2c6883e2-84b7-413a-8f26-898cc9f7ac0f">Initial Activity</a></li><li><a rel="nofollow" href="#37b37e97-1020-41cd-994d-cf5de91e8084">Intel's Response</a></li><li><a rel="nofollow" href="#1b924846-7d3e-4355-a866-c0121dd3eb5a">Internet Emboldened</a></li><li><a rel="nofollow" href="#cab206c3-8599-4420-9510-1eccfe37f962">Effect on MathWorks</a></li><li><a rel="nofollow" href="#d73750de-5167-4514-9281-bc0654ea353f">Reaction at IBM</a></li><li><a rel="nofollow" href="#3e771fbc-398c-4be6-95e1-43c9881a33e9">Intel Response</a></li><li><a rel="nofollow" href="#d618c9e3-cb31-4c79-a93a-077ca4619c60">Public Reaction</a></li><li><a rel="nofollow" href="#da24ec92-6877-42a2-8c4b-8cf28df717a5">Postmortem</a></li><li><a rel="nofollow" href="#aa1b2117-2672-4529-97a6-60064c88329f">References</a></li></ul></div><h4>1994 Internet<a rel="nofollow" name="de4e99d4-ba14-4447-a07a-fc6ec6ef0ee0"></a></h4><p>In the fall of 1994 we did not have anything like the Web as we know it today. There was an Internet, but the connections and protocols were all text based.  We did have email and file transfer. News groups, including <tt>comp.soft-sys.matlab</tt> and <tt>comp.sys.intel</tt>, existed. The Mosaic graphical browser had been available for just a few months, but most people, including me, had not yet started to use it. Internet Explorer was not yet on the scene and it would be four more years before we would hear of Google.</p><p>When I began to get email asking for information about the bug, I would start my reply with "If you have access to the Internet ..." and then give instructions on how to use the MathWorks FTP site. Imagine doing that today.</p><p>And, as far as I can remember, there was not yet any spam. All of the email, and all of the postings to the newsgroups, were legitimate.  Maybe they weren't all worthwhile, but at least there wasn't yet any of the absolute junk we unfortunately see today.</p><h4>Initial Activity<a rel="nofollow" name="2c6883e2-84b7-413a-8f26-898cc9f7ac0f"></a></h4><p>Prof. Thomas Nicely started all the activity by sending a memo about an error in the calculation of the reciprocal of a twin prime to the CompuServe network on October 30, 1994.  This soon found its way to Terje Mathisen in Norway who confirmed a bug in floating point division on the new Intel Pentium processor and posted an announcement, along with a test program, to the <tt>comp.sys.intel</tt> newsgroup on November 3.</p><p>A couple of MathWorks customers saw the news and called our tech support, asking how the bug might affect MATLAB.  At nearly the same time I heard about the bug from a mailing list covering floating point arithmetic.</p><p>On November 14 Tim Coe posted what turned out to be an instance of the worst possible error. The next day I made my first posting, to both <tt>comp.soft-sys.matlab</tt> and <tt>comp.sys.intel</tt>, summarizing what was known up to then. I said that as far as I was concerned the worst aspect of the situation was that we didn't know how bad it was and so we had to be concerned about it.</p><h4>Intel's Response<a rel="nofollow" name="37b37e97-1020-41cd-994d-cf5de91e8084"></a></h4><p>Here is Intel's initial response, in the form of the FAXBACK document produced by their customer support system.</p><p>
<p style="margin-left:3ex;">
There has been a lot of communication recently on the Internet about a
floating point flaw on the Pentium processor.  For almost all users, this
is not a problem.
</p>
<p>
<p style="margin-left:3ex;">
Here are the facts.  Intel detected a subtle flaw in the precision of the
divide operation for the Pentium processor.  For rare cases (one in nine
billion divides), the precision of the result is reduced.  Intel discovered
this subtle flaw during on going testing after several trillions of floating
point operations in our continuing testing of the Pentium processor.  Intel
immediately tested the most stringent technical applications that use the
floating point unit over the course of months and we have been unable to
detect any error.  In fact, after extensive testing and shipping millions of
Pentium processor-based systems there has only been one reported instance of
this flaw affecting a user to our knowledge,  In this case, a mathematician
doing theoretical analysis of prime numbers and reciprocals saw reduced
precision at the 9th place to the right of the decimal.
</p>
<p>
<p style="margin-left:3ex;">
In fact, extensive engineering tests demonstrated that an average spreadsheet
user could encounter this subtle flaw of reduced precision once in every
27,000 years of use.  Based on these empirical observations and our extensive
testing, the user of standard off-the-shelf software will not be impacted.
If you have this kind of prime number generation or other complex
mathematics,
call 1 800 628-8686 (International) 916 356-3551).  If you don't, you won't
encounter any problems with your Pentium processor-based system.  If ever
in the life of the computer this becomes a problem, Intel will work with
the customer to resolve the issue.
</p>
<p>Needless to say, that kind of response did not satisfy activists on the net.</p><h4>Internet Emboldened<a rel="nofollow" name="1b924846-7d3e-4355-a866-c0121dd3eb5a"></a></h4><p>Intel had only recently begun to appeal directly to consumers with its "Intel Inside" campaign. Intel's traditional customers were computer manufacturers, and they were not concerned with "subtle flaws" that had already been fixed in the latest stepping of the part.</p><p>But now posts criticizing Intel started to appear on the net. A small, but important and vocal portion of the customer base was protesting.</p><p>On November 22, two engineers at the Jet Propulsion Laboratory suggested to their purchasing department that the laboratory stop ordering computers with Pentium chips. Steve Young, a reporter with CNN, heard about JPL's decision, found my posting on the newsgroup, and called me.  After talking to me for a few minutes, he sent a video crew to MathWorks in Massachusetts and interviewed me over the phone from wherever he was in California.  That evening, CNN's <i>Moneyline</i> used Young's news about JPL and his interview with me to make the Pentium Division Bug mainstream news. Two days later -- it happened to be Thanksgiving -- stories appeared in <i>The New York Times</i>, <i>The Boston Globe</i>, <i>The San Jose Mercury News</i>, and elsewhere. Hundreds of articles followed in the next several weeks.</p><p>On November 27, Andy Grove, CEO of Intel, tried to post his view of the situation on <tt>comp.sys.intel</tt>.  But I'm afraid he only made matters worse. For one thing, he didn't even have his own logon, so he had a colleague, Richard Wirt, post the message on his behalf.  Many netters were suspicious that it was a fake.  The general tone was similar to the FAXBACK I reproduced above, aggressively defensive.  And the posting was too long.  I have included the entire posting in the collection of Pentium bug documents available from MATLAB Central.</p><p>In the three weeks from Mathisen's first posting until the end of November the traffic on <tt>comp.sys.intel</tt> increased from a trickle to hundreds messages a day.  Most of it was rants about Intel and rants about the rants. I had to stop reading it.  Some of it was cross posted to <tt>comp.soft-sys.matlab</tt>, so the traffic was heavy there too for a while.</p><p>The net had been heard.  It had gone from being a plaything for a few academic geeks to something with economic clout.  The Internet was beginning to grow up.</p><h4>Effect on MathWorks<a rel="nofollow" name="cab206c3-8599-4420-9510-1eccfe37f962"></a></h4><p>In the fall of 1994 the MathWorks was celebrating its 10th anniversary. We had not yet moved to Apple Hill.  We were still located on Prime Parkway, off of Speen Street.  We had less than 250 employees.</p><p>Our product name, MATLAB, was known to our customers, but our company name, MathWorks, was not widely known.  On November 23, we announced that we were preparing a version of MATLAB that could detect and correct the division bug.  Our public relations firm issued a press release with the headline,</p><p>THE MATHWORKS DEVELOPS FIX FOR THE INTEL PENTIUM(tm) FLOATING POINT ERROR</p><p>So on the day the story appears in <i>The New York Times</i>, this message showed up in the fax machines of media outlets all over the country. It turned out to be a very successful press campaign.</p><p>MathWorks has been at the forefront of companies using the Internet. We were 73rd company to register as a ".com" URL. So with the Mosaic browser becoming available about this time, we put up one of the first company Home pages.</p><p>I collected as many of the documents associated with this affair as I could and made them available in a .zip file from an FTP site. We put a notice about that collection on our home page, even though most people learned about it from newsgroups and email.  Here is that first MathWorks Home Page.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/1994.first_site.jpg" alt=""> </p><h4>Reaction at IBM<a rel="nofollow" name="d73750de-5167-4514-9281-bc0654ea353f"></a></h4><p>On December 12, IBM issued a report entitled "Pentium Study" that claimed financial spreadsheet calculations did not produce floating point numbers with uniformly distributed random bit patterns, but rather frequently produced numbers with long strings of 1's in their binary representation. These are the numbers that are "at risk" for encountering the FDIV bug. As a result, they predicted division errors would be much more frequent than Intel claimed.</p><p>Citing their report, IBM announced they were halting shipment of Pentium-based personal computers.  Intel's stock dropped 10 points within a few hours of the IBM press release.</p><h4>Intel Response<a rel="nofollow" name="3e771fbc-398c-4be6-95e1-43c9881a33e9"></a></h4><p>A week after the IBM announcement, on December 20, Intel finally acknowledged the situation.  They announced a no-questions-asked return policy.  They would replace the Pentium chip for anyone that requested it.  They set up a number of replacement centers around the country (and around the world, I assume). They set aside $475-million to pay for it all.  Their announcement said:</p><p>
<p style="margin-left:3ex;">
Our previous policy was to talk with users to determine whether their needs
required replacement of the processor. To some people, this policy seemed
arrogant and uncaring. We apologize. We were motivated by a belief that
replacement is simply unnecessary for most people. We still feel that way, but
we are changing our policy because we want there to be no doubt that we stand
behind this product.
</p>
<p>When I first thought about writing a blog post recalling the Pentium affair, I ordered the recent biography of Andy Grove listed in the References.  It reads like a ghost-written autobiography. There is a substantial chapter entitled "The Pentium Launch: Intel Meets the Internet" which provides Grove's view of these events and their consequences.  He still doesn't quite get it -- he continues to refer to newsgroup traffic as email.  But the chapter does reveal that the affair had a deep affect on him.  I think his message is well summarized by this quote on a key chain containing a surplus defective Pentium.</p><p>
<p style="padding-left:3ex;">
<i>Bad companies are destroyed by crises;<br />
Good companies survive them;<br />
Great companies are improved by them.;</i><br />
--Andy Grove, December 1994</p>
<p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/keychain_small.jpg" alt=""> </p><p>Pentium key chain. Image thanks to Thomas Johansson, <a rel="nofollow" target="_blank" href="mailto:thomas@cpucollection.se">thomas@cpucollection.se</a>.</p><h4>Public Reaction<a rel="nofollow" name="d618c9e3-cb31-4c79-a93a-077ca4619c60"></a></h4><p>The entire affair fascinated the public.  In addition to the key chains, there were necklaces, pendants, and other jewelry.  There were cartoons in newspapers and popular magazines, and jokes in late-night TV monologues. The interest lasted for a couple of months.  Some of the jokes, unfortunately some of the worst ones, are preserved in Web sites today. Just Google "Pentium Jokes".</p><p>One of my favorite stories is personal.  My daughter came to visit for Christmas.  She uses a Macintosh and I accidentally dropped it while unloading the car.  I took it into a shop in Natick that I had never been in before to see about getting it repaired.  My picture had recently been in the local newspaper and a guy behind the counter recognized me.  He said, "Hey, you're Cleve Moler.  I've got something to show you."  He clicked on an icon on a nearby Mac.  The icon said "Pentium Powered Calculator".  Sure enough, the results of divisions had errors in the fifth decimal place.  This is on a Mac!  The splash screen said the program came from an outfit called "Sarcastic Software". Who are those guys?  I'd love to meet them.</p><h4>Postmortem<a rel="nofollow" name="da24ec92-6877-42a2-8c4b-8cf28df717a5"></a></h4><p>I'm not sure of the actual number, but I understand that relatively few people actually asked to replace their Pentiums after all. Intel did not have to spend very much of the $475-million they had allocated. Most people were satisfied just to be assured that they could get a replacement if they ever felt they really needed it.</p><p>Only a few dozen people requested the Pentium-aware version of MATLAB. And none of them reported setting off the floating point division warning message without deliberately trying to trigger it.</p><p>So, as far as I know, Thomas Nicely was the only person to ever actually encounter the FDIV bug without actually looking for it. We had other reports of suspected division error sightings, but they were all ultimately traced to arithmetic errors in other places. In fact, the probability of the occurrence of the FDIV error is extremely small.  But we didn't know that at the beginning of this affair, so that was why we had to be concerned.</p><h4>References<a rel="nofollow" name="aa1b2117-2672-4529-97a6-60064c88329f"></a></h4><p>A collection of original documents associated with the Pentium division bug is available from MATLAB Central. <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/1666">Pentium Papers</a></p><p>Richard S. Tedlow, <i>Andy Grove, The Life and Times of an American Business Icon</i>, Portfolio, Penguin Books, 2006, 568 pp.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/IpKOsTyKdMM" height="1" width="1"/>]]></content:encoded>
         <category>History</category>
      </item>
      <item>
         <title>Sum Block: Round or Rectangular?</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/6rzrSylM3j8/</link>
         <description>Working in technical support, I see a lot of Simulink models from users. I have realized that many users do not know how to, or do not take the time to configure the ports of the Sum block. For example, when I see things like this, it makes my eyes hurt a little: Here are [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2209</guid>
         <pubDate>Fri, 10 May 2013 18:51:42 +0000</pubDate>
         <content:encoded><![CDATA[<p>Working in technical support, I see a lot of Simulink models from users. I have realized that many users do not know how to, or do not take the time to configure the ports of the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/add.html">Sum</a> block.</p>

<p>For example, when I see things like this, it makes my eyes hurt a little:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/lookingBad.png" alt="Unusual configurations of the Sum block"/></p>

<p>Here are a few tips to format the Sum block to make your models easier to understand.</p>

<p><strong>Round Sum block</strong></p>

<p>When you drag the Sum block from the Simulink Library Browser, its <strong>Icon Shape</strong> is set to <strong>Round</strong>, and it has one input port on the left and one on the bottom:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/defaultSumBlock.png" alt="Default configuration of the Sum block"/></p>

<p>When the Sum block Icon Shape is set to Round, the ports are spread evenly from top to bottom and the vertical bar "|" can be used to skip one position. For example, if we want to add a port on top of the block, we can modify the list of signs:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/threeSumBlock.png" alt="3 ports configuration of the Sum block"/></p>

<p><strong>Rectangular Sum block</strong></p>

<p>If you change the <strong>Icon Shape</strong> property of the default Sum block to <strong>Rectangular</strong>, the block will look like the following:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/defaultRectangularSumBlock.png" alt="Rectangular configuration of the Sum block"/></p>

<p>Personally, I can not think of a good reason for skipping a port in Rectangular shape. So I almost always remove the "|" when I change the shape to Rectangular.</p>

 <p><img src="http://blogs.mathworks.com/images/seth/2013Q2/RectangularSumBlock.png" alt="Rectangular configuration of the Sum block"/></p>

<p><strong>Sum of Elements</strong></p>

<p>One way I like to use the Sum block is to sum all the elements of a vector or matrix:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/sumOfAllElements.png" alt="Sum of elements configuration of the Sum block"/></p>

<p>For matrices, the Sum block can also be configured to Sum only over one specific dimension:</p>

 <p><img src="http://blogs.mathworks.com/images/seth/2013Q2/sumOfElements.png" alt="Sum of elements configuration of the Sum block"/></p>

<p><strong>Round or Rectangular?</strong></p>

<p>One question remains: <em>When should the Sum block be Round and when should it be Rectangular?</em></p>

<p>There is no absolute rule, but personally I like to use the Rectangular shape when implementing equations that flow from left to right, without obvious feedback. For example:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/rectangularFlow.png" alt="When to use configuration of the Sum block"/></p>

<p>I keep the Round shape for when I want to make it obvious that there is a feedback involved:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/roundForFeedback.png" alt="When to use Round configuration of the Sum block"/></p>

<p><strong>Now it's your turn</strong></p>

<p>Please share with us if you have rules or guidelines on the format of your blocks by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2209&#comment">comment here</a>.</p>
<img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/6rzrSylM3j8" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Colorspaces out the Wazoo!</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/xbgPEa1J_Zs/</link>
         <description>Brett's Pick this week is &quot;Colorspace Transformations&quot;, by Pascal Getreuer.For inspiration for this week's Pick, I went back to my post from April of last year, in which I asked readers to suggest files to feature. I started to write up Pascal's submission long ago, but somehow got sidetracked, and I wanted to circle back [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4556</guid>
         <pubDate>Fri, 10 May 2013 13:00:49 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/911">Brett</a>'s Pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/28790">"Colorspace Transformations"</a>, by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/14582">Pascal Getreuer</a>.</p><p>For inspiration for this week's Pick, I went back to <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2012/04/13/what-is-your-favorite-unrecognized-file-exchange-submission/">my post</a> from April of last year, in which I asked readers to suggest files to feature. I started to write up Pascal's submission long ago, but somehow got sidetracked, and I wanted to circle back around to it.</p><p>File Exchange champ <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/29192">Oliver Woodford</a> casually suggested "a couple of useful ones." (His other selection was featured <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2012/08/17/shaded-error-bars/">last August</a> by Jiro.) Both of his "Picks" are quite useful.</p><p>So, what's so great about this colorspace converter? In particular, I really like the fact that Pascal's code extends the colorspace conversion capabilities beyond those offered by the Image Processing Toolbox, and that Pascal has included C-code (and instructions for calling it via the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2013a/matlab/create-mex-files.html">MEX interface</a>) to make them faster.</p><p>Colorspace Transformations facilitates conversion to any of these colorspaces:</p><pre>'RGB'              sRGB IEC 61966-2-1
'YCbCr'            Luma + Chroma ("digitized" version of Y'PbPr)
'JPEG-YCbCr'       Luma + Chroma space used in JFIF JPEG
'YDbDr'            SECAM Y'DbDr Luma + Chroma
'YPbPr'            Luma (ITU-R BT.601) + Chroma
'YUV'              NTSC PAL Y'UV Luma + Chroma
'YIQ'              NTSC Y'IQ Luma + Chroma
'HSV' or 'HSB'     Hue Saturation Value/Brightness
'HSL' or 'HLS'     Hue Saturation Luminance
'HSI'              Hue Saturation Intensity
'XYZ'              CIE 1931 XYZ
'Lab'              CIE 1976 L*a*b* (CIELAB)
'Luv'              CIE L*u*v* (CIELUV)
'LCH'              CIE L*C*H* (CIELCH)
'CAT02 LMS'        CIE CAT02 LMS</pre><p>That's a lot of different ways to represent a color image!</p><p>Whenever I am asked to segment a color image--and trust me, that's pretty often!--my initial thought is to look at the R,G, and B colorplanes individually to understand where the information I'm after lies. I do this so often that I wrote and shared <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/19706-explorergb">a utility</a> that facilitates this exploration process. (In "Advanced Mode," ExploreRGB shows--in addition to RGB [and R, G, and B]--HSV, YCbCr, and L*a*b* versions of the image. I can often find a single-plane version of the original image in one of these transformed colorspaces that makes the segmentation easy. For instance, if I needed to isolate the central yellow pepper in the "peppers.png" image that ships with the Image Processing Toolbox:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/peppers.png" alt=""> </p><p>I might consider (ironically) starting from the blue chrominance image (i.e., the second colorplane of the YCbCr representation of the image):</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/bluechrominance.png" alt=""> </p><p>Starting with that image plane:</p><pre class="language-matlab">mask = ~im2bw(img,0.24);
cc = bwconncomp(mask);
stats = regionprops(cc,<span class="string">'Area'</span>);
A = [stats.Area];
[~,biggest] = max(A);
mask(labelmatrix(cc)~=biggest) = 0;
mask = imfill(mask,<span class="string">'holes'</span>);
imshow(<span class="string">'peppers.png'</span>)
showMaskAsOverlay(0.7,mask,<span class="string">'c'</span>);
</pre><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/segmentedPepper.png" alt=""> </p><p>Working in a non-standard colorspace made this segmentation problem easier than it might otherwise have been, and certainly easier than doing it in RGB-space would be.</p><p>(<a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/22108-showmaskasoverlay"><tt>showMaskAsOverlay</tt></a> is a utility I shared for overlaying a transparent mask on an image.)</p><p>Okay, so back to Pascal's file.</p><p>With a little bit of code, I can use "Colorspace Transforms" to examine quickly many additional representations of the original image:</p><pre class="language-matlab">cs = {<span class="string">'RGB'</span>,<span class="string">'YCbCr'</span>,<span class="string">'JPEG-YCbCr'</span>,<span class="string">'YDbDr'</span>,<span class="string">'YPbPr'</span>,<span class="string">'YUV'</span>,<span class="keyword">...</span>
<span class="string">'YIQ'</span>,<span class="string">'HSV'</span>,<span class="string">'HSL'</span>,<span class="string">'HSI'</span>,<span class="keyword">...</span>
<span class="string">'XYZ'</span>,<span class="string">'Lab'</span>,<span class="string">'Luv'</span>,<span class="string">'LCH'</span>,<span class="string">'CAT02 LMS'</span>};
peppers = imread(<span class="string">'peppers.png'</span>);
figure(<span class="string">'color'</span>,<span class="string">'w'</span>);
ax = tight_subplot(numel(cs),4);
ind = 1;
<span class="keyword">for</span> ii = 1:numel(cs)
    newim = colorspace([<span class="string">'-&gt;'</span> cs{ii}],peppers);
    <span class="keyword">if</span> max(newim(:)) &gt; 1
        newim = newim/max(newim(:));
    <span class="keyword">end</span>
    axes(ax(ind));
    imshow(newim,[]);title(cs{ii});
    <span class="keyword">for</span> jj = 1:3
        ind = ind+1;
        axes(ax(ind));
        imshow(newim(:,:,jj),[]);title(sprintf(<span class="string">'%s(:,:,%i)'</span>,cs{ii},jj));
    <span class="keyword">end</span>
    ind = ind+1;
<span class="keyword">end</span>
expandAxes(ax)
</pre><p>(<a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/27991-tight-subplot"><tt>tight_subplot</tt></a> was a previous Pick-of-the-Week.)</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/colorspaceList.png" alt=""> </p><p>Now I have a lot more options at my disposal for segmenting images!</p><p>P.S. I know you can't really see what's happening in those tiny thumbnails*, but then that's the beauty of <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/18291-expandaxes"><tt>expandAxes</tt></a>; if you were to run the code snippet above, you would be able to click on any of those tiny axes and expand them to full-frame. And you could right-click on any expanded axes to export the image to the Workspace!</p><p>*P.P.S. If your image is large, doing what I just did could be a very bad idea. These aren't really "thumbnails"; even if the visualization is small, each of those image objects has in its <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2013a/matlab/ref/image_props.html">"cdata"</a> container a full copy of the image it reflects.</p><p>Thank you, Oliver, for the suggestion. And thank <i>you</i>, Pascal, for the very useful submission. Swag on the way to both of you!</p><p>As always, I welcome your <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4556#respond">thoughts and comments</a>. Or leave feedback for Pascal <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/28790#comments">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div>' cs{ii}],peppers);
%       if max(newim(:)) &gt; 1
%           newim = newim/max(newim(:));
%       end
%       axes(ax(ind));
%       imshow(newim,[]);title(cs{ii});
%       for jj = 1:3
%           ind = ind+1;
%           axes(ax(ind));
%           imshow(newim(:,:,jj),[]);title(sprintf('%s(:,:,%i)',cs{ii},jj));
%       end
%       ind = ind+1;
%   end
%   expandAxes(ax)

%%
% ( was a previous Pick-of-the-Week.) 

%%
% 
% &lt; &gt;
% 

%%
% Now I have a lot more options at my disposal for segmenting images!

%% 
% P.S. I know you can't really see what's happening in those tiny thumbnails*,
% but then that's the beauty of
% ;
% if you were to run the code snippet above, you would be able to click on
% any of those tiny axes and expand them to full-frame. And you could
% right-click on any expanded axes to export the image to the Workspace!

%% 
% *P.P.S. If your image is large, doing what I just did could be a very bad
% idea. These aren't really "thumbnails"; even if the visualization is small, 
% each of those image objects has in its 
% container a full copy of the image it reflects.

%% 
% Thank you, Oliver, for the suggestion. And thank _you_, Pascal, for the
% very useful submission. Swag on the way to both of you!

%%
% As always, I welcome your
% .
% Or leave feedback for Pascal .
##### SOURCE END ##### b7763c2fc1234b029827c0f68bbf81b4
--&gt;<img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/xbgPEa1J_Zs" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Recent Question about Speed with Subarray Calculations</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/9te7pV1k6Q4/</link>
         <description>Recently someone asked me to explain the speed behavior doing a calculation using a loop and array indexing vs. getting the subarray first.ContentsExampleFirst MethodSecond MethodSame Results?Compare RuntimeWhat's Happening?Your Results?ExampleSuppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.myfun [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=688</guid>
         <pubDate>Sat, 04 May 2013 14:47:31 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Recently someone asked me to explain the speed behavior doing a calculation using a loop and array indexing vs. getting the subarray first.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#993880b3-5843-4778-bc94-32d83ac85cac">Example</a></li><li><a rel="nofollow" href="#6af5b04d-a4a2-4d87-87e3-80b5f5e558e1">First Method</a></li><li><a rel="nofollow" href="#268c5a14-73fe-439d-8a70-9c107435afbe">Second Method</a></li><li><a rel="nofollow" href="#9ccb7a79-b332-4e32-abe0-81a3ed286deb">Same Results?</a></li><li><a rel="nofollow" href="#6ae5ef22-d2db-4d73-9f37-b3d80d85f82d">Compare Runtime</a></li><li><a rel="nofollow" href="#aea57373-3b4c-4692-ad92-ac8c6dfe920c">What's Happening?</a></li><li><a rel="nofollow" href="#b2f25522-87bc-4cc4-a85d-00bc6f60d4fc">Your Results?</a></li></ul></div><h4>Example<a rel="nofollow" name="993880b3-5843-4778-bc94-32d83ac85cac"></a></h4><p>Suppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.</p><pre class="codeinput">myfun = @(x,z) x'*x+z;
</pre><p>And even though this may be calculated in a fully vectorized manner, let's explore what happens when we work on subarrays from the array input.</p><p>I am now creating the input array <tt>x</tt> and the results output arrays for doing the calculation two ways, with an additional intermediate step in one of the methods.</p><pre class="codeinput">n = 500;
x = randn(n,n);
result1 = zeros(n,1);
result2 = zeros(n,1);
</pre><h4>First Method<a rel="nofollow" name="6af5b04d-a4a2-4d87-87e3-80b5f5e558e1"></a></h4><p>Here we see and time the first method.  In this one, we create a temporary array for <tt>x(:,k)</tt> <tt>n</tt> times through the outer loop.</p><pre class="codeinput">tic
<span class="keyword">for</span> k = 1:n
    <span class="keyword">for</span> z = 1:n
        result1(z) = myfun(x(:,k), z);
    <span class="keyword">end</span>
    result1 = result1+x(:,k);
<span class="keyword">end</span>
runtime(1) = toc;
</pre><h4>Second Method<a rel="nofollow" name="268c5a14-73fe-439d-8a70-9c107435afbe"></a></h4><p>In this method, we extract the column of interest first in the outer loop, and reuse that temporary array each time through the inner loop. Again we see and time the results.</p><pre class="codeinput">tic
<span class="keyword">for</span> k = 1:n
    xt = x(:,k);
    <span class="keyword">for</span> z = 1:n
        result2(z) = myfun(xt, z);
    <span class="keyword">end</span>
    result2 = result2+x(:,k);
<span class="keyword">end</span>
runtime(2) = toc;
</pre><h4>Same Results?<a rel="nofollow" name="9ccb7a79-b332-4e32-abe0-81a3ed286deb"></a></h4><p>First, let's make sure we get the same answer both ways.  You can see that we do.</p><pre class="codeinput">theSame = isequal(result1,result2)
</pre><pre class="codeoutput">theSame =
     1
</pre><h4>Compare Runtime<a rel="nofollow" name="6ae5ef22-d2db-4d73-9f37-b3d80d85f82d"></a></h4><p>Next, let's compare the times.  I want to remind you that doing timing from a script generally has more overhead than when the same code is run inside a function.  We just want to see the relative behavior so we should get some insight from this exercise.</p><pre class="codeinput">disp([<span class="string">'Run times are: '</span>,num2str(runtime)])
</pre><pre class="codeoutput">Run times are: 2.3936      1.9558
</pre><h4>What's Happening?<a rel="nofollow" name="aea57373-3b4c-4692-ad92-ac8c6dfe920c"></a></h4><p>Here's what's going on.  In the first method, we create a temporary variable <tt>n</tt> times through the outer loop, even though that array is a constant for a fixed column.  In the second method, we extract the relevant column once, and reuse it <tt>n</tt> times through the inner loop.</p><p>Be thoughtful if you do play around with this.  Depending on the details of your function, if the calculations you do each time are large compared to the time to extract a column vector, you may not see much difference between the two methods.  However, if the calculations are sufficiently short in duration, then the repeated creation of the temporary variable could add a tremendous amount of overhead to the calculation.  In general, you should not be worse off always capturing the temporary array the fewest number of times possible.</p><h4>Your Results?<a rel="nofollow" name="b2f25522-87bc-4cc4-a85d-00bc6f60d4fc"></a></h4><p>Have you noticed similar timing "puzzles" when analyzing one of your algorithms?  I'd love to hear more <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=688#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/9te7pV1k6Q4" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Comparing Runs using Simulation Data Inspector</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/WScoAPqzHng/</link>
         <description>Do you use the Simulation Data Inspector? Here is an example where it saved me a lot of debugging time. Simulation Accuracy I recently had to validate system behavior and analyze numerical accuracy of a model. Making small modifications in one part of the model was leading to unexpectedly large differences at the outputs. Since [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2169</guid>
         <pubDate>Fri, 03 May 2013 15:34:33 +0000</pubDate>
         <content:encoded><![CDATA[<p>Do you use the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/simulation-data-inspector-overview.html">Simulation Data Inspector</a>? Here is an example where it saved me a lot of debugging time.</p>

<p><strong>Simulation Accuracy</strong></p>

<p>I recently had to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/validate-system-behavior.html">validate system behavior</a> and analyze numerical accuracy of a model. Making small modifications in one part of the model was leading to unexpectedly large differences at the outputs. Since the model was very large, I thought it would be painful to insert <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/scope.html">Scopes</a> or <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/toworkspace.html">To Workspace</a> blocks in the model to try identifying the source of the problem.</p>

<p>I found out that the Simulation Data Inspector can be very useful to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/comparison-of-all-logged-signal-data-from-multiple-simulations.html">compare simulation results</a> without adding blocks to your model and without writing any scripts. Let's see how this work!</p>

<p><strong>Logging Signals</strong></p>

<p>The first step is to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/configuring-a-signal-for-signal-logging.html">configure signals for logging</a>. I like to use the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/ug/the-model-explorer-overview.html">Model Explorer</a> for that. It is significantly faster than right-clicking on the signal lines one by one. Here are a few tips to configure the Model Explorer with the goal of controlling signal logging.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/configure_logging.png" alt="Configuring signals for logging using the model explorer"/></p>

<p>Also, ensure that signal logging is enabled in the model configuration.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/enable_logging.png" alt="Enabling logging"/></p>

<p><strong>Record &#038; Inspect Simulation Output</strong></p>

<p>In your model, click on the Record button.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/enable_sdi.png" alt="Record &#038; Inspect Simulation Output"/></p>

<p>When the simulation is completed, open the Simulation Data Inspector using the link that pops up.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/launching_sdi.png" alt="Launching Simulation Data Inspector"/></p>

<p><strong>Compare Runs</strong></p>

<p>Make some changes to your model and simulate it again. In the Simulation Data Inspector, go to the <strong>Compare Runs</strong> Tab, select your 2 runs and click <strong>Compare</strong>.</p>

<p>Using the absolute tolerance I specified, the Simulation data Inspector helped me to quickly identify where the divergence appear in my model.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/compare_runs.png" alt="Comparing Runs in Simulation Data Inspector"/></p>



<p><strong>Now it's your turn</strong></p>

<p>Give a look and the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/validate-system-behavior.html">Validate System Behavior</a> section of the documentation to learn more about the Simulation Data Inspector and let us know if it helps your workflow by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2169&#comment">comment here</a>.






<img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/WScoAPqzHng" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Raspberry Pi DC Motor Driver</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/vtFfv1dlqTg/</link>
         <description>Doug's pick this week is Raspberry Pi DC Motor H-Bridge Driver Block by Joshua Hurst. As my previous posts may suggest, I've been a long-time fan of the Arduino platform. Among other things I use it as the basis of a demonstration to showcase a variety of MathWorks' tools that includes driving a motor to [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4536</guid>
         <pubDate>Fri, 03 May 2013 13:00:27 +0000</pubDate>
         <content:encoded><![CDATA[<a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/62957">Doug</a>'s pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/41528-raspberry-pi-dc-motor-h-bridge-driver-block-sfunction">Raspberry Pi DC Motor H-Bridge Driver Block</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/319689">Joshua Hurst</a>.
<br /><br />
As my previous posts may suggest, I've been a long-time fan of the Arduino platform. Among other things I use it as the basis of a demonstration to showcase a variety of MathWorks' tools that includes driving a motor to rotate a camera to track an object. The Arduino works great for doing closed-loop position control of the camera, but falls short when it comes to actually processing the camera video to detect the object. So currently the video processing is relegated to my laptop which prevents me from creating a completely embedded solution.
<br /><br />
Enter R2013a which introduced support for a number of new target platforms which <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2013/03/15/additional-hardware-support-in-r2013a/">Jiro pointed out</a> earlier this year. I was drawn to Raspberry Pi in particular because it is a similar price and form factor to the Arduino, but has built-in support for USB webcams:
<br /><br />
<img src="http://www.mathworks.com/images/nextgen/supporting/academia/hardware-resources/raspberry-pi-gallery-image-3.jpg" alt="Raspberry Pi Block Library"/>
<br /><br />
Looking at the blocks that are included with the target, however, you'll notice that there is nothing included for sending voltages to a DC Motor like you can do with the Arduino PWM Output blocks. Because of that I had initially planned to use both the Raspberry Pi and Arduino for my demo until I ran across Joshua's submission the other day. His model uses S-Function Builder blocks to take advantage of the new <a rel="nofollow" target="_blank" href="https://projects.drogon.net/raspberry-pi/wiringpi/">WiringPi</a> support in the Raspberry Pi image that is used in the support package. Here's the top-level of Joshua's model:
<br /><br />
<img src="http://blogs.mathworks.com/pick/files/MotorDriverModel.png" alt="Motor Driver Model"/>
<br /><br />
After some breadboard work, I built and downloaded the model and I was controlling my motor in minutes by simply changing the Input Volts value in External Mode. Now I just need to decide on the best way to read the motor's potentiometer then the whole system can run on the Pi. Or perhaps I should bite the bullet and switch to an encoder. If anyone has any suggestions, leave a comment! 
<br /><br />
I was happy to see that Joshua was inspired by Giampiero's <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/39354-device-drivers">Device Driver guide</a> that explains how to create custom drivers for the hardware support packages. Joshua has also recently uploaded several other related submissions. I'm looking forward to seeing what Joshua and others come up with in the future to increase the I/O options for the different hardware platforms.
<br /><br />
One minor suggestion I would have for Joshua is to include the pin numbers that correspond to the PWM outputs for this model. I had to do a bit of hunting to track that down (it's 7 and 11 on the P1 header for those that are interested). But other than that, this submission has been a big help, thanks Joshua!
<br /><br />
<strong>Comments</strong><br />
Let us know what you think <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4536#respond">here</a> or leave a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/41528-raspberry-pi-dc-motor-h-bridge-driver-block-sfunction/#comments">comment</a> for Joshua.<img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/vtFfv1dlqTg" height="1" width="1"/>]]></content:encoded>
         <category>Simulink</category>
      </item>
      <item>
         <title>Speeding up User Interfaces in MATLAB with profiler</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/2mFpr8eP0sw/</link>
         <description>Sometimes when you are working on a User Interface you want to use the profiler to speed up the code. However, with a UI so much time can be spent by the user rather than the code of interest that the timing is not as precise as would be preferred. I like this technique so [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1101</guid>
         <pubDate>Fri, 03 May 2013 12:51:07 +0000</pubDate>
         <content:encoded><![CDATA[Sometimes when you are working on a User Interface you want to use the profiler to speed up the code.  However, with a UI so much time can be spent by the user rather than the code of interest that the timing is not as precise as would be preferred.

<p>
<p>
I like this technique so that I can do <em>ad hock</em> timings as needed in a complicated User Interface in MATLAB.
<p>
<p>

<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate305" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/2mFpr8eP0sw" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>JPEG and PNG – lossy and lossless image compression</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/nWM8uqZ7r90/</link>
         <description>I was reviewing enhancement requests recently when I came across this one: Add support for a 'Quality' parameter when using imwrite to write a PNG file, just like you can currently do when writing a JPEG file.Well, there is actually a pretty good reason why there is no 'Quality' parameter for writing PNG files, but [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=835</guid>
         <pubDate>Thu, 02 May 2013 20:45:41 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>I was reviewing enhancement requests recently when I came across this one: <i>Add support for a 'Quality' parameter when using <tt>imwrite</tt> to write a PNG file, just like you can currently do when writing a JPEG file.</i></p><p>Well, there is actually a pretty good reason why there is no 'Quality' parameter for writing PNG files, but it's not an obvious reason unless you know more about the differences between various image compression methods.</p><p>A very important characteristic of a compression method is whether it is <i>lossless</i> or <i>lossy</i>. With a <i>lossless</i> compression method, the original data can be recovered exactly. When you make a "zip" file on your computer, this is what you certainly expect.</p><p>Here's an example: I can use <tt>gzip</tt> to compress the MATLAB script file I'm using for this blog post.</p><pre class="codeinput">gzip(<span class="string">'lossless_lossy.m'</span>);
dir(<span class="string">'lossless_lossy.*'</span>)
</pre><pre class="codeoutput">
lossless_lossy.m     lossless_lossy.m.gz  

</pre><p>Let's compare their sizes to see if the output of <tt>gzip</tt> is really compressed.</p><pre class="codeinput">d1 = dir(<span class="string">'lossless_lossy.m'</span>);
d1.bytes
</pre><pre class="codeoutput">
ans =

        4098

</pre><pre class="codeinput">d2 = dir(<span class="string">'lossless_lossy.m.gz'</span>);
d2.bytes
</pre><pre class="codeoutput">
ans =

        1785

</pre><p>Indeed, the compressed does actually have fewer bytes. Can we get the original file back exactly?</p><pre class="codeinput">gunzip(<span class="string">'lossless_lossy.m.gz'</span>,<span class="string">'./tmp'</span>)
isequal(fileread(<span class="string">'lossless_lossy.m'</span>),fileread(<span class="string">'./tmp/lossless_lossy.m'</span>))
</pre><pre class="codeoutput">
ans =

     1

</pre><p>Yes.</p><p>Let's switch to image formats. The PNG image format uses lossless compression. When you save image data to a PNG file, you can read the file back in and get back the original pixels, unchanged. For a sample image I'll use my <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/35961-zone-plate-test-image/content/imzoneplate.m">imzoneplate function</a> on the MATLAB Central File Exchange.</p><pre class="codeinput">I = im2uint8(imzoneplate);
imshow(I)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/lossless_lossy_01.png" alt=""> <p>Let's write <tt>I</tt> out to a PNG file, read it back in, and see if the pixels are the same.</p><pre class="codeinput">imwrite(I,<span class="string">'zoneplate.png'</span>);
I2 = imread(<span class="string">'zoneplate.png'</span>);
isequal(I,I2)
</pre><pre class="codeoutput">
ans =

     1

</pre><p>OK, now let's try the same experiment using JPEG.</p><pre class="codeinput">imwrite(I,<span class="string">'zoneplate.jpg'</span>)
I2j = imread(<span class="string">'zoneplate.jpg'</span>);
isequal(I,I2j)
</pre><pre class="codeoutput">
ans =

     0

</pre><p>No, the pixels are not equal! It turns out the JPEG is a <i>lossy</i> image compression format. (Full disclosure: there is a lossless variant of JPEG, but it is rarely used.)</p><p>Why in the world would we use a compression format that doesn't preserve the original data? Because by giving up on exact data recovery and by taking advantage of properties of human visual perception, we can make the stored file a lot smaller. Let's compare the file sizes of the PNG file with the JPEG file.</p><pre class="codeinput">z1 = dir(<span class="string">'zoneplate.png'</span>);
num_bytes_png = z1.bytes
</pre><pre class="codeoutput">
num_bytes_png =

      218864

</pre><pre class="codeinput">z2 = dir(<span class="string">'zoneplate.jpg'</span>);
num_bytes_jpeg = z2.bytes
</pre><pre class="codeoutput">
num_bytes_jpeg =

       72660

</pre><p>The JPEG file is only one-third the size of the PNG file! But it looks almost exactly the same.</p><pre class="codeinput">imshow(<span class="string">'zoneplate.jpg'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/lossless_lossy_02.png" alt=""> <p>So, what about that <tt>'Quality'</tt> parameter that I mentioned at the top of today's post? It turns out that we can make the JPEG file even smaller if we are willing to put up with some visible distortion in the image. Let's try a quality factor of 25. (The default is 75 on a scale of 0 to 100.)</p><pre class="codeinput">imwrite(I,<span class="string">'zoneplate_25.jpg'</span>,<span class="string">'Quality'</span>,25)
I2j_25 = imread(<span class="string">'zoneplate_25.jpg'</span>);
imshow(I2j_25)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/lossless_lossy_03.png" alt=""> <p>You can see some distortion, especially around the high-frequency part of the pattern. How about the file size?</p><pre class="codeinput">z3 = dir(<span class="string">'zoneplate_25.jpg'</span>);
z3.bytes
</pre><pre class="codeoutput">
ans =

       39544

</pre><p>That's about 54% of the size of the zoneplate.jpg.</p><p>Sometimes people think they can get "lossless JPEG" by using a <tt>'Quality'</tt> factor of 100, but unfortunately that isn't the case. Let's check it:</p><pre class="codeinput">imwrite(I,<span class="string">'zoneplate_100.jpg'</span>,<span class="string">'Quality'</span>,100)
I2j_100 = imread(<span class="string">'zoneplate_100.jpg'</span>);
isequal(I,I2j_100)
</pre><pre class="codeoutput">
ans =

     0

</pre><p>So there you go -- that's why there's no <tt>'Quality'</tt> parameter when writing PNG files. PNG files are always perfect!</p><p>When I write blog posts, sometimes I use PNG image files and sometimes I use JPEG. My choice is based on what kind of graphics I have in that particular post. And that's a blog topic for another day.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/nWM8uqZ7r90" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Data Tips on MATLAB Mobile</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/ng82MEpzQt0/</link>
         <description>It has been a while since we last talked about displaying data tips on MATLAB Mobile. The data cursor feature has since then evolved from tap-and-hold invocation to a more prominent ‘Show Data Cursor’ button. Tapping on this button brings up the crosshair. Move the crosshair to any location on the figure to display the [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2222</guid>
         <pubDate>Wed, 01 May 2013 14:15:38 +0000</pubDate>
         <content:encoded><![CDATA[<p>It has been a while since we last <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2011/01/31/matlab-mobile-12-released/">talked</a> about displaying data tips on MATLAB Mobile.</p>
<p>The data cursor feature has since then evolved from tap-and-hold invocation to a more prominent ‘Show Data Cursor’ button. Tapping on this button brings up the crosshair. Move the crosshair to any location on the figure to display the coordinates of that location.</p>
<p>We’re happy to announce that the latest release of MATLAB Mobile for Android supports this feature, much like its iOS counterpart.</p>
<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/datacursor1.png"><img class="alignnone size-large wp-image-2220" title="Tap on Show Data Cursor" src="http://blogs.mathworks.com/community/files/datacursor1-586x1024.png" alt="Tap on Show Data Cursor" width="282" height="491"/></a><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/datacursor2.png"><img class="alignnone size-large wp-image-2221" title="Position crosshair at desired location" src="http://blogs.mathworks.com/community/files/datacursor2-586x1024.png" alt="Position crosshair at desired location" width="282" height="491"/></a></p>
<p><strong><em>                     Tap on Show Data Cursor                                    Position crosshair at desired location</em></strong></p>
<p style="text-align:left;">Download MATLAB Mobile from <a rel="nofollow" target="_blank" href="https://play.google.com/store/apps/details?id=com.mathworks.matlabmobile">Google Play</a>.</p>
<p>If you have used the data cursor functionality on your mobile device, we would love to hear from you. Leave us a comment <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/?p=2222#respond">here </a>with your thoughts.</p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/ng82MEpzQt0" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Pentium Division Bug Revisited</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/wlOiCjJcM7k/</link>
         <description>The Pentium division bug episode in the fall of 1994 was a defining moment for the MathWorks, for the Internet, for Intel Corporation, and for me personally. In this blog I am reprinting the article that I wrote for the Winter 1995 issue of MATLAB News and Notes and for SIAM News. In my next [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=589</guid>
         <pubDate>Mon, 29 Apr 2013 17:00:49 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>The Pentium division bug episode in the fall of 1994 was a defining moment for the MathWorks, for the Internet, for Intel Corporation, and for me personally.  In this blog I am reprinting the article that I wrote for the Winter 1995 issue of MATLAB News and Notes and for SIAM News.  In my next blog I want to discuss the episode's impact.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#a46fa584-a8d4-4639-9567-076d1e81b389">A Tale of Two Numbers (Reprinted from MATLAB News and Notes, Winter 1995)</a></li><li><a rel="nofollow" href="#34552650-affd-4c89-ba72-1167094318c6">Thomas Nicely</a></li><li><a rel="nofollow" href="#9a1a7494-2828-47d2-b7c1-10e5d0155efb">Alex Wolfe</a></li><li><a rel="nofollow" href="#a3e80685-b94c-4527-955b-7a904b127178">Terje Mathisen</a></li><li><a rel="nofollow" href="#d55a83b9-dc33-4a74-93f5-d10fb65fbc04">Tim Coe</a></li><li><a rel="nofollow" href="#5f737c9c-31a5-48fb-8935-54c509115b09">Press Coverage</a></li><li><a rel="nofollow" href="#1baa927c-85e7-4f40-a1f3-4096b18ee8aa">Peter Tang</a></li><li><a rel="nofollow" href="#c7388acb-ae3c-496c-912d-e71c58a4d8d8">SRT Algorithm</a></li><li><a rel="nofollow" href="#d0ff0ffb-3973-49a7-b1ac-0e62b14ddc9b">Our Workaround</a></li><li><a rel="nofollow" href="#5037fa8b-05f7-4bdb-818f-126e38a119cb">Pentium-Safe Division</a></li></ul></div><h4>A Tale of Two Numbers (Reprinted from MATLAB News and Notes, Winter 1995)<a rel="nofollow" name="a46fa584-a8d4-4639-9567-076d1e81b389"></a></h4><p>This is the tale of two numbers, and how they found their way over the Internet to the world's front pages on Thanksgiving day, embarrassing the world's premier computer chip manufacturer.</p><h4>Thomas Nicely<a rel="nofollow" name="34552650-affd-4c89-ba72-1167094318c6"></a></h4><p>The first number is a twelve digit integer</p><p>$$ p  =  824633702441 $$</p><p>Thomas Nicely of Lynchburg College in Virginia is interested in this number because both <i>p</i> and <i>p+2</i> are prime. Two consecutive odd numbers that are both prime are called <i>twin primes</i>. Nicely's research involves the distribution of twin primes and, in particular, the sum of their reciprocals,</p><p>$$ S = 1/5 + 1/7 + ... + 1/29 + 1/31 + ... + 1/p + 1/(p+2) + ... $$</p><p>It is known that this infinite sum has a finite value, but nobody knows what that value is.  For over a year, Nicely has been carrying out various computations involving twin, triple and quadruple primes. One of his objectives has been to demonstrate that today's PCs are just as effective as supercomputers for this kind of research. He was using half a dozen different computers in his work until March, when he added a machine based on Intel Corporation's Pentium chip to this collection.</p><p>In June, Nicely noticed inconsistencies among several different quantities he was computing.  He traced it to the values he was getting for $1/p$ and $1/(p+2)$.  Although he was using double precision, they were accurate only to roughly single precision. He blamed at first on his own programs, then the compiler and operating system, then the bus and motherboard in his machine. By late October though, he was convinced that the difficulty was in the chip itself.</p><h4>Alex Wolfe<a rel="nofollow" name="9a1a7494-2828-47d2-b7c1-10e5d0155efb"></a></h4><p>On October 30, in an e-mail message to several other people who had access to Pentium systems, Nicely said that he thought there was a bug in the processor's floating point arithmetic unit.  One of the recipients of Nicely's memo posted it on the CompuServe network. Alex Wolfe, a reporter for the EE Times, spotted the posting and forwarded it to Terje Mathisen.</p><h4>Terje Mathisen<a rel="nofollow" name="a3e80685-b94c-4527-955b-7a904b127178"></a></h4><p>Terje Mathisen, a computer jock at Norsk Hydro in Oslo, Norway, has published articles on programming the Pentium, and posted notes on the Internet about the accuracy of its transcendental functions. Within hours of receiving Wolfe's query, Mathisen confirmed Nicely's example, wrote a short, assembly language test program, and, on November 3, initiated a chain of Internet postings in newsgroup <tt>comp.sys.intel</tt> about the FDIV bug.  (FDIV is the floating point divide instruction on the Pentium.)  A day later, Germany's Andreas Kaiser posted a list of two dozen numbers whose reciprocals are computed to only single precision accuracy on the Pentium.</p><h4>Tim Coe<a rel="nofollow" name="d55a83b9-dc33-4a74-93f5-d10fb65fbc04"></a></h4><p>Tim Coe is an engineer at Vitesse Semiconductor in southern California. He has designed floating point arithmetic units himself and saw in Kaiser's list of erroneous reciprocals clues to how other designers had tackled the same task.  He surmised, correctly it turns out, that the Pentium's division instruction employs a technique known to chip designers as a radix 4 SLT algorithm.  This produces two bits of quotient per machine cycle and thereby makes the Pentium twice as fast at division as previous Intel chips running at the same clock rate.</p><p>Coe created a model that explained all the errors Kaiser had reported in reciprocals.  He also realized that division operations involving numerators other than one potentially had even larger relative errors. His model lead him to a pair of seven digit integers whose ratio</p><p>$$ c  =  4195835 / 3145727 $$</p><p>appeared to be an instance of the worst case error.   Coe did his analysis without actually using a Pentium -- he doesn't own one. To verify his prediction, he had to bundle his year-and-a-half old daughter into his car, drive down to a local computer store, and borrow a demonstration machine.</p><p>This true value of Coe's ratio is</p><p>$$ c  =  1.33382044... $$</p><p>But computed on a Pentium, it is</p><p>$$ c  =  1.33373906... $$</p><p>The computed quotient is accurate to only 14 bits.  The relative error is $6.1 &#92;cdot 10^{-5}$.  This is worse than single precision roundoff error and over ten orders of magnitude worse than what we expect from double precision computation.  The error doesn't occur very often, but when it does, it can be very significant.  We are faced with a very small probability of making a very big error.</p><h4>Press Coverage<a rel="nofollow" name="5f737c9c-31a5-48fb-8935-54c509115b09"></a></h4><p>I first learned of the FDIV bug a few days before Coe's revelation from an electronic mailing list maintained by David Hough; at that point I began to follow <tt>comp.sys.intel</tt>.  At first, I was curious but not alarmed. It seemed to be some kind of single- versus double-precision problem which, although annoying, is not all that uncommon.  But Coe's discovery, together with a couple of customer calls to The MathWorks tech support, raised my level of interest considerably.</p><p>On November 15, I posted a summary of what I knew then to both the Intel and the MATLAB newsgroups, using Nicely's prime and Coe's ratio as examples. I also pointed out that the divisor in both cases is a little less than 3 times a power of two:</p><p>$$ 824633702441  =  3 &#92;cdot 2^{38} - 18391 $$</p><p>and</p><p>$$ 3145727  =  3 &#92;cdot 2^{20} - 1 $$</p><p>By this time, the Net had become hyperactive and my posting was redistributed widely.  A week later, reporters for major newspapers and news services had Xeroxed copies of faxed copies of printouts of my posting.</p><p>The story began to get popular press coverage when Net activists called their local newspapers and TV stations.  I was interviewed by CNN on Tuesday, the 22nd, and spent most of the next day on the telephone with other reporters.  My picture was in the <i>New York Times</i> and the <i>San Jose Mercury News</i> on Thursday which happened to be Thanksgiving. The <i>Times</i> story included a sidebar, titled "Close, But Not Close Enough", which used Coe's ratio to illustrate the problem. The story was front-page news in the <i>Boston Globe</i>, with the headline "Sorry, Wrong Number." The <i>Globe</i>'s sidebar demonstrated the error by evaluating Coe's ratio in a spreadsheet.</p><p>In the month since I learned of Nicely's prime and Coe's ratio they have certainly earned their place in the Great Numbers Hall of Fame.</p><p>One challenging aspect of this has been how to explaing to the press how big the error is. The focus of attention has been on what we numerical analysts call the residual,</p><p>$$ r  =  4195835 - (4195835 / 3145727) (3145727) $$</p><p>With exact computation, <i>r</i> would be zero, but on the Pentium it is 256. To most people, 256 seems like a pretty big error.  But when compared to the input data, of course, it doesn't seem so large.  This gets us into relative error and significant digits -- terms that are not encountered in everyday journalistic prose.  There was even confusion on the part of some reporters about where to starting counting "decimal digits". Not everybody got the details right.  The <i>New York Times</i> was the only publication I saw that thought to show the actual value of the erroneous quotient.  The British publication, <i>The Economist</i>, had the good sense to describe the error as 0.006%.  In retrospect, perhaps the best description of the error is "about 61 parts per million."</p><p>Since double precision floating point computation is vital to MATLAB, and since Pentium-based machines account for a significant portion of new MATLAB usage, we decided early on to provide a release of our software that works around the bug.  My first thought was to modify our source code so that every division operation</p><pre>   |z = x/y|</pre><p>was followed by a residual calculation</p><pre>   |r = x - y*z|</pre><p>When the residual is too large, the division could be redone in software using Newton's method.  We abandoned both aspects of this approach -- we don't compute the residual, and we don't do software emulation.</p><h4>Peter Tang<a rel="nofollow" name="1baa927c-85e7-4f40-a1f3-4096b18ee8aa"></a></h4><p>Coe, Mathisen and I are now working with Peter Tang of Argonne Laboratory (on sabbatical in Hong Kong) and a group of hardware and software engineers from Intel, who are in California and Oregon.  We have never met face-to-face. Our collaboration is all by e-mail and telephone.  (11 am in Massachusetts is 8 am in California and Oregon, 5 pm in Oslo and 1 am in Hong Kong.) We are developing, implementing, testing and proving the correctness of software that will work around the FDIV bug and related bugs in the Pentium's on-chip tangent, arctangent and remainder instructions.  We will offer the software to compiler vendors, commercial software developers and individuals folks via the Net.  We hope this software will be used by anyone doing floating point arithmetic on a Pentium who is unable to replace the chip.</p><h4>SRT Algorithm<a rel="nofollow" name="c7388acb-ae3c-496c-912d-e71c58a4d8d8"></a></h4><p>The Pentium's division woes can be traced to five missing entries in a lookup table that is actually part of the chip's circuitry.  The radix-4 SRT algorithm is a variation of the familiar long division technique we all earned in school.  Each step of the algorithm takes one machine cycle and appends another two-bit digit to the quotient. Both the quotient and the remainder are represented in a redundant fashion as the difference between two numbers.  In this way, the next digit of the quotient can be obtained by table lookup, with several high-order bits from both the divisor and remainder used as indices into the table. The table is not rectangular; a triangular portion of it is eliminated by constraints on the possible indices.</p><p>When the algorithm was implemented in silicon, five entries on the boundary of this triangular portion were dropped.  These missing entries (each of which should have a value of +2) effectively mean that, for certain combinations of bits developed during the division process, the chips make an error while updating the remainder.</p><h4>Our Workaround<a rel="nofollow" name="d0ff0ffb-3973-49a7-b1ac-0e62b14ddc9b"></a></h4><p>The key to our workaround is the fact the chip does a perfectly good job with division almost all the time.  It is simply a question of avoiding the operands that don't work very well,  which our software does with a quick test of the divisor before each attempted FDIV.  The absence of dangerous bit patterns indicates that the FDIV can be done safely. The presence of one of the patterns does not guarantee that the error will occur, just a signal that it might.  In this case, scaling both numerator and denominator by 15/16 takes the divisor out of the unsafe region and insures that the subsequent division will be fully accurate.</p><p>With this approach, it is not necessary to test the magnitude of the residual resulting from a division.  It is known <i>a priori</i> that all divisions will produce fully accurate results.  If desired, an additional test can compare the result of scaled and unscaled divisions and count the number of errors that would occur on an unmodified Pentium.  We will offer this test in MATLAB, but it can be turned off for maximum execution speed.</p><p>The regions to be avoided can be characterized by examining the high order bits of the fraction in the IEEE floating point representation. Floating point numbers in any of the three available precisions can be thought of as real numbers of the form</p><p>$$ &#92;pm (1 + f ) &#92;cdot 2^e $$</p><p>where <i>e</i> is an integer in the range determined by under- and overflow and <i>f</i>  is a rational number in the half open interval [0, 1). The eight high order bits of <i>f</i> divide this interval into $2^8$ = 256 subintervals.  Five of these subintervals contain all the at-risk divisors. The hexadecimal representations of the leading bits of the five subintervals are</p><pre>  1F, 4F, 7F, AF, and DF</pre><p>(As I write this article, Coe, Tang and some of the Intel people are still working on a proof of correctness.  The ultimate version of the algorithm may well use more than eight bits, but the idea will be the same.)</p><p>A picture of the floating point numbers between any two powers-of-two looks something like this</p><pre>  [____()______()______()______()______()____]
           1F      4F      7F      AF      DF</pre><p>The length of each of the five subintervals is 1/256 of the overall length. The result of any division involving a divisor outside these subintervals will be accurate.  Only a small fraction of divisions involving divisors inside the subintervals produce erroneous results, but it is easiest, and quickest, to avoid the subintervals altogether.  Scaling the numerator and denominator by 15/16 shifts it to a safe region.  (I had originally proposed scaling by 3/4, but this takes the 7Fthird subinterval into the 1F subinterval.)</p><p>For example, the denominator in Coe's ratio is</p><p>$$ 3145727  =  1.49999952316284 &#92;cdot 2^{21} $$</p><p>The hexadecimal representation is printed as <tt>4147FFFF80000000</tt>. So <i>e</i>= 21  and <i>f</i> = $2^{-1} - 2^{-21}$, and the number is close to the right end point of the 7F subinterval.  The 17 consecutive high order 1 bits in <i>f</i> conspire with the bits in Coe's numerator to produce an instance of worst-case error.</p><p>The Pentium, like most other microprocessors, saves floating point numbers in memory with either a 32-bit single precision format, or a 64-bit double precision format.  In the floating point arithmetic unit itself, however, an 80-bit extended-precision format is used for the calculations. Thus, if an at-risk denominator is encountered in either single or double precision, it can be scaled by 15/16 and extended precision can be used for the division.  Then, when the resulting quotient is rounded back to the working precision, it will yield exactly the same result, down to the last bit, as would be produced by a chip without the bug.</p><h4>Pentium-Safe Division<a rel="nofollow" name="5037fa8b-05f7-4bdb-818f-126e38a119cb"></a></h4><p>The entire algorithm can be summarized in a few lines of MATLAB pseudo-code. This doesn't actually work, because MATLAB doesn't do bit-level operations on floating point numbers.  Moreover, we do not make the distinction between the 64- and 80-bit representations that ensure full accuracy when scaling is required.  But I hope this explanation has given readers an idea of the thinking that went into the workaround.</p><p>The algorithm is:</p><pre>  function z = fdiv(x,y)
    if at_risk(y)
       x = (15/16)*x;
       y = (15/16)*y;
    end
    z = x/y;
  end</pre><p>The safety filter is:</p><pre>  function a = at_risk(y)
     f = and(hex(y),'000FF00000000000');
     a = any(f == ['1F'; '4F'; '7F'; 'AF'; 'DF'])
  end</pre><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/wlOiCjJcM7k" height="1" width="1"/>]]></content:encoded>
         <category>History</category>
      </item>
      <item>
         <title>Zero-Crossing Detection… what are your options?</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/SRVn27I06DE/</link>
         <description>When using Simulink variable-step solvers, zero-crossing detection is very useful to capture events accurately. However for some equations, configuring zero-crossing detection can be challenging. Last week I received the following question and example model: In the attached model, I implemented a basic bang-bang controller for a plow. Using a Sign block, I generate a 1 [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=1935</guid>
         <pubDate>Fri, 26 Apr 2013 19:11:15 +0000</pubDate>
         <content:encoded><![CDATA[<p>When using Simulink variable-step solvers, <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/ug/simulating-dynamic-systems.html#f7-9506">zero-crossing detection</a> is very useful to capture events accurately. However for some equations, configuring zero-crossing detection can be challenging.</p>

<p>Last week I received the following question and example model:</p>

<p><em>In the attached model, I implemented a basic bang-bang controller for a plow. Using a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012a/toolbox/simulink/slref/sign.html">Sign</a> block, I generate a 1 for the plow to go up, -1 to go down and 0 to stop. The problem is that the plow never seems to stabilize around zero. Can you help me understand why?</em></p>

<p>Here is an image of the model:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/initialPlowModel.png" alt="Bang Bang Controller for a plow"/></p>

<p><strong>Nonadaptive zero-crossing detection</strong></p>

<p>With the default settings, this model errors out as soon as we try to give a non-zero command with the following error:</p>

<p><font color="red"><tt>At time 1.0000000000236877, simulation hits (1000) consecutive zero crossings. Consecutive zero crossings will slow down the simulation or cause the simulation to hang. To continue the simulation, you may 1) Try using Adaptive zero-crossing detection algorithm or 2) Disable the zero crossing of the blocks shown in the following table. <br />
--------------------------------------------------------------------------------<br />
Number of consecutive zero-crossings : 1000<br />
Zero-crossing signal name : Input<br />
Block type : Signum<br />
Block path : 'myPlowController/Sign'<br />
--------------------------------------------------------------------------------<br />
You can turn off this message by using the MATLAB command: <br />
set_param('myPlowController','MaxConsecutiveZCsMsg','none'); </tt></font></p>

<p>This error is relatively simple to understand by looking at the ideal plant model (an Integrator block) and the switching logic. If the plow position is slightly negative, the controller makes it move upward, leading to a positive error. The controller sees this positive error, makes the plow go down, bringing us back to our original state .</p>

<p>With zero-crossing detection enabled for the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/sign.html">Sign</a> block, Simulink will detect that we crossed zero and try to reduce its step-size to capture this transition accurately. But here, reducing the step size will not help. The step size can be a small as possible, a small negative error will always lead to a jump on the positive side, and vice-versa.</p>

<p>Let's try the suggestions offered by the error message.  What suggestions? If you didn't read the error message, go back and read it now.</p>

<p><strong>Suggestion 1: Adaptive zero-crossing detection</strong></p>

<p>In the solver section of the model configuration, we can try selecting <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/gui/solver-pane.html#bq9z2nq-1">adaptive zero-crossing detection</a>. This will dynamically activate and deactivate zero-crossing bracketing, helping with models that exhibit strong chattering.

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/adaptiveZC.png" alt="Adaptive zero-crossing detection"/></p>

<p>With this setting the simulation completes, but the variable step solver takes way too many steps when it is not needed, and the position error is too large.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/adaptive_results.png" alt="Simulation results with adaptive zero-crossing detection"/></p>

<p>The reason is that the adaptive algorithm encountered multiple consecutive zero-crossings for the Sign block and decided to disable zero-crossing detection for this block. Once this is done, the solver takes larger steps and gives inaccurate results.</p>

<p>Let's try suggestion 2 from the error message.</p>

<p><strong>Suggestion 2: Disabling zero-crossing</strong></p>

<p>The second suggestion from the error message is to disable zero-crossing detection for the problematic block.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/disableZC.png" alt="Sign block with disabled ZC"/></p>

<p>In this case, the tracking is significantly better because the solver uses the state of the integrator to limit its step size, but we see a lot of switching happening when the plow desired height is constant.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/disabled_zc.png" alt="results with zero-crossing disabled"/></p>

<p>The main problem here is that it is impossible for the Simulink engine to stop exactly on the zero value of the Sign block with this system. With the equations involved, Simulink can take very small steps around zero, but will not stop exactly on it. This not what the Sign block is designed to do.</p>

<p><strong>Possible solutions</strong></p>

<p>If we want a system that can be simulated efficiently using a variable step solver, we have to modify the equations. If we want to keep the plant as it is, we need a controller with a logic that will stop when the error is within a certain range around zero. For example, we could use a Stateflow chart or a block with <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Hysteresis">hysteresis</a> like the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/relay.html">Relay</a> block:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/controller_with_deadzone.png" alt="Controller with dead zone"/></p>

<p>In this case, the plow stops moving when the command is fixed and the zero-crossing detection helps ensure that the solver takes appropriate steps when needed.

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/modified_results.png" alt="Results of the Controller with dead zone"/></p>

<p><strong>Now it's your turn</strong></p>

<p>If you have some interesting plowing or zero-crossing stories to share, leave a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=1935&#comment">comment here</a></p>


<img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/SRVn27I06DE" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Toggle that Fig</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/QNri0cKkeV8/</link>
         <description>Jiro's pick this week is togglefig by our own Brett Shoelson.Brett and I, along with Bob, started writing for this blog about 5 years ago, back when Doug was still the owner of the blog. Since the beginning, we typically highlighted submissions that were written by the general public and not by one of us. [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4528</guid>
         <pubDate>Fri, 26 Apr 2013 13:00:21 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/15007">Jiro</a>'s pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/18220"><tt>togglefig</tt></a> by our own <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/911">Brett Shoelson</a>.</p><p>Brett and I, along with Bob, started writing for this blog about 5 years ago, back when <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/videos/">Doug</a> was still the owner of the blog. Since the beginning, we typically highlighted submissions that were written by the general public and not by one of us. But ultimately, we like to highlight files that can be of some value to our readers, and I must say that there's no shortage of such files in <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/index?term=authorid%3A911">Brett's entries</a>.</p><p>So what does <tt>togglefig</tt> do? Have you ever wanted to better manage your figure windows? I've often had a need to reuse my figure windows. Once, I was developing some piece of code that created multiple figures, and as I was iterating on my code, I kept creating the same number of windows each time, and I would end up with tens of figure windows open after a while. Of course I could "close all" of them at the beginning of my script, but I had some windows I needed open for other reasons. As a solution, I would create/select figures using some numbers, e.g.</p><pre class="language-matlab">figure(123)
</pre><p>This would always use the same figure window, or create one if it doesn't exist. But I would want to give a meaningful name to it, so then I would need to set the name property after getting the handle to the figure.</p><pre class="codeinput">h = figure(123);
set(h, <span class="string">'Name'</span>, <span class="string">'Important Window'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_togglefig/potw_togglefig_01.png" alt=""> <p>It works, but it's just some extra lines of code that are not adding any value to the real purpose of my program.</p><p>Brett's <tt>togglefig</tt> addresses this in a very elegant manner. It would raise the figure with the specified name, or create one if it doesn't exist.</p><pre class="codeinput">togglefig(<span class="string">'More Important Window'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_togglefig/potw_togglefig_02.png" alt=""> <p>You can also pass in an optional argument to clear the figure window when it's given focus.</p><p>Thanks, Brett, for this extremely useful function that makes me more efficient in using MATLAB!</p><p><b>Comments</b></p><p>Let us know what you think <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4528#respond">here</a> or leave a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/18220#comments">comment</a> for Brett.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/QNri0cKkeV8" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Using Symbolic Math Toolbox to Compute Area Moments of Inertia</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/GAkkzQGU4nE/</link>
         <description>Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years working on the Symbolic Math Toolbox. He has a background in mathematics and computer science. He already contributed to my BLOG in the past writing about Using Symbolic Equations And Symbolic [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=684</guid>
         <pubDate>Fri, 26 Apr 2013 11:14:21 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years working on the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic">Symbolic Math Toolbox</a>. He has a background in mathematics and computer science. He already contributed to my BLOG in the past writing about <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2012/07/27/using-symbolic-equations-and-symbolic-functions-in-matlab">Using Symbolic Equations And Symbolic Functions In MATLAB</a> as well as on approaches for <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2011/10/25/simplifying-symbolic-results">Simplifying Symbolic Results</a>.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#05e69b68-4591-4e86-a7a3-4366fbda2fad">In a Nutshell: What Is This Article About?</a></li><li><a rel="nofollow" href="#510e5d8c-2254-4f99-9565-cc9fb1f1338c">Basic Example: Cross Section of an Elliptical Tube</a></li><li><a rel="nofollow" href="#319f5ba4-64a6-4e2e-b648-831a0818d6ff">Area Moment Of Inertia</a></li><li><a rel="nofollow" href="#3b715d35-70da-4013-bb0b-470df2df3da5">Math Behind This Example</a></li><li><a rel="nofollow" href="#19841dd9-5c50-4448-ba67-76dd636545d3">Symbolic Integration</a></li><li><a rel="nofollow" href="#6c55693e-8593-48c1-90be-48129f5b3b0e">Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters</a></li><li><a rel="nofollow" href="#2415b2ac-5410-444a-8c2b-f15693021763">How to Create MuPAD Graphics Shown in This Article</a></li><li><a rel="nofollow" href="#ebec3076-fed9-49e8-967d-2c5a6a31fea0">Have You Tried Symbolic Math Toolbox?</a></li></ul></div><h4>In a Nutshell: What Is This Article About?<a rel="nofollow" name="05e69b68-4591-4e86-a7a3-4366fbda2fad"></a></h4><p>If you are interested in using MATLAB and the Symbolic Math Toolbox in teaching some basics in mechanical engineering, this might be of interest to you.</p><p>Computing <i>area moments of inertia</i> is an important task in mechanics. For example, area moments of inertia play a critical role in stress, dynamic, and stability analysis of structures. In this article, we use capabilities of the <a rel="nofollow">Symbolic Math Toolbox</a> to compute area moments for cross sections of elliptical tubes.</p><p>We start with a basic case involving only numeric parameters, and then make the computations more general by introducing symbolic parameters.</p><p>All plots used in this article have been created in the <a rel="nofollow" target="_blank" href="http://www.mathworks.de/discovery/mupad.html">MuPAD Notebook app</a>. You can find the source code for these plots at the end of the article.</p><h4>Basic Example: Cross Section of an Elliptical Tube<a rel="nofollow" name="510e5d8c-2254-4f99-9565-cc9fb1f1338c"></a></h4><p>The following picture shows the cross section of an elliptical tube.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/lateralCut.png" alt=""> </p><p>The following ellipses define outer and inner contours of the section:</p><div><ul><li>$y = &#92;pm 2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{9}}$ describe the <i>outer</i> contour line for $x &#92;in [-3,3]$.</li><li>$y = &#92;pm &#92;sqrt{1 - &#92;frac{x^2}{4}}$ describe the <i>inner</i> contour line for $x &#92;in [-2,2]$.</li></ul></div><p>We will compute the area moment of inertia of this section with respect to the $x$-axis.</p><h4>Area Moment Of Inertia<a rel="nofollow" name="319f5ba4-64a6-4e2e-b648-831a0818d6ff"></a></h4><p>The moment of inertia of an area $A$ with respect to the $x$-axis is defined in terms of the double integral</p><p>$$I_x = {&#92;int &#92;int}_A y^2&#92;, &#92;mathrm{d}A.$$</p><p>You can find this definition on <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Second_moment_of_area">Wikipedia</a>.</p><h4>Math Behind This Example<a rel="nofollow" name="3b715d35-70da-4013-bb0b-470df2df3da5"></a></h4><p>In our example, the area $A$ is the hatched area shown in the previous plot. Taking advantage of the symmetry of the section with respect to both the $x$- and $y$-axes, we can restrict our computations to the first quadrant of the $x-y$-plane.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/UpperQuarterLateralCut.png" alt=""> </p><p>To compute the necessary double integral over the hatched area, we divide this area into two separate areas $A1$ and $A2$.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/IntegrationAreas.png" alt=""> </p><p>To compute the final area moment of inertia about the x-axis, we multiply the sum of the double integrals over $A_1$ and $A_2$ by four.</p><p>$$I_x = {&#92;int&#92;int}_A y^2 &#92;, &#92;mathrm dA = 4 &#92;cdot &#92;Big({&#92;int&#92;int}_{A_1}
y^2 &#92;, &#92;mathrm dA_1 + {&#92;int&#92;int}_{A_2} y^2 &#92;, &#92;mathrm dA_2&#92;Big).$$</p><p>Now, we only need to compute these two double integrals. The mathematical theory behind multi-dimensional integration tells us that we can rewrite each of these double integrals in terms of two integrals:</p><p>$$I_1 = {&#92;int&#92;int}_{A_1} y^2 &#92;, &#92;mathrm dA_1 = &#92;int_0^2 &#92;int_{&#92;sqrt{1 -
&#92;frac{x^2}{4}}}^{2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{9}}} y^2 &#92;, &#92;mathrm dy &#92;,
&#92;mathrm dx,$$</p><p>$$I_2 = {&#92;int&#92;int}_{A_2} y^2 &#92;, &#92;mathrm dA_2 = &#92;int_2^3 &#92;int_{0}^{2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{9}}}
y^2&#92;, &#92;mathrm dy&#92;, &#92;mathrm dx.$$</p><p>The <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/int.html"><tt>int</tt></a> function from the Symbolic Math Toolbox can compute these integrals.</p><h4>Symbolic Integration<a rel="nofollow" name="19841dd9-5c50-4448-ba67-76dd636545d3"></a></h4><p>We define $x$ and $y$ as symbolic variables:</p><pre class="codeinput">syms <span class="string">x</span> <span class="string">y</span>;
</pre><p>We start computing the inner integral $&#92;int_{&#92;sqrt{1 - &#92;frac{x^2}{4}}}^{2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{9}}} y^2 &#92;, &#92;mathrm dy$ of $I_1$:</p><pre class="codeinput">innerI1 = int(y^2, y, sqrt(1-x^2/4), 2*sqrt(1-x^2/9))
</pre><pre class="codeoutput">innerI1 =
(8*(9 - x^2)^(3/2))/81 - (4 - x^2)^(3/2)/24
</pre><p>Next, we integrate <tt>innerI1</tt> with respect to $x$ from $0$ to $2$. This provides $I_1$:</p><pre class="codeinput">I1 = int(innerI1, x, 0, 2)
</pre><pre class="codeoutput">I1 =
3*asin(2/3) - pi/8 + (74*5^(1/2))/81
</pre><p>We use the same strategy to compute $I_2$. First, we compute the inner integral $&#92;int_{0}^{2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{9}}} y^2&#92;, &#92;mathrm dy$. Then, we integrate the resulting expression with respect to $x$ from $2$ to $3$:</p><pre class="codeinput">I2 = int(int(y^2, y, 0, 2*sqrt(1-x^2/9)), x, 2, 3);
</pre><p>Hence, the area moment of inertia of the elliptical tube with respect to the $x$-axis is</p><pre class="codeinput">Ix = 4 * (I1 + I2)
</pre><pre class="codeoutput">Ix =
(11*pi)/2
</pre><p>We can approximate the result numerically by using the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/toolbox/symbolic/vpa.html"><tt>vpa</tt></a> function. For example, we approximate the result using 5 significant (nonzero) digits:</p><pre class="codeinput">vpa(Ix, 5)
</pre><pre class="codeoutput">ans =
17.279
</pre><h4>Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters<a rel="nofollow" name="6c55693e-8593-48c1-90be-48129f5b3b0e"></a></h4><p>We can use a numerical integrator, such as MATLAB's <a rel="nofollow" target="_blank" href="http://www.mathworks.de/de/help/matlab/ref/integral2.html"><tt>integral2</tt></a>, to compute the area moment of inertia in the previous example. A numerical integrator might return slightly less accurate results, but other than that there is not much benefit from using symbolic integration there.</p><p>But what if we consider the cross section of a more general elliptical tube whose shape is defined by arbitrary symbolic parameters?</p><p>For example, we want to compute the area moment of inertia of this elliptical tube.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/LateralCutMoreGeneral.png" alt=""> </p><p>Its contour lines are still ellipses, but they are defined by the symbolic parameters $r_1$, $r_2$, $R_1$ and $R_2$:</p><div><ul><li>$y = &#92;pm R_2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{R_1^2}}$ describe the outer contour line for $x &#92;in [-R_1,R_1]$.</li><li>$y = &#92;pm r_2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{r_1^2}}$ describe the inner contour line for $x &#92;in [-r_1,r_1]$.</li></ul></div><p>Now we need to compute these integrals:</p><p>$$I_1 = {&#92;int&#92;int}_{A_1} y^2 &#92;, &#92;mathrm dA_1 = &#92;int_0^{r_1} &#92;int_{r_2 &#92;, &#92;sqrt{1 -
&#92;frac{x^2}{r_1^2}}}^{R_2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{R_1^2}}} y^2 &#92;, &#92;mathrm dy &#92;,
&#92;mathrm dx,$$</p><p>$$I_2 = {&#92;int&#92;int}_{A_2} y^2 &#92;, &#92;mathrm dA_2 = &#92;int_{r_1}^{R_1}
&#92;int_{0}^{R_2 &#92;, &#92;sqrt{1 - &#92;frac{x^2}{R_1^2}}} y^2&#92;, &#92;mathrm dy&#92;, &#92;mathrm dx.$$</p><p>Although the situation is more complicated now, we can still use the same strategy as above, using symbolic variables instead of numbers. Nevertheless, we need to add one more step: specify relationships between symbolic parameters. This is because the variables $r_1$, $r_2$, $R_1$, and $R_2$ can be any complex number, unless we explicitly restrict their values. For example, the system does not know if these variables are positive or negative, if $r_1 &lt; R_1$ or otherwise. In this example, we want to specify that $r_1&gt;0$, $r_2&gt;0$, $R_1&gt;r_1$, and $R_2&gt;r_2$. In the Symbolic Math Toolbox, such restrictions are called <i>assumptions on variables</i>. They can be set by using the <a rel="nofollow" target="_blank" href="http://www.mathworks.de/de/help/matlab/ref/assume.html"><tt>assume</tt></a> and <a rel="nofollow" target="_blank" href="http://www.mathworks.de/de/help/matlab/ref/assumeAlso.html"><tt>assumeAlso</tt></a> functions:</p><pre class="codeinput">syms <span class="string">x</span> <span class="string">y</span> <span class="string">r1</span> <span class="string">r2</span> <span class="string">R1</span> <span class="string">R2</span>;
assume(r1 &gt; 0);
assume(r2 &gt; 0);
assumeAlso(r1 &lt; R1);
assumeAlso(r2 &lt; R2);
I1 = int(int(y^2, y, r2*sqrt(1-x^2/r1^2), R2*sqrt(1-x^2/R1^2)), x, 0, r1);
I2 = int(int(y^2, y, 0, R2*sqrt(1-x^2/R1^2)), x, r1, R1);
Ixgeneral = 4 * (I1 + I2);
pretty(Ixgeneral)
</pre><pre class="codeoutput"> 
        /          4     / r1 &#92; &#92;         /                     4     / r1 &#92; &#92; 
        |      3 R1  asin| -- | |         |             4   3 R1  asin| -- | | 
      3 |                &#92; R1 / |       3 |      3 pi R1              &#92; R1 / | 
  4 R2  | #1 + ---------------- |   4 R2  | #1 - -------- + ---------------- | 
        &#92;             8         /         &#92;         16             8         / 
  ------------------------------- - ------------------------------------------ 
                   3                                      3 
               3 R1                                   3 R1 
   
                3 
        pi r1 r2 
      - --------- 
            4 
   
  where 
   
           /     2        3 &#92; 
           | 5 R1  r1   r1  |    2     2 1/2 
     #1 == | -------- - --- | (R1  - r1 ) 
           &#92;    8        4  /
</pre><p>Now, let's substitute our symbolic parameters  with the same values that we had in the first example. Do we get the same result? Let's double-check: when substituting $r_1=2,r_2,=1,R_1=3,R_2=2$ in <tt>Ixgeneral</tt>, do we get the same result for <tt>Ix</tt> as obtained for the section initially considered?</p><p>As expected, the general solution <tt>Ixgeneral</tt> reduces to the specific solution <tt>Ix</tt> when we substitute our original dimensions:</p><pre class="codeinput">vpa(subs(Ixgeneral, [r1, R1, r2, R2],[2, 3, 1, 2]), 5)
</pre><pre class="codeoutput">ans =
17.279
</pre><p>Note that it is essential to set the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. By default, the Symbolic Math Toolbox assumes that all variables including symbolic parameters are arbitrary complex numbers. This makes computing integrals much more complicated and time-consuming. For example, try computing <tt>Ixgeneral</tt> without setting the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. In general, it can be impossible to even get the result without any additional assumptions.</p><h4>How to Create MuPAD Graphics Shown in This Article<a rel="nofollow" name="2415b2ac-5410-444a-8c2b-f15693021763"></a></h4><p>To generate the graphics shown in this article, use <a rel="nofollow" target="_blank" href="http://www.mathworks.de/discovery/mupad.html">MuPAD Notebook app</a>. Note that the code in this section does not run in the MATLAB Command Window.</p><p>To open the MuPAD Notebook app:</p><div><ol><li>On the MATLAB Toolstrip, click the Apps tab.</li><li>On the Apps tab, click the down arrow at the end of the Apps section.</li><li>Under Math, Statistics and Optimization, click the MuPAD Notebook button.</li></ol></div><p>Alternatively, type <tt>mupad</tt> in the MATLAB Command Window.</p><p>Paste the following commands to a MuPAD notebook to obtain the four graphics used above:</p><pre>Ellipse:= (x,a,b) -&gt; sqrt(b^2*(1-x^2/a^2)):</pre><pre>f1 := plot::Function2d(Ellipse(x,2,1), x = -3..3):
f2 := plot::Function2d(Ellipse(x,3,2), x = -3..3):
f3 := plot::Function2d(Ellipse(x,3,2), x = -3..-2):
f4 := plot::Function2d(Ellipse(x,3,2), x = 2..3):</pre><pre>f5 := plot::Function2d(-Ellipse(x,2,1), x = -3..3):
f6 := plot::Function2d(-Ellipse(x,3,2), x = -3..3):
f7 := plot::Function2d(-Ellipse(x,3,2), x = -3..-2):
f8 := plot::Function2d(-Ellipse(x,3,2), x = 2..3):</pre><pre>f9 := plot::Function2d(Ellipse(x,2,1), x = 0..2, VerticalAsymptotesVisible = FALSE):
f10 := plot::Function2d(Ellipse(x,3,2), x = 0..3, VerticalAsymptotesVisible = FALSE):
f11 := plot::Function2d(Ellipse(x,3,2), x = 2..3, VerticalAsymptotesVisible = FALSE):</pre><pre>plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
     plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
     Scaling = Constrained,
     GridVisible = TRUE,
     VerticalAsymptotesVisible = FALSE,
     Height = 120, Width = 200,
     Header = "Cross section of elliptical tube (x-y-plane)"):</pre><pre>plot(plot::Hatch(f9,f10),plot::Hatch(f11),f9,f10,
     Scaling = Constrained,
     GridVisible = TRUE,
     Height = 120, Width = 200,
     Header = "Restriction to first quadrant (x-y-plane)"):</pre><pre>plot(plot::Hatch(f9,f10,Color=RGB::Magenta),plot::Hatch(f11,Color = RGB::Green),f9,f10,
     Scaling=Constrained,
     GridVisible = TRUE,
     plot::Text2d("A1",[1.0,1.25]),
     plot::Text2d("A2",[2.5,0.25]),
     Height = 120, Width = 200,
     Header = "Integration areas"):</pre><pre>plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
     plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
     plot::Text2d("r1",[1.8,0.05]),
     plot::Text2d("r2",[0.05,0.85]),
     plot::Text2d("R1",[2.74,0.05]),
     plot::Text2d("R2",[0.05,1.84]),
     Scaling = Constrained,
     GridVisible = TRUE,
     VerticalAsymptotesVisible = FALSE,
     XTicksLabelsVisible = FALSE,
     YTicksLabelsVisible = FALSE,
     ViewingBox = [-3.5..3.5,-2.5..2.5],
     Height = 120, Width = 200,
     Header = "Cross section of elliptical tube (more general situation)"):</pre><h4>Have You Tried Symbolic Math Toolbox?<a rel="nofollow" name="ebec3076-fed9-49e8-967d-2c5a6a31fea0"></a></h4><p>Have you used the Symbolic Math Toolbox in computations related to mechanics? Let me know <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=684#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div> sqrt(b^2*(1-x^2/a^2)):
%  
%  f1 := plot::Function2d(Ellipse(x,2,1), x = -3..3):
%  f2 := plot::Function2d(Ellipse(x,3,2), x = -3..3):
%  f3 := plot::Function2d(Ellipse(x,3,2), x = -3..-2):
%  f4 := plot::Function2d(Ellipse(x,3,2), x = 2..3):
%  
%  f5 := plot::Function2d(-Ellipse(x,2,1), x = -3..3):
%  f6 := plot::Function2d(-Ellipse(x,3,2), x = -3..3):
%  f7 := plot::Function2d(-Ellipse(x,3,2), x = -3..-2):
%  f8 := plot::Function2d(-Ellipse(x,3,2), x = 2..3):
%  
%  f9 := plot::Function2d(Ellipse(x,2,1), x = 0..2, VerticalAsymptotesVisible = FALSE):
%  f10 := plot::Function2d(Ellipse(x,3,2), x = 0..3, VerticalAsymptotesVisible = FALSE):
%  f11 := plot::Function2d(Ellipse(x,3,2), x = 2..3, VerticalAsymptotesVisible = FALSE):
%  
%  plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
%       plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
%       Scaling = Constrained, 
%       GridVisible = TRUE, 
%       VerticalAsymptotesVisible = FALSE,
%       Height = 120, Width = 200,
%       Header = "Cross section of elliptical tube (x-y-plane)"):
%  
%  plot(plot::Hatch(f9,f10),plot::Hatch(f11),f9,f10,
%       Scaling = Constrained,
%       GridVisible = TRUE,
%       Height = 120, Width = 200,
%       Header = "Restriction to first quadrant (x-y-plane)"):
%  
%  plot(plot::Hatch(f9,f10,Color=RGB::Magenta),plot::Hatch(f11,Color = RGB::Green),f9,f10,
%       Scaling=Constrained,
%       GridVisible = TRUE, 
%       plot::Text2d("A1",[1.0,1.25]),
%       plot::Text2d("A2",[2.5,0.25]),
%       Height = 120, Width = 200,
%       Header = "Integration areas"):
%  
%  plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
%       plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
%       plot::Text2d("r1",[1.8,0.05]),
%       plot::Text2d("r2",[0.05,0.85]),
%       plot::Text2d("R1",[2.74,0.05]),
%       plot::Text2d("R2",[0.05,1.84]),
%       Scaling = Constrained, 
%       GridVisible = TRUE, 
%       VerticalAsymptotesVisible = FALSE,
%       XTicksLabelsVisible = FALSE,
%       YTicksLabelsVisible = FALSE,
%       ViewingBox = [-3.5..3.5,-2.5..2.5],
%       Height = 120, Width = 200,
%       Header = "Cross section of elliptical tube (more general situation)"):
%% Have You Tried Symbolic Math Toolbox?
% Have you used the Symbolic Math Toolbox in computations related to 
% mechanics? Let me know .
##### SOURCE END ##### 75b0bee11e3e4c56aafb679a67295a76
--&gt;<img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/GAkkzQGU4nE" height="1" width="1"/>]]></content:encoded>
         <category>Symbolic</category>
      </item>
      <item>
         <title>Implementing a PID Controller on an Arduino Board</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/BK2DfvAWPx0/</link>
         <description>This week my colleague Pravallika is back to continue her motor control story! In my previous post, we saw how to estimate continuous transfer functions with System Identification Toolbox. We estimated the following transfer function for a simple DC Motor using tfest: For this transfer function, we designed the following controller using pidtune: We will [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2141</guid>
         <pubDate>Sun, 21 Apr 2013 21:49:06 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>This week my colleague <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/answers/contributors/2963950-pravallika">Pravallika</a> is back to continue her motor control story!</em></p>

<p><img src="http://blogs.mathworks.com/images/seth/pvinnako_tn_large.jpg" alt="Pravallikota Vinnakota, guest blogger"></p>

<p>In my <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/2012/03/28/estimating-continuous-time-transfer-functions-with-system-identification-toolbox/" title="Estimating Continuous-Time Transfer Functions with System Identification Toolbox">previous post</a>, we saw how to estimate continuous transfer functions with <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/sysid/">System Identification Toolbox</a>. We estimated the following transfer function for a simple DC Motor using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/ident/ref/tfest.html"><tt>tfest</tt></a>:</p>
<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/theIdentifiedSystem.png" alt="Transfer function identified from a DC Motor"/></p>

<p>For this transfer function, we designed the following controller using <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/control/ref/pidtune.html"><tt>pidtune</tt></a>:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/theController.png" alt="Controller generated by pidtune"/></p>

<p>We will now implement the controller on the Arduino Uno and see how the DC motor fares with this controller. To deploy the controller on the hardware, we will use <a rel="nofollow" target="_blank" href="http://www.mathworks.com/discovery/simulink-target-hardware.html">Simulink’s capability to generate an executable and run it on selected hardware</a>.

<p><strong>Deploying controller to the Arduino board</strong></p>

<p>You probably noticed that the controller shown above is in a continuous form. To use it on our target, the first thing to do is to discretize it using the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/control/ref/c2d.html"><tt>c2d</tt></a> function:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/discreteController.png" alt="Discretizing the controller generated by pidtune"/></p>

<p>Then we grab the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/pidcontroller.html">PID block</a> from the Simulink Library and configure it.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/configuringPID.png" alt="PID block configuration"/></p>

<p>To keep the PID controller’s output within the limits of the hardware, we go to the PID Advanced tab and enable output saturation along with anti-windup protection. 

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/pidAdvanced.png" alt="Advanced PID block configuration"/></p>

<p>To test the controller on the hardware, we created a Simulink model using blocks from the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/arduino-software/arduino-simulink.html">Arduino Support Package</a>.</p>

<p>As you can see, we receive the desired motor position from the serial port and compare it to the measured position from the Analog Input. The position error goes through the PID block which generates a voltage to be sent to the motor. We also send the measured position through the serial port.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/controllerModel.png" alt="Controller model to be used on the Arduino board"/></p>

<p><strong>Hardware response</strong></p>

<p>We ran the model on the target, sent it some commands and logged the data transmitted through the serial port. Here is what it looks like:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/hardware_results.png" alt="Data logged from our controller"/></p>

<p>So, it does a pretty good job of tracking the reference signal. When we compare the response from the hardware to that of the simulation, we observe that they are very close! The System Identification Toolbox model is quite good.</p>

<p><strong>Now it is your turn</strong></p>

<p>How are you designing controllers when a system is difficult to model? Have you tried the Run on Target Hardware capability in Simulink to run your models on the supported boards? Let us know by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2141&#comment">comment here</a>.</p><img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/BK2DfvAWPx0" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Manage the (Automatic) Naming of Your Figure Windows</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/ORLSrdqUUnU/</link>
         <description>Brett's Pick this week is &quot;setname&quot;, by Andrew Bliss.Some of you may be familiar with my own togglefig function; it allows one to recall and reuse a figure by specifying its name. I find it extremely practical, and I use it almost on a daily basis. (It's particularly useful when you're iterating on a block [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4507</guid>
         <pubDate>Fri, 19 Apr 2013 13:00:48 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/911">Brett</a>'s Pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/33076">"setname"</a>, by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/20418">Andrew Bliss</a>.</p><p>Some of you may be familiar with my own <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/18220"><tt>togglefig</tt></a> function; it allows one to recall and reuse a figure by specifying its name. I find it extremely practical, and I use it almost on a daily basis. (It's particularly useful when you're iterating on a block of code separated into <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab_prog/run-sections-of-programs.html#brqxeeu-271">"sections."</a> Andrew's <tt>setname</tt> makes a very nice companion to <tt>togglefig</tt>.)</p><p>As of this writing, Andrew has 10 files on the Exchange, which have collectively been downloaded more than 500 times in the past 30 days. (Not too shabby!) Nonetheless, I don't believe any of his submissions have previously been recognized as a Pick of the Week. Until now.</p><p>Ironically, the file of Andrew's that I am most enamored of is his least-downloaded.</p><p>So what does Andrew's function do? If you've previously indicated a title for the axes in your figure, <tt>setname</tt> automatically renames the figure to match axes name. If you haven't titled your graphic, the function extracts a string from the x- and y- labels of the axes to construct a figure name.</p><p>Consider, for example, this snippet of code:</p><pre class="language-matlab">t = 0:pi/64:8*pi;
plot(t,sin(t)+rand(size(t)))
xlabel(<span class="string">'Time'</span>)
ylabel(<span class="string">'Noisy Sine'</span>)
title(<span class="string">'Noisy Sinusoid'</span>)
</pre><p>This creates a figure not-so-usefully named "Untitled" (with a number appended to differentiate it from the other <i>n</i> "Untitled" figures you've previously created.)</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/setname1.png" alt=""> </p><p>Now issue the <tt>setname</tt> command (no arguments needed--it works by default on the current axes, though you may specify a non-default axes.) Now the figure is renamed to "Noisy Sinusoid," and you can readily pick it out from all the other open figures.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/pick/files/setname2.png" alt=""> </p><p>Alternatively, if you didn't explicitly provide a title, <tt>setname</tt> would automatically name the figure "Time vs Noisy Sine." Now not only can I find the figure, I can easily reuse it:</p><pre class="language-matlab"><span class="comment">% Recall the previous figure...</span>
togglefig(<span class="string">'Noisy Sinusoid'</span>)
plot(t,cos(t)+rand(size(t)))
title(<span class="string">'Noisy Cosine'</span>)
<span class="comment">% ...and then rename the figure!</span>
setname
</pre><p>This is brilliant, Andrew...thanks! One suggestion: it would be really nice if I could pass to <tt>setname</tt> an argument ('all'?) that tells the function to rename all open figures. (For those times when I've lazily created 20 different 'Untitled' figures.)</p><p>As always, I welcome your <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4507#respond">thoughts and comments</a>. Or leave feedback for Andrew <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/33076#comments">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/ORLSrdqUUnU" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Generalizing the access to an array of structures in MATLAB</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/dscDCTA-lH0/</link>
         <description>Recently a MATLAB user asked me how to make it possible to work with an array of structures in such a way that she could filter the array of structures and then combine the remaining fields. Once combined she would run arbitrary processing functions on this combined data. This generalized architecture allows her to not [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1086</guid>
         <pubDate>Wed, 17 Apr 2013 15:18:32 +0000</pubDate>
         <content:encoded><![CDATA[Recently a MATLAB user asked me how to make it possible to work with an array of structures in such a way that she could filter the array of structures and then combine the remaining fields.  Once combined she would run arbitrary processing functions on this combined data.
<p>
This generalized architecture allows her to not use switch case and other flow control.  The strings that represent the fields of interest could come from a GUI making her GUI able to process in many arbitrary and customizable ways.
<p>

<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate304" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>

Here is the code from the post:

<code><pre>
clear
clc

s(1).condition = 1;
s(2).condition = 1;
s(3).condition = 2;
s(4).condition = 2;

s(1).velocity = [11:21];
s(2).velocity = [22:32];
s(3).velocity = [33:43];
s(4).velocity = [44:54];

s(1).acceleration = [111:121];
s(2).acceleration = [122:132];
s(3).acceleration = [133:143];
s(4).acceleration = [144:154];

fieldToFilterBy    = 'condition';
valueToFilterBy    = 2;
fieldToProcess     = 'acceleration';
processingFunction = @mean;


listOfFilterValues    = [s.(fieldToFilterBy)];
vi                    = (listOfFilterValues == valueToFilterBy)
filteredStructure     = s(vi)
mergedFieldOfInterest = [filteredStructure(:).(fieldToProcess)]
processedFilteredData = feval(processingFunction, mergedFieldOfInterest)
</pre></code><img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/dscDCTA-lH0" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Wilkinson’s Matrices</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/FPQYLzmuub4/</link>
         <description>One of Jim Wilkinson's outstanding skills was his ability to pick great examples. A previous post featured his signature polynomial. This post features his signature matrices.ContentsTridiagonal MatricesWilkinson's MatricesEigenvaluesPropertiesRemarkable ClosenessEigenvectorsPerturbation TheoryAcknowledgementReferenceTridiagonal MatricesWhen working with eigenvalues, we always have to be concerned about multiplicity and separation. Multiple eigenvalues and clusters of close eigenvalues require careful attention. Symmetric [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=573</guid>
         <pubDate>Mon, 15 Apr 2013 17:00:34 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>One of Jim Wilkinson's outstanding skills was his ability to pick great examples.  A previous post featured his signature polynomial. This post features his signature matrices.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#b02f0d32-cc5b-4caf-84bf-004916d6943f">Tridiagonal Matrices</a></li><li><a rel="nofollow" href="#05fe0fd2-337c-432e-8f89-360e8c60182c">Wilkinson's Matrices</a></li><li><a rel="nofollow" href="#4df1ab29-2238-4cca-9e0e-25c85c1b77f6">Eigenvalues</a></li><li><a rel="nofollow" href="#fc289bd0-3d97-4a48-b025-330addca7510">Properties</a></li><li><a rel="nofollow" href="#7439e6e5-1366-4c86-b6e7-3ad2301c54d6">Remarkable Closeness</a></li><li><a rel="nofollow" href="#9ee7bdf1-0660-46e0-b1e1-3b0f78aedb53">Eigenvectors</a></li><li><a rel="nofollow" href="#eaf005b7-1853-4ac2-952c-ae3c216e2803">Perturbation Theory</a></li><li><a rel="nofollow" href="#09aed841-3408-482a-806e-6ff493b1d1cf">Acknowledgement</a></li><li><a rel="nofollow" href="#df8cc255-c9a2-498e-b1f0-306d00a068e4">Reference</a></li></ul></div><h4>Tridiagonal Matrices<a rel="nofollow" name="b02f0d32-cc5b-4caf-84bf-004916d6943f"></a></h4><p>When working with eigenvalues, we always have to be concerned about multiplicity and separation.  Multiple eigenvalues and clusters of close eigenvalues require careful attention.  Symmetric tridiagonal matrices are easier to handle than the general case.  If none of the off diagonal elements are zero, there are no multiple eigenvalues.  But if none of the off diagonal elements are "small", can we conclude that the eigenvalues are reasonably well separated?  One of Wilkinson's matrices answers this question with a resounding "no".</p><h4>Wilkinson's Matrices<a rel="nofollow" name="05fe0fd2-337c-432e-8f89-360e8c60182c"></a></h4><p>Wilkinson introduces the matrices $W_{2n+1}^-$ and $W_{2n+1}^+$ on page 308 of <i>The Algebraic Eigenvalue Problem</i> and then employs them throughout the rest of the book.  These matrices are the families of symmetric tridiagonal matrices generated by the following MATLAB function. ($W_n^+$ is also generated by the function <tt>wilkinson</tt> in <tt>toolbox&#92;matlab&#92;elmat</tt> that has been part of MATLAB for many years.)</p><pre class="codeinput">type <span class="string">generate_wilkinson_matrices</span>
</pre><pre class="codeoutput">
function [Wm,Wp] = generate_wilkinson_matrices(n)

   D = diag(ones(2*n,1),1);
   Wm = diag(-n:n) + D + D';
   Wp = abs(diag(-n:n)) + D + D';

</pre><p>Here, for example, is $n = 3, 2n+1 = 7$.</p><pre class="codeinput">format <span class="string">compact</span>
[Wm,Wp] = generate_wilkinson_matrices(3)
</pre><pre class="codeoutput">Wm =
    -3     1     0     0     0     0     0
     1    -2     1     0     0     0     0
     0     1    -1     1     0     0     0
     0     0     1     0     1     0     0
     0     0     0     1     1     1     0
     0     0     0     0     1     2     1
     0     0     0     0     0     1     3
Wp =
     3     1     0     0     0     0     0
     1     2     1     0     0     0     0
     0     1     1     1     0     0     0
     0     0     1     0     1     0     0
     0     0     0     1     1     1     0
     0     0     0     0     1     2     1
     0     0     0     0     0     1     3
</pre><h4>Eigenvalues<a rel="nofollow" name="4df1ab29-2238-4cca-9e0e-25c85c1b77f6"></a></h4><p>Wilkinson usually has $2n+1 = 21$. Here are the eigenvalues of $W_{21}^-$ and $W_{21}^+$.</p><pre class="codeinput">format <span class="string">long</span>
[Wm,Wp] = generate_wilkinson_matrices(10);
disp(<span class="string">'       eig(Wm(21))         eig(Wp(21))'</span>)
disp(flipud([eig(Wm) eig(Wp)]))
</pre><pre class="codeoutput">       eig(Wm(21))         eig(Wp(21))
  10.746194182903357  10.746194182903393
   9.210678647333035  10.746194182903322
   8.038941119306445   9.210678647361332
   7.003952002665359   9.210678647304919
   6.000225680185169   8.038941122829023
   5.000008158672943   8.038941115814275
   4.000000205070442   7.003952209528674
   3.000000003808129   7.003951798616375
   2.000000000054486   6.000234031584166
   1.000000000000619   6.000217522257097
   0.000000000000003   5.000244425001915
  -1.000000000000618   4.999782477742903
  -2.000000000054490   4.004354023440857
  -3.000000003808127   3.996048201383625
  -4.000000205070437   3.043099292578824
  -5.000008158672947   2.961058884185726
  -6.000225680185168   2.130209219362506
  -7.003952002665363   1.789321352695084
  -8.038941119306442   0.947534367529292
  -9.210678647333047   0.253805817096678
 -10.746194182903357  -1.125441522119985
</pre><h4>Properties<a rel="nofollow" name="fc289bd0-3d97-4a48-b025-330addca7510"></a></h4><p>Here are some important properties of these eigenvalues.</p><div><ul><li>All the eigenvalues of $W_{2n+1}^-$, except the middle one,   occur in $&#92;pm$ pairs.</li></ul></div><div><ul><li>$W_{2n+1}^-$ is singular.  The middle eigenvalue is zero.</li></ul></div><div><ul><li>All the eigenvalues of $W_{2n+1}^+$, but one, are positive.</li></ul></div><div><ul><li>The positive eigenvalues of $W_{2n+1}^+$ occur roughly in pairs, with a   positive eigenvalue of $W_{2n+1}^-$ approximately in the center of   each pair.</li></ul></div><div><ul><li>The larger pairs of eigenvalues of $W_{2n+1}^+$ are incredibly close   together.</li></ul></div><h4>Remarkable Closeness<a rel="nofollow" name="7439e6e5-1366-4c86-b6e7-3ad2301c54d6"></a></h4><p>All of the off diagonal elements in $W_{21}^+$ equal one, so none are "small", and yet the first two eigenvalues of $W_{21}^+$ agree to fourteen significant figures.  Wilkinson calls this "remarkable" and "pathological". The relative distance is</p><pre class="codeinput">format <span class="string">short</span> <span class="string">e</span>
e = flipud(eig(Wp));
delta = (e(1)-e(2))/e(1)
</pre><pre class="codeoutput">delta =
   6.6120e-15
</pre><h4>Eigenvectors<a rel="nofollow" name="9ee7bdf1-0660-46e0-b1e1-3b0f78aedb53"></a></h4><p>The behavior of the eigenvalues can be understood by looking at the eigenvectors.  Here is the vector $u_1$ associated with the first eigenvalue of $W_{21}^-$ and the vectors $v_1$ and $v_2$ associated with the leading pair of eigenvalues of $W_{21}^+$, Each vector has been normalized so that its first component is one.</p><pre class="codeinput">[U,~] = eig(Wm);
[V,~] = eig(Wp);
u1 = flipud(U(:,end)/U(end,end));
v1 = flipud(V(:,end)/V(end,end));
v2 = flipud(V(:,end-1)/V(end,end-1));

format <span class="string">long</span>
[u1 v1 v2]
</pre><pre class="codeoutput">ans =
   1.000000000000000   1.000000000000000   1.000000000000000
   0.746194182903358   0.746194182903392   0.746194182903321
   0.302999941502167   0.302999941502254   0.302999941502075
   0.085902493869951   0.085902493870164   0.085902493869724
   0.018807481330335   0.018807481331049   0.018807481329571
   0.003361464615150   0.003361464618322   0.003361464611748
   0.000508147087273   0.000508147104788   0.000508147068490
   0.000066594309069   0.000066594424058   0.000066594185758
   0.000007705362252   0.000007706235465   0.000007704425844
   0.000000798285440   0.000000805807738   0.000000790218740
   0.000000074882661   0.000000147323229  -0.000000002800555
   0.000000006418173   0.000000777356287  -0.000000820314052
   0.000000000506441   0.000007428942095  -0.000007992139484
   0.000000000037026   0.000064197613845  -0.000069080489810
   0.000000000002522   0.000489858240829  -0.000527118748833
   0.000000000000161   0.003240481200881  -0.003486964947267
   0.000000000000010   0.018130575985481  -0.019509658947141
   0.000000000000001   0.082810753074099  -0.089109664858083
   0.000000000000000   0.292094585462557  -0.314312449184672
   0.000000000000000   0.719337698380754  -0.774053354706959
   0.000000000000000   0.964008718993031  -1.037335016061421
</pre><p>And here is a plot of these three eigenvectors. The components of the first half of each of the three vectors decay rapidly and all three agree with each other to many decimal places.</p><pre class="codeinput">n = 10;
plot_wilkinson_eigenvectors
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/jhw_3_01.png" alt=""> <p>For a tridiagonal matrix $A$, the eigenvalue/vector equation</p><p>$$ Ax = &#92;lambda x $$</p><p>is a three-term recurrence relation for the components of $x$. For the first half of each of the three vectors, we have the same positive elements on the diagonal of $A$, ones on the off diagonal, and nearly the same positive value of $&#92;lambda$, so the recurrence relation is nearly the same and leads to nearly the same rapidly decreasing components.</p><p>Once the recurrence relation gets half way through the vector and the components get small, this argument breaks down.  For $u_1$ the diagonal elements are negative and so the components of the vector remain small.  Perron-Frobenius implies that $v_1$ goes positive. Symmetry implies that $v_2$ goes negative to stay orthogonal to $v_1$.</p><h4>Perturbation Theory<a rel="nofollow" name="eaf005b7-1853-4ac2-952c-ae3c216e2803"></a></h4><p>A closer examination of the elements of $v_1$ reveals that they decay exponentially until they reach a minimum half way through the vector at index $n+1$. It is possible to estimate <i>a priori</i> that this minimum value is of order $O(1/n!)$</p><pre class="codeinput">format <span class="string">short</span> <span class="string">e</span>
minimum = v1(n+1)
estimate = 1/factorial(n)
</pre><pre class="codeoutput">minimum =
   1.4732e-07
estimate =
   2.7557e-07
</pre><p>This information about the shape of the dominant eigenvector makes it possible to prove that the corresponding eigenvalue, $&#92;lambda_1$, is a double eigenvalue with separation of order the square of the minimum in the eigenvector, which is $O(1/(n!)^2)$.</p><pre class="codeinput">separation = e(1)-e(2)
estimate = 1/factorial(n)^2
</pre><pre class="codeoutput">separation =
   7.1054e-14
estimate =
   7.5941e-14
</pre><h4>Acknowledgement<a rel="nofollow" name="09aed841-3408-482a-806e-6ff493b1d1cf"></a></h4><p>Thanks to Pete Stewart, University of Maryland, for some helpful email while I was working on this post.</p><h4>Reference<a rel="nofollow" name="df8cc255-c9a2-498e-b1f0-306d00a068e4"></a></h4><p>J. H. Wilkinson, <i>The Algebraic Eigenvalue Problem</i>, Claredon Press, Oxford, 1965, 662 pp.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/FPQYLzmuub4" height="1" width="1"/>]]></content:encoded>
         <category>Matrices</category>
      </item>
      <item>
         <title>Revisiting dctdemo – part 4</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/9Loy5jz1MAs/</link>
         <description>This is the fourth and last part of my plan (my evil plan?) to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features. I got the idea from Dave Garrison's recent article on writing MATLAB apps.Here's the old app I'm trying to reinvent: And here's what I had [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=825</guid>
         <pubDate>Fri, 12 Apr 2013 13:41:36 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>This is the fourth and last part of my plan (my evil plan?) to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features. I got the idea from Dave Garrison's <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/newsletters/articles/writing-apps-in-matlab.html">recent article</a> on writing MATLAB apps.</p><p>Here's the old app I'm trying to reinvent:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo-screen-shot.png" alt=""> </p><p>And here's what I had working <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/21/revisiting-dctdemo-part-3/">last time</a>:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dct-compression-example-v3.png" alt=""> </p><p>There are two things I want to wrap up before calling it good enough:</p><div><ul><li>Implement the display of the DCT coefficient mask (lower left of app)</li><li>Allow user to control the number of DCT coefficients by setting the <tt>NumDCTCoefficients</tt> property of the app.</li></ul></div><p>First let's get the DCT coefficient mask display working. Recall that last time I added a function to compute the reconstructed image, given the desired number of DCT coefficients. I'll add a second output argument to that function in order to return the DCT coefficient mask. Here's the code. The only changes are on the first line (to define the additional output argument) and the last three lines (to compute the mask).</p><pre>function [I2,mask] = reconstructImage(I,n)
% Reconstruct the image from n of the DCT coefficients in each 8-by-8
% block. Select the n coefficients with the largest variance across the
% image. Second output argument is the 8-by-8 DCT coefficient mask.</pre><pre>% Compute 8-by-8 block DCTs.
f = @(block) dct2(block.data);
A = blockproc(I,[8 8],f);</pre><pre>% Compute DCT coefficient variances and decide
% which to keep.
B = im2col(A,[8 8],'distinct')';
vars = var(B);
[~,idx] = sort(vars,'descend');
keep = idx(1:n);</pre><pre>% Zero out the DCT coefficients we are not keeping.
B2 = zeros(size(B));
B2(:,keep) = B(:,keep);</pre><pre>% Reconstruct image using 8-by-8 block inverse
% DCTs.
C = col2im(B2',[8 8],size(I),'distinct');
finv = @(block) idct2(block.data);
I2 = blockproc(C,[8 8],finv);</pre><pre>mask = false(8,8);
mask(keep) = true;
end</pre><p>Next I need some code to visualize the coefficient mask. I want to display it as image with gray lines drawn between the mask pixels. So I added a local function called <tt>displayCoefficientMask</tt>:</p><pre>function displayCoefficientMask(mask,ax)
imshow(mask,'Parent',ax)
for k = 0.5:1.0:8.5
    line('XData',[0.5 8.5], ...
        'YData',[k k], ...
        'Color',[0.6 0.6 0.6], ...
        'LineWidth',2, ...
        'Clipping','off', ...
        'Parent',ax);
    line('XData',[k k],...
        'YData',[0.5 8.5],...
        'Color',[0.6 0.6 0.6], ...
        'LineWidth',2,...
        'Clipping','off', ...
        'Parent',ax);
end
title(ax,'DCT Coefficient Mask')
end</pre><p>The last step is to call <tt>displayCoefficientMask</tt> from the <tt>update</tt> method (which gets called whenever the slider is moved). In the code below, I have modified the call to <tt>reconstructImage</tt> to use two output arguments in order to get the mask; I have assigned the various app properties; and I have added the call to <tt>displayCoefficientMask</tt> at the end.</p><pre>function update(app)
% Update the computation
[recon_image,mask] = reconstructImage(app.OriginalImage, ...
    app.NumDCTCoefficients);</pre><pre>diff_image = imabsdiff(app.OriginalImage, recon_image);</pre><pre>% Update the app properties
app.ReconstructedImage = recon_image;
app.ErrorImage = diff_image;
app.DCTCoefficientMask = mask;</pre><pre>% Update the display
imshow(app.OriginalImage,'Parent',app.OriginalImageAxes);
title(app.OriginalImageAxes,'Original Image');</pre><pre>imshow(recon_image,'Parent',app.ReconstructedImageAxes);
title(app.ReconstructedImageAxes,'Reconstructed Image');</pre><pre>imshow(diff_image,[],'Parent',app.ErrorImageAxes);
title(app.ErrorImageAxes,'Error Image');</pre><pre>displayCoefficientMask(mask,app.MaskAxes);</pre><pre>drawnow;
end</pre><p>Here's the result with the DCT coefficient mask visualization included:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dct-compression-example-v4.png" alt=""> </p><p>The last thing I want to do with this little app is to allow users to set the app's <tt>NumDCTCoefficients</tt> property from the command line and to have the app automatically update. To do this, I'll make a couple of changes to the <tt>NumDCTCoefficients</tt> property. First, I'll make it a <i>dependent</i> property. Instead of being stored independently, this property will be computed on-the-fly from slider setting whenever it is queried. That requires that I define a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab_oop/property-access-methods.html"><i>property get method</i></a> that computes the property's value on demand. And last I'll need a <i>property set method</i> that defines what actions should be taken whenever the user sets the property.</p><p>Here's the modified <tt>property</tt> block that indicates that <tt>NumDCTCoefficients</tt> is a dependent property.</p><pre>properties (Dependent)
    NumDCTCoefficients
end</pre><p>And here are the get and set functions for <tt>NumDCTCoefficients</tt>. The get function computes the number on-the-fly based on the current slider position. The set function modifies the slider position and then calls the <tt>update</tt> method to recompute and redisplay everything.</p><pre>function value = get.NumDCTCoefficients(app)
    value = round(get(app.Slider,'Value') * 64);
end</pre><pre>function set.NumDCTCoefficients(app,num_coefficients)
    set(app.Slider,'Value',num_coefficients/64)
    update(app);
end</pre><p>Here's an example of this interaction.</p><pre class="codeinput">app = dctCompressionExample_v5
</pre><pre class="codeoutput">
app = 

  dctCompressionExample_v5 with properties:

         OriginalImage: [240x240 double]
    ReconstructedImage: [240x240 double]
            ErrorImage: [240x240 double]
    DCTCoefficientMask: [8x8 logical]
    NumDCTCoefficients: 3

</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part4_01.png" alt=""> <p>I can see the DCT coefficient mask on the app, but I can also look at the <tt>DCTCoefficientMask</tt> property.</p><pre class="codeinput">app.DCTCoefficientMask
</pre><pre class="codeoutput">
ans =

     1     1     0     0     0     0     0     0
     1     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0

</pre><p>And I can set the <tt>NumDCTCoefficients</tt> property, which causes the app to update.</p><pre class="codeinput">app.NumDCTCoefficients = 1;
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part4_02.png" alt=""> <p>OK, I think that's enough to get all the basic ideas. If you want to play around with the final version of the code for this blog post, you can download it from <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/steve/2013/dctCompressionExample_v5.m">here</a>.</p><div><ul><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/08/revisiting-dctdemo-part-1/">Revisiting dctdemo - part 1</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/21/revisiting-dctdemo-part-2/">Revisiting dctdemo - part 2</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/21/revisiting-dctdemo-part-3/">Revisiting dctdemo - part 3</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/04/12/revisiting-dctdemo-part-4/">Revisiting dctdemo - part 4</a></li></ul></div><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/9Loy5jz1MAs" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Simulate Robots with Sim.I.am</title>
         <link>http://feedproxy.google.com/~r/mathworks/pick/~3/i7W7PGW-Z5g/</link>
         <description>Jiro's pick this week is Sim.I.am by Jean-Pierre de la Croix.This week, I had a trip to University of Cincinnati with my colleague (and fellow blogger) Sean de Wolski. There, I did a session titled &quot;Enabling Project-Based Learning with MATLAB, Simulink, and Hardware&quot;. Project-based learning is a &quot;collaborative education style facilitated by teachers, aimed at [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/pick/?p=4498</guid>
         <pubDate>Fri, 12 Apr 2013 13:00:41 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/15007">Jiro</a>'s pick this week is <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/40860">Sim.I.am</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/331930">Jean-Pierre de la Croix</a>.</p><p>This week, I had a trip to University of Cincinnati with my colleague (and fellow blogger) Sean de Wolski. There, I did a session titled "Enabling Project-Based Learning with MATLAB, Simulink, and Hardware". <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Project-based_learning">Project-based learning</a> is a "collaborative education style facilitated by teachers, aimed at increasing students' retention of content in a way that is directly engaging, through projects applicable to life outside of the classroom." There are various tools that would serve the purpose of engaging students, and MATLAB and Simulink are certainly among them.</p><p>With MATLAB and Simulink, you can have software-based projects (simulations) and hardware-based projects. I wrote about some of the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/2013/03/15/additional-hardware-support-in-r2013a/">hardware support</a> that is included with Simulink, and this allows you to easily take what you have in simulation onto low cost hardware. However, when you are trying to implement a project-based learning approach for a class of hundreds of students, purchasing hardware devices for every student becomes impractical. In that case, simulation becomes even more important.</p><p>Jean-Pierre is a Ph.D. student in <a rel="nofollow" target="_blank" href="http://gritslab.gatech.edu/home/">GRITSLab</a> at <a rel="nofollow" target="_blank" href="http://www.gatech.edu/">Georgia Tech</a> (my alma mater!). Sim.I.am is a simulator that can be used to learn and apply control theory for mobile robots. The robot used in the simulator is based on the <a rel="nofollow" target="_blank" href="http://www.k-team.com/mobile-robotics-products/khepera-iii">Khepera III (K3)</a> mobile robot. This File Exchange submission comes with a detailed manual for the simulator, although the App is user-friendly and self-explanatory. What I like even more is the collection of programming exercises included with the package. It's ready to be used in a robotics course right away!</p><p>In this animation, you can see a target-seeking algorithm in action. The green dot indicates the target that the robot seeks.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/pick/jiro/potw_simiam/simiam_simulator_animation.gif" alt=""> </p><p>At my session at University of Cincinnati, I also talked about a similar <a rel="nofollow" target="_blank" href="http://verifiablerobotics.com/CreateMATLABsimulator/createsimulator.html">MATLAB-based Simulator</a> for the <a rel="nofollow" target="_blank" href="http://store.irobot.com/shop/index.jsp?categoryId=3311368">iRobot&reg; Create&reg;</a>. This simulator works alongside the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/32698">MATLAB-iRobot Create interface</a>, and this allows students to test their control algorithms they developed in simulation on the actual robot.</p><p>You can find other project-based learning materials created by people from around the world in the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/classroom-resources/">Classroom Resources</a> page. Check out the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/hardware-resources/">Hardware for Project-Based Learning</a> page to see what kind of hardware platforms interface with MATLAB and Simulink.</p><p><b>Comments</b></p><p>Are you involved with project-based learning? Let us know about it <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/pick/?p=4498#respond">here</a> and leave a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/40860#comments">comment</a> for Jean-Pierre.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/pick/~4/i7W7PGW-Z5g" height="1" width="1"/>]]></content:encoded>
         <category>Picks</category>
      </item>
      <item>
         <title>Creating Driver Blocks for Arduino, Lego, and other targets</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/YOeyBd4JC6E/</link>
         <description>As you may know, it is easy to run Simulink models on a set of supported target hardware. This has been possible since R2012a. Even if we add more targets and support more features for each target with every new release, it is still possible that you will need a driver that is not included [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=2078</guid>
         <pubDate>Fri, 12 Apr 2013 08:00:15 +0000</pubDate>
         <content:encoded><![CDATA[<p>As you may know, it is easy to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/discovery/simulink-target-hardware.html">run Simulink models on a set of supported target hardware</a>. This has been possible since R2012a.</p>

<p>Even if we add more targets and support more features for each target with every new release, it is still possible that you will need a driver that is not included in the Simulink support package. If you desperately need a driver for your hardware, you can always build it yourself.</p>

<p>Let's see how this works using an example from a LEGO NXT project I worked on.</p>

<p><strong>The LEGO Light Sensor</strong></p>

<p>The LEGO NXT kit ships with a <a rel="nofollow" target="_blank" href="http://shop.lego.com/en-US/Light-Sensor-9844">Light Sensor</a> including a red LED that can be turned on or off. In the Simulink support package, you can control the light from a checkbox parameter in the block dialog.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/LEGO_light_sensor.png" alt="Dialog of the LEGO Light Sensor driver block"/></p>

<p>For our project, we used this sensor to make a line following robot. To make our algorithm more robust, we thought it would be interesting to turn the light on and off while tracking the line, to actively filter out the ambient light.</p> 

<p><strong>Step 1: Determine the code to be generated for your driver block</strong></p>

<p>In the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/lego-mindstorms-nxt-software/legomindstorms-simulink.html">LEGO MINDSTORMS NXT Support from Simulink</a>, you can find many small examples showing how the robot can be programmed in C. By default, they are located in <tt>C:&#92;MATLAB&#92;SupportPackages&#92;R2013a&#92;nxtOSEK&#92;samples_c</tt>. In one of those example, I found a function  initializing the robot that looked like:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/LEGO_example_code.png" alt="Example code used to program the NXT brick in C"/></p>

<p>The function <tt>ecrobot_set_light_sensor_active</tt> is exactly what I need to generate from my driver block. I also figured that a corresponding function <tt>ecrobot_set_light_sensor_inactive</tt> exists to turn the light off, and I found that those functions are declared in a file named <tt>ecrobot_interface.h</tt>.</p>

<p><strong>Step 2 - Create an S-Function</strong></p>

<p>Here you have 2 options to create the S-Function</p>

<p><em>Step 2 - Option 1: S-Function Builder Block</em></p>

  <p>My colleague <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/76178">Giampiero Campa</a> published a very good submission on <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/">MATLAB Central</a> titled <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/39354-device-drivers">Device Drivers</a> showing how to use the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/sfunctionbuilder.html">S-Function Builder</a> block to include the code you found during step 1 in your model.</p>

<p>His submission contains detailed procedures and screen captures to guide you through the process step-by-step. If you are intimidated by writing an S-function, I recommend using his S-Function Builder technique.</p>

<p><em>Step 2 - Option 2: Writing an S-Function and a TLC file</em></p>

<p>If you are like me and want to understand the magic that is happening when you click <strong>build</strong> in the S-Function Builder block, this second option is for you.</p>

<p>First, we need to realize that unless you model the interaction of the sensor/actuator with the environment, in simulation, driver blocks typically do nothing.  All blocks must specify the number of ports and parameters, and their dimensions, even if they do nothing. In my case, I created an s-function with 1 input port of dimension 1 to specify if the light should be on or off. Here is the entire code for my s-function.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/lego_light_sfunction.png" alt="S-Function to control the light of the LEGO light sensor"/></p>

<p>To specify the code generated for your block, you need to use the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/ecoder/block-authoring-with-tlc.html">Target Language Compiler</a>.</p>

<p>Concretely, this means that you need to write a TLC file for your block. For that, I recommend starting with examples from <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/sfg/s-function-examples.html">sfundemos</a></tt>.</p>

<p>For this example we need our TLC to do two things: Tell the compiler to include <tt>ecrobot_interface.h</tt>, and call <tt>ecrobot_set_light_sensor_active</tt> and <tt>ecrobot_set_light_sensor_inactive</tt>. Here is what it looks like.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q2/lego_light_tlc.png" alt="TLC file to control the light of the LEGO light sensor"/></p>

<p>Note that I used <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/rtw/tlc/block-target-file-methods.html#f37023">BlockTypeSetup</a></tt> to include the header file, and <tt><a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/rtw/tlc/block-target-file-methods.html#f37160">Outputs</a></tt> to define what the block output method should be.</p>

<p><strong>Now it's your turn</strong></p>

<p>Download this <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q2/LEGO_light_sensor.zip">LEGO example</a> or a similar <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q2/adruino_example.zip">example for the Arduino target</a> and begin creating your own driver blocks!</p>

<p>If you develop custom drivers for the Simulink Target Hardware, share them on <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/">MATLAB Central</a> and let us know by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=2078&#comment">comment here</a>.</p><img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/YOeyBd4JC6E" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>MATLAB to FPGA using HDL Coder(TM)</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/kOoWp0H4zmg/</link>
         <description>It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the product development lead for HDL Coder at MathWorks. In this post, Kiran introduces a new capability in HDL Coder&amp;#8482; that generates synthesizable VHDL/Verilog code directly from MATLAB and highlights some of the key features of this new MATLAB based workflow.ContentsIntroduction to HDL Code [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=673</guid>
         <pubDate>Thu, 11 Apr 2013 12:22:41 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the product development lead for <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/hdl-coder">HDL Coder</a> at MathWorks. In this post, Kiran introduces a new capability in HDL Coder&#8482; that generates synthesizable VHDL/Verilog code directly from MATLAB and highlights some of the key features of this new MATLAB based workflow.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#70424a2f-088b-4758-8de0-5fac5103cdcd">Introduction to HDL Code Generation from MATLAB</a></li><li><a rel="nofollow" href="#91a6f507-30f4-41eb-9876-b2d47f392316">MATLAB to Hardware Workflow</a></li><li><a rel="nofollow" href="#ae2259c5-71e6-4582-ae3c-dd8824b7a4f5">Example MATLAB Algorithm</a></li><li><a rel="nofollow" href="#e5de1a1f-d9cb-4b08-9982-2f47f2c5d4e2">Example MATLAB Test Bench</a></li><li><a rel="nofollow" href="#eb8b6ef6-825c-43f1-8ea0-8d9f9ed13006">HDL Workflow Advisor</a></li><li><a rel="nofollow" href="#d1cf933b-d17d-4d81-8d56-2a0f984df493">Design Space Exploration and Optimization Options</a></li><li><a rel="nofollow" href="#08ade249-3944-44d2-95db-db0d7060c5de">Best Practices</a></li><li><a rel="nofollow" href="#cdf41669-3ba0-44ac-8908-22d323960590">Conclusion</a></li></ul></div><h4>Introduction to HDL Code Generation from MATLAB<a rel="nofollow" name="70424a2f-088b-4758-8de0-5fac5103cdcd"></a></h4><p>If you are using MATLAB to model digital signal processing (DSP) or video and image processing algorithms that eventually end up in FPGAs or ASICs, read on...</p><p>FPGAs provide a good compromise between general purpose processors (GPPs) and application specific integrated circuits (ASICs). GPPs are fully programmable but are less efficient in terms of power and performance; ASICs implement dedicated functionality and show the best power and performance characteristics, but require extremely expensive design validation and implementation cycles. FPGAs are also used for prototyping in ASIC workflows for hardware verification and early software development.</p><p>Due to the order of magnitude performance improvement when running high-throughput, high-performance applications, algorithm designers are increasingly using FPGAs to prototype and validate their innovations instead of using traditional processors. However, many of the algorithms are implemented in MATLAB due to the simple-to-use programming model and rich analysis and visualization capabilities. When targeting FPGAs or ASICs these MATLAB algorithms have to be manually translated to HDL.</p><p>For many algorithm developers who are well-versed with software programming paradigms, mastering the FPGA design workflow is a challenge. Unlike software algorithm development, hardware development requires them to <b><i>think parallel</i></b>. Other obstacles include: learning the VHDL or Verilog language, mastering IDEs from FPGA vendors, and understanding esoteric terms like "multi-cycle path" and "delay balancing".</p><p>In this post, I describe an easier path from MATLAB to FPGAs. I will show how you can automatically generate HDL code from your MATLAB algorithm, implement the HDL code on an FPGA, and use MATLAB to verify your HDL code.</p><h4>MATLAB to Hardware Workflow<a rel="nofollow" name="91a6f507-30f4-41eb-9876-b2d47f392316"></a></h4><p>The process of translating MATLAB designs to hardware consists of the following steps:</p><div><ol><li>Model your algorithm in MATLAB - use MATLAB to simulate, debug, and iteratively test and optimize the design.</li><li>Generate HDL code - automatically create HDL code for FPGA prototyping.</li><li>Verify HDL code - reuse your MATLAB test bench to verify the generated HDL code.</li><li>Create and verify FPGA prototype - implement and verify your design on FPGAs.</li></ol></div><p>There are some unique challenges in translating MATLAB to hardware. MATLAB code is procedural and can be highly abstract; it can use floating-point data and has no notion of time. Complex loops can be inferred from matrix operations and toolbox functions.</p><p>Implementing MATLAB code in hardware involves:</p><div><ul><li>Converting floating-point MATLAB code to fixed-point MATLAB code with optimized bit widths suitable for efficient hardware generation.</li><li>Identifying and mapping procedural constructs to concurrent area- and speed-optimized hardware operations.</li><li>Introducing the concept of time by adding clocks and clock rates to schedule the operations in hardware.</li><li>Creating resource-shared architectures to implement expensive operators like multipliers and for-loop bodies.</li><li>Mapping large persistent arrays to block RAM in hardware</li></ul></div><p>HDL Coder&#8482; simplifies the above tasks though workflow automation.</p><h4>Example MATLAB Algorithm<a rel="nofollow" name="ae2259c5-71e6-4582-ae3c-dd8824b7a4f5"></a></h4><p>Let&#8217;s take a MATLAB function implementing histogram equalization and go through this workflow. This algorithm, implemented in MATLAB, enhances image contrast by transforming the values in an intensity image so that the histogram of the output image is approximately flat.</p><p><i>type mlhdlc_heq.m</i></p><pre class="language-matlab"><span class="comment">% Histogram Equalization Algorithm</span>
<span class="keyword">function</span> [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height)
</pre><pre class="language-matlab"><span class="keyword">persistent</span> histogram
<span class="keyword">persistent</span> transferFunc
<span class="keyword">persistent</span> histInd
<span class="keyword">persistent</span> cumSum
</pre><pre class="language-matlab"><span class="keyword">if</span> isempty(histogram)
    histogram = zeros(1, 2^8);
    transferFunc = zeros(1, 2^8);
    histInd = 0;
    cumSum = 0;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">% Figure out indices based on where we are in the frame</span>
<span class="keyword">if</span> y_in &lt; height &amp;&amp; x_in &lt; width <span class="comment">% valid pixel data</span>
    histInd = pixel_in + 1;
<span class="keyword">elseif</span> y_in == height &amp;&amp; x_in == 0 <span class="comment">% first column of height+1</span>
    histInd = 1;
<span class="keyword">elseif</span> y_in &gt;= height <span class="comment">% vertical blanking period</span>
    histInd = min(histInd + 1, 2^8);
<span class="keyword">elseif</span> y_in &lt; height <span class="comment">% horizontal blanking - do nothing</span>
    histInd = 1;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">%Read histogram</span>
histValRead = histogram(histInd);
</pre><pre class="language-matlab"><span class="comment">%Read transfer function</span>
transValRead = transferFunc(histInd);
</pre><pre class="language-matlab"><span class="comment">%If valid part of frame add one to pixel bin and keep transfer func val</span>
<span class="keyword">if</span> y_in &lt; height &amp;&amp; x_in &lt; width
    histValWrite = histValRead + 1; <span class="comment">%Add pixel to bin</span>
    transValWrite = transValRead; <span class="comment">%Write back same value</span>
    cumSum = 0;
<span class="keyword">elseif</span> y_in &gt;= height <span class="comment">%In blanking time index through all bins and reset to zero</span>
    histValWrite = 0;
    transValWrite = cumSum + histValRead;
    cumSum = transValWrite;
<span class="keyword">else</span>
    histValWrite = histValRead;
    transValWrite = transValRead;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">%Write histogram</span>
histogram(histInd) = histValWrite;
</pre><pre class="language-matlab"><span class="comment">%Write transfer function</span>
transferFunc(histInd) = transValWrite;
</pre><pre class="language-matlab">pixel_out = transValRead;
</pre><h4>Example MATLAB Test Bench<a rel="nofollow" name="e5de1a1f-d9cb-4b08-9982-2f47f2c5d4e2"></a></h4><p>Here is the test bench that verifies that the algorithm works with an example image. (Note that this testbench uses Image Processing Toolbox functions for reading the original image and plotting the transformed image after equalization.)</p><p><i>type mlhdlc_heq_tb.m</i></p><pre class="language-matlab"><span class="comment">%% Test bench for Histogram Equalization Algorithm</span>
clear <span class="string">mlhdlc_heq</span>;
testFile = <span class="string">'office.png'</span>;
RGB = imread(testFile);
</pre><pre class="language-matlab"><span class="comment">% Get intensity part of color image</span>
YCBCR = rgb2ycbcr(RGB);
imgOrig = YCBCR(:,:,1);
</pre><pre class="language-matlab">[height, width] = size(imgOrig);
imgOut = zeros(height,width);
hBlank = 20;
<span class="comment">% make sure we have enough vertical blanking to filter the histogram</span>
vBlank = ceil(2^14/(width+hBlank));
</pre><pre class="language-matlab"><span class="keyword">for</span> frame = 1:2
    disp([<span class="string">'working on frame: '</span>, num2str(frame)]);
    <span class="keyword">for</span> y_in = 0:height+vBlank-1
        <span class="comment">%disp(['frame: ', num2str(frame), ' of 2, row: ', num2str(y_in)]);</span>
        <span class="keyword">for</span> x_in = 0:width+hBlank-1
            <span class="keyword">if</span> x_in &lt; width &amp;&amp; y_in &lt; height
                pixel_in = double(imgOrig(y_in+1, x_in+1));
            <span class="keyword">else</span>
                pixel_in = 0;
            <span class="keyword">end</span>
</pre><pre>             [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height);</pre><pre>             if x_in &lt; width &amp;&amp; y_in &lt; height
                 imgOut(y_in+1,x_in+1) = pixel_out;
             end
         end
     end
 end</pre><pre class="language-matlab"><span class="comment">% Make color image from equalized intensity image</span>
<span class="comment">% Rescale image</span>
imgOut = double(imgOut);
imgOut(:) = imgOut/max(imgOut(:));
imgOut = uint8(imgOut*255);
</pre><pre class="language-matlab">YCBCR(:,:,1) = imgOut;
RGBOut = ycbcr2rgb(YCBCR);
</pre><pre class="language-matlab">figure(1)
subplot(2,2,1); imshow(RGB, []);
title(<span class="string">'Original Image'</span>);
subplot(2,2,2); imshow(RGBOut, []);
title(<span class="string">'Equalized Image'</span>);
subplot(2,2,3); hist(double(imgOrig(:)),2^14-1);
title(<span class="string">'Histogram of original Image'</span>);
subplot(2,2,4); hist(double(imgOut(:)),2^14-1);
title(<span class="string">'Histogram of equalized Image'</span>);
</pre><p>Let's simulate this algorithm to see the results.</p><pre class="codeinput">mlhdlc_heq_tb
</pre><pre class="codeoutput">working on frame: 1
working on frame: 2
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/ml2hdlBlog_01.png" alt=""> <h4>HDL Workflow Advisor<a rel="nofollow" name="eb8b6ef6-825c-43f1-8ea0-8d9f9ed13006"></a></h4><p>The HDL Workflow Advisor (see the snapshot below) helps automate the steps and provides a guided path from MATLAB to hardware. You can see the following key steps of the workflow in the left pane of the workflow advisor:</p><div><ol><li>Fixed-Point Conversion</li><li>HDL Code Generation</li><li>HDL Verification</li><li>HDL Synthesis and Analysis</li></ol></div><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/hdlwfa.png" alt=""> </p><p>Let's look at each workflow step in detail.</p><p><b>Fixed-Point Conversion</b></p><p>Signal processing applications are typically implemented using floating-point operations in MATLAB. However, for power, cost, and performance reasons, these algorithms need to be converted to use fixed-point operations when targeting hardware. Fixed-point conversion can be very challenging and time-consuming, typically demanding 25 to 50 percent of the total design and implementation time.  The automatic floating-point to fixed-point conversion workflow in HDL Coder&#8482; can greatly simplify and accelerate this conversion process.</p><p>The floating-point to fixed-point conversion workflow consists of the following steps:</p><div><ol><li>Verify that the floating-point design is compatible with code generation.</li><li>Propose fixed-point types based on computed ranges, either through the simulation of the testbench or through static analysis that propagates design ranges to compute derived ranges for all the variables.</li><li>Generate fixed-point MATLAB code by applying proposed fixed-point types.</li><li>Verify the generated fixed-point code and compare the numerical accuracy of the generated fixed-point code with the original floating point code.</li></ol></div><p>Note that this step is optional. You can skip this step if your MATLAB design is already implemented in fixed-point.</p><p><b>HDL Code Generation</b></p><p>The HDL Code Generation step generates HDL code from the fixed-point MATLAB code. You can generate either VHDL or Verilog code that implements your MATLAB design. In addition to generating synthesizable HDL code, HDL Coder&#8482; also generates various reports, including a traceability report that helps you navigate between your MATLAB code and the generated HDL code, and a resource utilization report that shows you, at the algorithm level, approximately what hardware resources are needed to implement the design, in terms of adders, multipliers, and RAMs.</p><p>During code generation, you can specify various optimization options to explore the design space without having to modify your algorithm. In the Design Space Exploration and Optimization Options section below, you can see how you can modify code generation options and optimize your design for speed or area.</p><p><b>HDL Verification</b></p><p>Standalone HDL test bench generation:</p><p>HDL Coder&#8482; generates VHDL and Verilog test benches from your MATLAB scripts for rapid verification of generated HDL code. You can customize an HDL test bench using a variety of options that apply stimuli to the HDL code. You can also generate script files to automate the process of compiling and simulating your code in HDL simulators. These steps help to ensure the results of MATLAB simulation match the results of HDL simulation.</p><p>HDL Coder&#8482; also works with <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/hdl-verifier">HDL Verifier</a> to automatically generate two types of cosimulation testbenches:</p><div><ul><li>HDL cosimulation-based verification works with Mentor Graphics&reg; ModelSim&reg; and QuestaSim&reg;, where MATLAB and HDL simulation happen in lockstep.</li><li>FPGA-in-the-Loop simulation allows you to run a MATLAB simulation with an FPGA board in strict synchronization. You can use MATLAB to feed real world data into your design on the FPGA, and ensure that the algorithm will behave as expected when implemented in hardware.</li></ul></div><p><b>HDL Synthesis</b></p><p>Apart from the language-related challenges, programming for FPGAs requires the use of complex EDA tools. Generating a bitstream from the HDL design and programming the FPGA can be daunting tasks. HDL Coder&#8482; provides automation here, by creating project files for Xilinx&reg; and Altera&reg; that are configured with the generated HDL code. You can use the workflow steps to synthesize the HDL code within the MATLAB environment, see the results of synthesis, and iterate on the MATLAB design to improve synthesis results.</p><h4>Design Space Exploration and Optimization Options<a rel="nofollow" name="d1cf933b-d17d-4d81-8d56-2a0f984df493"></a></h4><p>HDL Coder&#8482; provides the following optimizations to help you explore the design space trade-offs between area and speed. You can use these options to explore various architectures and trade-offs without having to manually rewrite your algorithm.</p><p><b>Speed Optimizations</b></p><div><ul><li><b>Pipelining</b> : To improve the design&#8217;s clock frequency, HDL Coder enables you to insert pipeline registers in various locations within your design. For example, you can insert registers at the design inputs and outputs, and also at the output of a given MATLAB variable in your algorithm.</li><li><b>Distributed Pipelining</b> : HDL Coder also provides an optimization based on retiming to automatically move pipeline registers you have inserted to maximize clock frequency, by minimizing the delay through combinational paths in your design.</li></ul></div><p><b>Area Optimizations</b></p><div><ul><li><b>RAM mapping</b>: HDL Coder&#8482; maps matrices to wires or registers in hardware. If persistent matrix variables are mapped to registers, they can take up a large amount of FPGA area. HDL Coder&#8482; automatically maps persistent matrices to block RAM to improve area efficiency. The challenge in mapping MATLAB matrices to block RAM is that block RAM in hardware typically has a limited set of read and write ports. HDL Coder&#8482; solves this problem by automatically partitioning and scheduling the matrix reads and writes to honor the block RAM&#8217;s port constraints, while still honoring the other control- and data-dependencies in the design.</li><li><b>Resource sharing</b>: This optimization identifies functionally equivalent multiplier operations in MATLAB code and shares them. You can control the amount of multiplier sharing in the design.</li><li><b>Loop streaming</b>: A MATLAB for-loop creates a FOR_GENERATE loop in VHDL. The body of the loop is replicated as many times in hardware as the number of loop iterations. This results in an inefficient use of area. The loop streaming optimization creates a single hardware instance of the loop body that is time-multiplexed across loop iterations.</li><li><b>Constant multiplier optimization</b>: This design level optimization converts constant multipliers into shift and add operations using canonical signed digit (CSD) techniques.</li></ul></div><h4>Best Practices<a rel="nofollow" name="08ade249-3944-44d2-95db-db0d7060c5de"></a></h4><p>Now, let's look at few best practices related to writing MATLAB code when targeting FPGAs.</p><p><b>When writing a MATLAB design:</b></p><div><ul><li>Use the code generation subset of MATLAB supported for HDL code generation.</li><li>Keep the top-level interface as simple as possible. The top-level function size, types, and complexity determine the interface of the chip implemented in hardware.</li><li>Do not pass in a big chunk of parallel data into the design. Parallel data requires a large number of IO pins on the chip, and would probably not be synthesizable.  In a typical image processing design, you should serialize the pixels as inputs and buffer them internally in the algorithm.</li></ul></div><p><b>When writing a MATLAB test bench:</b></p><div><ul><li>Call the design from the testbench function.</li><li>Exercise the design thoroughly. This is particularly important for floating-point to fixed-point conversion, where HDL Coder&#8482; determines the ranges of the variables in the algorithm based on the values the testbench assigns to the variables. You can reuse this testbench to generate an HDL testbench for testing the generated hardware.</li><li>Simulate the design with the testbench prior to code generation to make sure there are no simulation errors, and to make sure all the required files are on the path.</li></ul></div><h4>Conclusion<a rel="nofollow" name="cdf41669-3ba0-44ac-8908-22d323960590"></a></h4><p>HDL Coder&#8482; provides a seamless workflow when you want to implement your algorithm in an FPGA. In this post, I have shown you how to take an image processing algorithm written in MATLAB, convert it to fixed-point, generate HDL code, verify the generated HDL code using the test bench, and finally, synthesize the design and implement it in hardware.</p><p>See this <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/newsroom/FLIR-Speeds-Thermal-Imaging-FPGA-Development-Through-Automatic-HDL-Generation-From-MATLAB.html">article</a> about how one of the HDL Coder customers, FLIR has used MATLAB to HDL workflow to achieve good results. You can also learn more about this workflow using the product examples <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/hdl-coder/examples.html">located here.</a></p><p>We hope this brief introduction to the HDL Coder&#8482; and MATLAB-to-HDL code generation, verification framework has shown how you can quickly get started on implementing your MATLAB designs and target FPGAs. Please let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using HDL Coder&#8482;, let us know about your experiences <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=673#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/kOoWp0H4zmg" height="1" width="1"/>]]></content:encoded>
         <category>News</category>
      </item>
      <item>
         <title>Using ‘dbstop if error’ and conditional breakpoints to debug MATLAB</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/RG2F1ZGkWx8/</link>
         <description>Sometimes MATLAB throws an error, but because the error is inside of a function you can not see what caused this error. By telling the debugger to stop execution under certain conditions or right before an error is thrown you will be better able to understand the conditions that caused the error.</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1077</guid>
         <pubDate>Mon, 08 Apr 2013 12:35:18 +0000</pubDate>
         <content:encoded><![CDATA[Sometimes MATLAB throws an error, but because the error is inside of a function you can not see what caused this error.  By telling the debugger to stop execution under certain conditions or right before an error is thrown you will be better able to understand the conditions that caused the error.


<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate302" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/RG2F1ZGkWx8" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>To Latch or not to Latch?</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/Jna7_rOpDgU/</link>
         <description>Yesterday I explained to a colleague the effect of the Inport block option Latch input for feedback signals of function-call subsystem outputs . I thought it would be interesting to share here. The Problem In the following model, inside the calib function-call subsystem, the Count signal is connected to a Unit Delay block. When logging [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=1955</guid>
         <pubDate>Fri, 05 Apr 2013 14:58:03 +0000</pubDate>
         <content:encoded><![CDATA[<p>Yesterday I explained to a colleague the effect of the Inport block option <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/slref/inport.html#brqe18y-28">Latch input for feedback signals of function-call subsystem outputs
</a>. I thought it would be interesting to share here.</p>

<p><strong>The Problem</strong></p>

<p>In the following <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/Problem_latch.slx">model</a>, inside the <em>calib</em> <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/functioncallsubsystem.html">function-call subsystem</a>, the <em>Count</em> signal is connected to a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/unitdelay.html">Unit Delay</a> block.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/fcnCallLoopModel.png" alt="Model with a Function-Call subsystem involved in a direct feedback loop"/></p>

<p>When logging data, we can see that the input and output of the Unit Delay are identical, as if the signal was not delayed!</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/fcnCallOutput.png" alt="Input and output of the Unit Delay are equal"/></p>

<p>Even though this might seem strange, this behavior is expected. Let's see why.</p> 

<p><strong>The simulation loop</strong></p>

<p>To understand what is happening, you first need to be familiar with the order into which the block methods are executed within the simulation loop. To really understand the simulation loop I recommend the following documentation pages:

<ul>
	<li>First, you need to know that the equations for blocks are implemented in multiple <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/ug/modeling-dynamic-systems.html#f7-22144">block methods</a>: Outputs, Update, Derivative, etc.</li>
	<li>To get an overview of the order into which those methods are called: <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/sfg/how-s-functions-work.html">How S-Functions Work</a></li>
	<li>To get the complete details of all the block methods available: <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/sfg/how-the-simulink-engine-interacts-with-c-s-functions.html">Simulink Engine Interaction with C S-Functions</a></li>
</ul>

<p>In our case, we have a model that is fixed-step and discrete, so the simulation loop is very simple and looks like this:</p> 

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/simulationloop.png" alt="Simulation loop"/></p>

<p> The important thing to understand is that Simulink executes the <strong>Outputs</strong> method of all blocks, and then the <strong>Update</strong> method of all blocks.</p>

<p><strong>The execution order</strong></p>

<p>The second thing we need to know is the order in which blocks are executed. For that, we display the block <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/ug/controlling-and-displaying-the-sorted-order.html">sorted order</a>.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/sortedOrder.png" alt="Sorted Order"/></p>

<p>When you display the sorted order, you can see red numbers displayed on the block. The first number is the number of the system, so the function-call subsystem in this model is system number 3. The second number is the order of the block in this system. In this case, the Gain is the first (<font color="red"><tt>3:0</tt></font>), Unit Delay the second (<font color="red"><tt>3:1</tt></font>), Counter the third (<font color="red"><tt>3:2</tt></font>), etc.</p>

<p><strong>The effect of the latch</strong></p>

<p>To see the effect of latching, I generated code for this model and added comments to highlight the fact that the feedback loop causes the input signal to change immediately as the output is written:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/fcnCallCode.png" alt="Generated Code without latch"/></p>

<p>Such feedback loops break the assumptions on which the Output-Update logic is built... and can make results difficult to interpret. This is why the Latch is available.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/latchInportDialog.png" alt="Inport block dialog"/></p>

<p>With the latch, a copy of the input signal is made at the beginning of the step and this copy is used for the computations:</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/fcnCallCodeWithLoop.png" alt="Generated Code with latch"/></p>

<p><strong>Conclusion</strong></p>

<p>In conclusion, we can say that introducing the latch is safer, but costs an additional copy. If you know that your function-call subsystem might be involved in a direct feedback loop, use Inport Latching to avoid surprises.</p>

<p><strong>Now it's you turn</strong></p>

<p>Are you latching the inputs of your function-call subsystems? Let us know the reason why by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=1955&#comment">comment here</a>.</p><img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/Jna7_rOpDgU" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Design Challenge: Autonomous Battlebots with Simulink</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/OSWZK0qLnM8/</link>
         <description>This week I welcome Dr. Paul Kassebaum to the blog. Paul is a physicist at MathWorks working to engage the public with engineering and science. He fell in love with engineering at the Cooper Union for the Advancement of Science and Art, and then became obsessed with physics at the Worcester Polytechnic Institute, where he [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2208</guid>
         <pubDate>Thu, 04 Apr 2013 16:33:47 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>This week I welcome Dr. Paul Kassebaum to the blog. Paul is a physicist at MathWorks working to engage the public with engineering and science. He fell in love with engineering at the Cooper Union for the Advancement of Science and Art, and then became obsessed with physics at the Worcester Polytechnic Institute, where he earned a Ph.D. specialized in quantum mechanics. His latest projects at MathWorks include designing a digital interactive museum exhibition at the Ecotarium in Worcester and managing a sponsorship between MathWorks and Artisan&#8217;s Asylum. His work at Artisan&#8217;s Asylum focuses on using MATLAB to create 3D prints that help one literally grasp abstract math and physics concepts.</em></p>
<h2>Build Your Own Autonomous Battlebot</h2>
<p>A massive maker space. Cutting-edge software. Expert mentors. And just one week to craft the most devastating robot possible.</p>
<p><em>by Dr. Paul Kassebaum</em></p>
<p>MathWorks is teaming up with <a rel="nofollow" target="_blank" href="http://artisansasylum.com/?page_id=215">Artisan&#8217;s Asylum</a> to wage a <a rel="nofollow" target="_blank" href="http://designchallengebattlebots.com/">robot battle</a> accelerated by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/discovery/simulink-target-hardware.html">Simulink&#8217;s run on target hardware capabilities</a> and the computer controlled manufacturing tools at Artisan&#8217;s Asylum, the largest maker space on the east coast. The fight will serve as the grand finale of the Cambridge Science Festival on Sunday April 21st at the Center for Arts at the Armory, and will be free and open to the public. The contest begins on Sunday April 14th at Artisan&#8217;s Asylum, where teams will design their robots over the course of a week. To sign up and for more info, have a look at <a rel="nofollow" target="_blank" href="http://designchallengebattlebots.com/">designchallengebattlebots.com</a>.</p>
<p><img src="http://blogs.mathworks.com/community/files/artisansAsylumLadderView.png" alt="" title="artisansAsylumLadderView" width="600" height="338" class="alignnone size-full wp-image-2212"/></p>
<p>Sergio Biagioni is working at MathWorks to develop a Simulink framework to aid high school and undergraduate contestants in their algorithm designs. Each robot will be equipped with an <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/arduino-software/arduino-simulink.html">Arduino Mega 2560</a>, a line sensor, touch sensors, sonar, and a wireless feed akin to GPS sent from an eye in the sky. The overhead camera will use the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/computer-vision/">Computer Vision System Toolbox</a> to locate each robot and its orientation based on colored stickers applied to the chassis.</p>
<p><img src="http://blogs.mathworks.com/community/files/sergioWorking01.png" alt="" title="sergioWorking01" width="400" height="505" class="alignnone size-full wp-image-2211"/></p>
<p></p> 
<p>Rob Masek, facilities manager of Artisan&#8217;s Asylum, is organizing the tournament, drawing on his experience as a (three time) contestant on Comedy Central&#8217;s BattleBots and as an organizer of several <a rel="nofollow" target="_blank" href="http://www.usfirst.org/roboticsprograms/frc">US FIRST Robotics competitions</a> and a home-brew robot competition called Pound of Pain. I&#8217;m confident he&#8217;ll be able to replicate his previous successes.</p>
<p><img src="http://blogs.mathworks.com/community/files/robMasek.png" alt="" title="robMasek" width="400" height="269" class="alignnone size-full wp-image-2210"/></p>
<p>Gui Cavalcanti, the founder of Artisan&#8217;s Asylum, is whipping up a robot chassis to help Sergio develop the Simulink framework all of the contestants will use. This prototype robot will be made of the same components available to the contestants, and will be offered up to the contestants to help them jump right into software development before their own chassis are fully operational. While the robots in this competition will have wheels, most of <a rel="nofollow" target="_blank" href="http://projecthexapod.com/blog/">Gui&#8217;s robots</a> have more than their fair share of legs.</p>
<p><img src="http://blogs.mathworks.com/community/files/guiCavalcanti.png" alt="" title="guiCavalcanti" width="400" height="497" class="alignnone size-full wp-image-2209"/></p>
<p></p> 
<p>Stay tuned for more details as the story progresses!</p>
<p>And speaking of robot competitions, have you heard about <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2013/03/25/fun-learning-and-drama-at-the-mathworks-student-robot-challenge/">MathWorks&#8217; latest robot competition in the UK</a>?</p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/OSWZK0qLnM8" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>New Datatype under Development for Possible MATLAB Release</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/y_pNDxHc1QY/</link>
         <description>There is a new datatype we are playing around with that we hope to make available in an upcoming release and we would like your input beforehand.ContentsNew Datatype in ActionLet's Examine the OutputShould We Invest More Resources?New Datatype in ActionLet me show you the new datatype in action so you can first get a feel [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=655</guid>
         <pubDate>Mon, 01 Apr 2013 13:14:09 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>There is a new datatype we are playing around with that we hope to make available in an upcoming release and we would like your input beforehand.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#0db87324-2965-4901-8815-a6971dc0e459">New Datatype in Action</a></li><li><a rel="nofollow" href="#b3bda645-6f1d-4c77-9b0f-97bded4ae828">Let's Examine the Output</a></li><li><a rel="nofollow" href="#d2c273a6-73dd-4ef1-875b-086b90250ba3">Should We Invest More Resources?</a></li></ul></div><h4>New Datatype in Action<a rel="nofollow" name="0db87324-2965-4901-8815-a6971dc0e459"></a></h4><p>Let me show you the new datatype in action so you can first get a feel for it.</p><pre class="codeinput">inputData = magic(3)
</pre><pre class="codeoutput">inputData =
     8     1     6
     3     5     7
     4     9     2
</pre><pre class="codeinput">outputValues = dis(inputData);
</pre><h4>Let's Examine the Output<a rel="nofollow" name="b3bda645-6f1d-4c77-9b0f-97bded4ae828"></a></h4><pre class="codeinput">outputValues
</pre><pre class="codeoutput">Why are you asking?
     4     2     3
     1     9     6
     8     7     5
</pre><p>Well, that's a bit strange, isn't it?  I wonder what the relationship between <tt>inputData</tt> and <tt>outputValues</tt> is.  What can we learn about <tt>outputValues</tt>?</p><pre class="codeinput">whos <span class="string">outputValues</span>
</pre><pre class="codeoutput">  Name              Size            Bytes  Class    Attributes

  outputValues      1x1               248  dis                

</pre><p>Well, it's a <tt>dis</tt> array.  Let's look at it again.</p><pre class="codeinput">outputValues
</pre><pre class="codeoutput">What's it matter to you?
     5     6     9
     4     3     2
     7     8     1
</pre><p>Say what?  Let's check it a few more times.</p><pre class="codeinput">outputValues
outputValues
outputValues
</pre><pre class="codeoutput">Who wants to know?
     6     3     9
     5     8     7
     4     2     1
Who wants to know?
     5     2     9
     1     4     8
     7     6     3
Who are you to ask me that?
     5     3     7
     9     8     2
     1     4     6
</pre><p>Hoping you get the double meaning here - the <tt>dis</tt> array not only mixes up the values of the input for display purposes, but also tries to gently *dis*respect you along the way.</p><p>Even though this is a silly class, I'll show you the code so you can see how simple it is to make such a class.</p><pre class="codeinput">type <span class="string">dis</span>
</pre><pre class="codeoutput">
classdef dis
    %dis dis is a class.
    %   In fact, it's a declasse class.
    
    properties
        Data
    end
    properties (Access=protected)
        Original
    end
    
    properties (Constant)
        Answers = {'Why are you asking?' ,...
            'What''s it matter to you?',...
            'Who are you to ask me that?',...
            'Who wants to know?',...
            'What''s the big deal?'}
    end
    
    methods
        function display(obj)
            disp(dis.Answers{randi(length(dis.Answers),1)})
            obj.Data(:) = obj.Data(randperm(numel(obj.Data)));
            disp(obj.Data)
        end
        function obj = dis(in)
            obj.Original = in;
            obj.Data = reshape(in(randperm(numel(in))),size(in));
        end
    end
    
end


</pre><h4>Should We Invest More Resources?<a rel="nofollow" name="d2c273a6-73dd-4ef1-875b-086b90250ba3"></a></h4><p>Of course, I could also add some numeric functions like <tt>plus</tt> to <tt>dis</tt>, but I didn't take the time, in case you didn't find this possible new MATLAB addition useful. So please share your thoughts with us <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=655#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/y_pNDxHc1QY" height="1" width="1"/>]]></content:encoded>
         <category>Fun</category>
      </item>
      <item>
         <title>Quantum Matrix Processor</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/Y-h2kifMHgo/</link>
         <description>The Quantum Matrix Processor, being announced today, is the world's first viable quantum array processor. Basic matrix operations are done instantaneously, with infinite procession. The programming environment is classic MATLAB.ContentsQuantum Research PartnersQMPQurealUncertainty PrincipleProgramming EnvironmentLINPACK BenchmarkQuantum Research PartnersI am pleased to be involved in today's announcement of the QMP, the Quantum Matrix Processor. This new device [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=584</guid>
         <pubDate>Mon, 01 Apr 2013 13:00:18 +0000</pubDate>
         <content:encoded><![CDATA[<style type="text/css">

h1 {font-size:18pt;}
h2.titlebg {font-size:13pt;}
h3 {color:#4A4F55;padding:0px;margin:5px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:11pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}
h4 {color:#4A4F55;padding:0px;margin:0px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:10pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}

p {padding:0px;margin:0px 0px 20px;}
img {padding:0px;margin:0px 0px 20px;border:none;}
p img, pre img, tt img, li img {margin-bottom:0px;}

ul {padding:0px;margin:0px 0px 20px 23px;list-style:square;}
ul li {padding:0px;margin:0px 0px 7px 0px;background:none;}
ul li ul {padding:5px 0px 0px;margin:0px 0px 7px 23px;}
ul li ol li {list-style:decimal;}
ol {padding:0px;margin:0px 0px 20px 0px;list-style:decimal;}
ol li {padding:0px;margin:0px 0px 7px 23px;list-style-type:decimal;}
ol li ol {padding:5px 0px 0px;margin:0px 0px 7px 0px;}
ol li ol li {list-style-type:lower-alpha;}
ol li ul {padding-top:7px;}
ol li ul li {list-style:square;}

pre, tt, code {font-size:12px;}
pre {margin:0px 0px 20px;}
pre.error {color:red;}
pre.codeinput {padding:10px;border:1px solid #d3d3d3;background:#f7f7f7;}
pre.codeoutput {padding:10px 11px;margin:0px 0px 20px;color:#4c4c4c;}

 _filtered {width:100%;}

span.keyword {color:#0000FF;}
span.comment {color:#228B22;}
span.string {color:#A020F0;}
span.untermstring {color:#B20000;}
span.syscmd {color:#B28C00;}

.footer {width:auto;padding:10px 0px;margin:25px 0px 0px;border-top:1px dotted #878787;font-size:0.8em;line-height:140%;font-style:italic;color:#878787;text-align:left;float:none;}
.footer p {margin:0px;}

</style><div class="content"><p>The Quantum Matrix Processor, being announced today, is the world's first viable quantum array processor.  Basic matrix operations are done instantaneously, with infinite procession.  The programming environment is classic MATLAB.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#943094f0-1fe1-4240-918e-809b5b67ac37">Quantum Research Partners</a></li><li><a rel="nofollow" href="#8bf2b0ef-0ed5-4ace-87a3-efaaf2577972">QMP</a></li><li><a rel="nofollow" href="#fc39789f-4763-411e-b9cc-55fc7fd12e9c">Qureal</a></li><li><a rel="nofollow" href="#d986cb19-7250-449e-94c8-a57a3741c019">Uncertainty Principle</a></li><li><a rel="nofollow" href="#f5f5e743-5d84-449b-afa2-4248d4bbb067">Programming Environment</a></li><li><a rel="nofollow" href="#075c8620-eb42-4fb4-a57b-78e7188f5a9b">LINPACK Benchmark</a></li></ul></div><h4>Quantum Research Partners<a rel="nofollow" name="943094f0-1fe1-4240-918e-809b5b67ac37"></a></h4><p>I am pleased to be involved in today's announcement of the QMP, the Quantum Matrix Processor.  This new device has been developed by Quantum Research Partners, a startup here in Santa Fe that was formed two years ago by a team from Los Alamos National Lab.  I have been a consultant from the beginning of their project because they have based their design on classic MATLAB.</p><h4>QMP<a rel="nofollow" name="8bf2b0ef-0ed5-4ace-87a3-efaaf2577972"></a></h4><p>The QMP is similar conceptually to a GPU, or Graphics Processing Unit. It is a coprocessor that interfaces with the motherboard via an expansion slot such as PCI Express or Accelerated Graphics Port. Matrices are transferred between the memories and registers of the CPU, or central processor, and the coprocessor.  Once the data is available in the QMP, quantum computing can take place.</p><h4>Qureal<a rel="nofollow" name="fc39789f-4763-411e-b9cc-55fc7fd12e9c"></a></h4><p>Traditional quantum computing involves "qubits", where a quantum circuit represents a single bit and quantum arithmetic operations are similar to digital arithmetic operations.  The primary innovative aspect of the QMP is the "qureal" where a single quantum circuit represents a real number. The five basic arithmetic operations of addition, subtraction, multiplication, division, and square root, can be carried out instantaneously, according to the rules of real arithmetic.</p><p>Quantities are stored in qureal registers and qureal memory as real numbers. There is no representation error.  Arithmetic operations are carried out exactly.  There is no roundoff error.  Arithmetic operations are done instantaneously.  If it could be measured, the execution time of an addition or multiplication operation would be found to be zero.</p><h4>Uncertainty Principle<a rel="nofollow" name="d986cb19-7250-449e-94c8-a57a3741c019"></a></h4><p>Heisenberg's uncertainty principle implies that it is not possible to access an infinitely precise real number in finite time.  It would take an infinite amount of time, for example, to access the binary or decimal representation of a real result.</p><h4>Programming Environment<a rel="nofollow" name="f5f5e743-5d84-449b-afa2-4248d4bbb067"></a></h4><p>The programming environment of the QMP is based on MATLAB.  The beta release of the environment is an implementation of what is now called "classic MATLAB", the simple interactive matrix calculator that I developed before we started MathWorks.  The available features include basic MATLAB matrix management and command processing.  Each of the following functions has been implemented as a single QMP instruction, so it is executed essentially instantaneously on a matrix of qureals.</p><pre>   ABS   ATAN  BASE  CHAR  CHOL  CHOP  COND  CONJ
   COS   DET   DIAG  DIAR  DISP  EIG   EPS   EXEC
   EXP   EYE   FLOP  HESS  HILB  IMAG  INV   KRON
   LINE  LOAD  LOG   LU    MAGI  NORM  ONES  ORTH
   PINV  PLOT  POLY  PRIN  PROD  QR    RAND  RANK
   RAT   RCON  REAL  ROOT  ROUN  RREF  SAVE  SCHU
   SIN   SIZE  SQRT  SUM   SVD   TRIL  TRIU  USER
   CLEA  ELSE  END   EXIT  FOR   HELP  IF    LONG
   RETU  SEMI  SHOR  WHAT  WHIL  WHO   WHY</pre><h4>LINPACK Benchmark<a rel="nofollow" name="075c8620-eb42-4fb4-a57b-78e7188f5a9b"></a></h4><p>This processor can solve a system of simultaneous linear equations instantaneously.  Does that qualify the QMP as the faster computer in the world? My colleague Jack Dongarra and the other folks running the <a rel="nofollow" target="_blank" href="http://www.top500.org/">top 500 list</a> will have two concerns when we submit our benchmark results.  First, we can't access the computed solution in zero time.  And, second my program is written in MATLAB, not Fortran.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/Y-h2kifMHgo" height="1" width="1"/>]]></content:encoded>
         <category>Fun</category>
      </item>
      <item>
         <title>Cluster-based image display</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/340EPqfkTRY/</link>
         <description>Although this is the time of year that I normally mention some of the new features from the &quot;a&quot; release, today I thought I would focus on a feature added several releases ago that I think deserves more attention: parallel cluster-based image display. I can't remember exactly when this was released; I think it might [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=814</guid>
         <pubDate>Mon, 01 Apr 2013 10:00:28 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Although this is the time of year that I normally mention some of the new features from the "a" release, <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/April_Fools'_Day">today</a> I thought I would focus on a feature added several releases ago that I think deserves more attention: parallel cluster-based image display. I can't remember exactly when this was released; I think it might have been R2011c.</p><p>Anyway, it turns out image display speed can be dramatically increased if we exploit the capabilities of today's massive parallel computing clusters. You start by opening a MATLAB pool from your desktop session using the Parallel Computing Toolbox function <tt>matlabpool</tt>. The Parallel Computing Toolbox has a new cluster profile that makes it easy to set things up for fast image display:</p><pre>matlabpool image-display</pre><p>Once the pool is configured, then the Image Processing Toolbox function <tt>imshow</tt> automatically uses the workers in the pool.</p><p>Let's try it with my blog author picture:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/Eddins_Steve_140x211.jpg" alt=""> </p><p>(I'm writing this blog post at home, so for a cluster I'll be using my home-brew video game console, which runs on a cluster of 128 <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/TRS-80">TRS-80s</a>.)</p><pre>imshow</pre><p>Here's what the display looks like on worker #37:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/cluster-37.png" alt=""> </p><p>And here is the display on worker #92:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/cluster-92.png" alt=""> </p><p>If you look carefully, you can see that the pixel block is not exactly the same size on the two workers. That's because of the automatic worker load balancing feature. Way cool!</p><p>Let's get down to some numbers. Specifically, I was interested to see how well image display performance scales with the number of workers. I used my function <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/18798-timeit-benchmarking-function"><tt>timeit</tt></a> to measure the display speed as I varied the number of workers. The plot below is "normalized speed-up." That is, 1 is the image display speed for normal MATLAB, with no use of the Parallel Computing Toolbox.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/perf-graph.png" alt=""> </p><p>As you can see, we get almost perfectly linear scaling with the number of workers. (I'm not sure what's going on with that blip on the left. I think it might have been caused by a bad tape unit on worker #25.)</p><p>So, Parallel Computing Toolbox users, please give this a try and let us know about your experience!</p><p>Before I wrap it up for today, I can't resist giving a hint about future development directions. (Long-time readers know how much MathWorks loves to preannounce features.) We recently got our hands on one of the experimental new superfluidic clusters. Early indications are that we'll be able to get image display speed to scale with the <b>square</b> of the number of workers!  Woo-hoo!</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/340EPqfkTRY" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Multiple Y Axes</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/27LIZTZvD7o/</link>
         <description>We were musing here about how common it is to want more than two Y axes on a plot. Checking out the File Exchange, there seem to be several candidates, indicating that this is something at least some people find useful.ContentsSample PlotList of Some PossibilitiesWhat are You Plotting with More Y Axes?Sample PlotHere's a sample [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=665</guid>
         <pubDate>Wed, 27 Mar 2013 19:42:07 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>We were musing here about how common it is to want more than two Y axes on a plot.  Checking out the File Exchange, there seem to be several candidates, indicating that this is something at least some people find useful.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#708b44b8-5fb8-446f-92c3-5a7356e4ab5d">Sample Plot</a></li><li><a rel="nofollow" href="#3b58211f-2b7e-484d-952e-5e8fffa5f81c">List of Some Possibilities</a></li><li><a rel="nofollow" href="#8c4f04ed-9976-4594-92c5-c77284c345fe">What are You Plotting with More Y Axes?</a></li></ul></div><h4>Sample Plot<a rel="nofollow" name="708b44b8-5fb8-446f-92c3-5a7356e4ab5d"></a></h4><p>Here's a sample plot using <tt>plotyy</tt> that comes with MATLAB.</p><pre class="codeinput">x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,<span class="string">'plot'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/plotyyFEX_01.png" alt=""> <h4>List of Some Possibilities<a rel="nofollow" name="3b58211f-2b7e-484d-952e-5e8fffa5f81c"></a></h4><p>In addition to <tt>plotyy</tt> in MATLAB, here's a list of <i>some</i> of the candidates from the File Exchange.</p><div><ul><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/9016"> <tt>addaxis</tt></a></li><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/4425-ploty4-m"><tt>plot4y</tt></a></li><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/26550-myplotyy"><tt>Myplotyy</tt></a></li><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/1017-plotyyy"><tt>plotyyy</tt></a></li><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/10242-plots-m-plotses-m"><tt>plots.m plotses.m</tt></a></li><li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/39595-multiplotyyy"><tt>multiplotyyy</tt></a></li></ul></div><h4>What are You Plotting with More Y Axes?<a rel="nofollow" name="8c4f04ed-9976-4594-92c5-c77284c345fe"></a></h4><p>I am curious to know what kind of data or results you are plotting so that having multiple y-axes makes a compelling presentation.  Let us know <a rel="nofollow" target="_blank" href="http://blogs.mathwoks.com/p=665#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/27LIZTZvD7o" height="1" width="1"/>]]></content:encoded>
         <category>Graphics</category>
      </item>
      <item>
         <title>New for R2013a: Time Scope with Triggering!</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/hURwDXnGoDA/</link>
         <description>Today we are happy to welcome guest blogger Kirthi Devleker to talk about a new trigger functionality added to the Time Scope in R2013a. Did you know that a Trigger functionality is now available with the Time Scope in the DSP System Toolbox (R2013a) ? The Time Scope ships both as a System object and [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=1857</guid>
         <pubDate>Mon, 25 Mar 2013 21:07:11 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>Today we are happy to welcome guest blogger Kirthi Devleker to talk about a new trigger functionality added to the Time Scope in R2013a.</em></p>

<p>Did you know that a Trigger functionality is now available with the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/2012/04/16/a-scope-for-simulink-and-matlab/">Time Scope</a> in the DSP System Toolbox (R2013a) ? The Time Scope ships both as a System object and also as a Simulink block with the<a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/dsp-system/"> DSP System Toolbox</a></p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/1.gif"><img title="Before Triggering" src="http://blogs.mathworks.com/images/seth/2013Q1/1.gif" alt="Time Scope without trigger"/></a>    
<a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/2.gif"><img title="After Enabling Trigger" src="http://blogs.mathworks.com/images/seth/2013Q1/2.gif" alt="Time Scope with trigger"/></a></p>

<p>Triggers are ubiquitous on real-world hardware oscilloscopes. They are useful to analyze signals,specifically to stabilize a repetitive waveform and search for a occurrence of a  particular pattern in the signal.</p>

<p><strong>Trigger Modes</strong>:</p>

<p>The Trigger in Time Scope supports 3 different modes of operation for a given trigger type. They are:</p>
<ul>
<li>Auto: In this mode, the Time Scope stabilizes the display if the trigger criteria is met or continues to display the incoming signal.</li>
<li>Normal : The time scope displays the stabilized signal only if the trigger criteria is met otherwise nothing is displayed.</li>
<li>Once: The time scope displays the signal only for the very first time the trigger event is encountered. (Simulation will still keep running)</li>
</ul>

<p>Here is an animation showing those different modes:</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/showAllTriggers.gif"><img title="Triggering modes available in the time scope" src="http://blogs.mathworks.com/images/seth/2013Q1/showAllTriggers.gif" alt="Triggering modes available in the time scope"/></a></p> 

<p>Let's look at a few more examples</p>

<p><strong>Edge Triggering</strong></p>

<p>Let's create a simple sine wave and display it on the Time Scope.</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/mcode.png"><img src="http://blogs.mathworks.com/images/seth/2013Q1/mcode.png" alt="Fs = 44.1e3;
Span = 1e-3
hsin = dsp.SineWave('Amplitude',10,'Frequency',2.2e3,...
    'SampleRate', Fs, 'SamplesPerFrame', 10);
hts = dsp.TimeScope('SampleRate', Fs, 'TimeSpan', Span);

for ii = 1:1e5
    x = step(hsin);
    step(hts,x);
end"/></a></p>

<p>As soon as you click the Trigger button, the triggers panel open allowing you to configure options like level, type, polarity, etc.</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/triggerDemo.gif"><img src="http://blogs.mathworks.com/images/seth/2013Q1/triggerDemo.gif" alt="Configuring the trigger"/></a></p>

<p><strong>Runt Triggering</strong></p>

<p>What are Runt signals? Runt signals are the signals which typically cross a voltage threshold level but fail to cross a second threshold before re-crossing the first threshold level. Runt signals are frequently encountered in digital circuits.</p>

<p>For example if we look at the following waveform:</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/pwm_best.gif"><img src="http://blogs.mathworks.com/images/seth/2013Q1/pwm_best.gif" alt="Noisy PWM signal"/></a></p>

<p>To look for Runt signals, Let us enable the Trigger, set the Trigger Mode to <em>Normal</em>, set the trigger type as <em>Runt</em>, adjust the voltage threshold and then the Time Scope detects and displays the presence of any Runt signals in the incoming data stream.</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/runt.gif"><img src="http://blogs.mathworks.com/images/seth/2013Q1/runt.gif" alt="Runt Trigger"/></a></p>

<p><strong>Now it's your turn</strong></p>

<p>Go through the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/dsp/ref/timescope.html#btsl04t">trigger documentation</a>, give this a try and let us know what you think by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=1857&#comment">comment here</a>.</p>
<img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/hURwDXnGoDA" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Using otherwise to throw errors in a switch case</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/4K6v1eZQQT8/</link>
         <description>In some code there is an enumerated set of choices. People will use a switch case statement to check for all but one choice and then catch that last one in the &amp;#8216;otherwise&amp;#8217; block of their code. However, if there is unexpected inputs, the &amp;#8216;otherwise&amp;#8217; will fire when it should not. This video shows a [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1075</guid>
         <pubDate>Mon, 25 Mar 2013 19:46:57 +0000</pubDate>
         <content:encoded><![CDATA[In some code there is an enumerated set of choices. People will use a switch case statement to check for all but one choice and then catch that last one in the &#8216;otherwise&#8217; block of their code.  However, if there is unexpected inputs, the &#8216;otherwise&#8217; will fire when it should not.  

<p>
<p>
This video shows a technique for catching this problem.  It is important to catch these errors from unexpected inputs immediately, because they can have effects on your code much farther down the line.  When this happens, it would be hard to trace back to the cause.
<p>
<p>


<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate303" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div>
<img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/4K6v1eZQQT8" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Fun, learning, and drama at the MathWorks Student Robot Challenge</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/gsMpU_A45ko/</link>
         <description>This week I&amp;#8217;d like to introduce guest blogger Dr Tanya Morton. Tanya leads the Application Engineering team in the UK, helping customers in industry and academia to apply MATLAB &amp;#038; Simulink to their technical, business and educational challenges. She is keen to encourage more people to enjoy lifelong careers in science, technology, engineering and mathematics. [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2181</guid>
         <pubDate>Mon, 25 Mar 2013 15:00:32 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>This week I&#8217;d like to introduce guest blogger Dr Tanya Morton. Tanya leads the Application Engineering team in the UK, helping customers in industry and academia to apply MATLAB &#038; Simulink to their technical, business and educational challenges. She is keen to encourage more people to enjoy lifelong careers in science, technology, engineering and mathematics. You can find Tanya on <a rel="nofollow" target="_blank" href="http://twitter.com/tanyammorton">Twitter</a> and <a rel="nofollow" target="_blank" href="http://www.linkedin.com/in/tanyammorton">LinkedIn</a>.</em></p>
<h2>The MathWorks Student Robot Challenge</h2>
<p><em>by Dr. Tanya Morton, MathWorks UK</em></p>
<p>Earlier this year a colleague and I were bouncing around ideas for ways to do more outreach with the local student community. He pointed behind him and said, &#8220;Why don&#8217;t we make use of the empty space in the new office to host a robot contest?&#8221; An idea was born…</p>
<p>Last Friday, this idea came to fruition when MathWorks hosted a Student Robot Challenge. Nine teams from the University of Cambridge participated in the contest. The challenge was to develop a controller for a LEGO MINDSTORM NXT robot to make it visit a set of 12 locations on an arena in the shortest time possible. </p>
<p>After a briefing, the students started working their way through short tasks designed to bring them up to speed with Simulink, the principles of controller design, and the process of generating code to run on the robot. Within five minutes, you could hear the first robot spinning on the spot. </p>
<p><img src="http://blogs.mathworks.com/community/files/tanya1.jpg" alt=" title=" width="464" height="299" class="alignnone size-full wp-image-2187"/></p>
<p>In the afternoon, the students explored a variety of navigation and control strategies, which they tested using a combination of simulation and hardware testing on their robot. </p>
<p>The day ended with a final contest where the teams competed against each other to navigate to the most locations in the shortest time. Team names were picked out of the hat to decide the running order for the final contest.  The first to go was the QED-grad team, an experienced team of PhD engineering students. The team successfully hit all 12 locations in a time of 1 minute and 41.3 seconds. Their robot left each location quickly, but tended to spiral around the next target rather than approach it directly.</p>
<p><img src="http://blogs.mathworks.com/community/files/tanya2.jpg" alt=" title=" width="482" height="340" class="alignnone size-full wp-image-2188"/></p>
<p><em>The LEGO robot with positioning ball used in the final arena</em><br/></p>
<p>Five of the next seven teams were not able to complete the course within the 3-minute time limit. One of these teams was QED-&#8217;12, a team of first-year undergraduate engineers who had been taught to program LEGO by the QED-grad team. Briefly, it seemed that the youngest team in the competition were going to beat their lab demonstrators; however, their robot stopped at the 11th point because they had forgotten to program in the 12th. An important lesson learned! Only the team of PhD mathematicians on Team CCA came close to the time of the QED-grad team with a time of 1 minute and 44.5 seconds.  </p>
<p>The last team to go was MatLads, with its leader Richard Peach, a 3rd year undergraduate engineer. MatLads&#8217; robot moved neatly around the course to knock the QED-grad team off the top spot to win by a mere 1.6 seconds! </p>
<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/tanya3.png"><img src="http://blogs.mathworks.com/community/files/tanya3-300x300.png" alt=" title=" width="300" height="300" class="alignnone size-medium wp-image-2189"/></a></p>
<p><em>Paths taken by the fastest two robots (click to see a larger image)</em><br/></p>
<p>It was an exciting finale to a fun event. The students enjoyed the project-based learning experience and gained some valuable skills to help them in their future careers. </p>
<p><img src="http://blogs.mathworks.com/community/files/tanya4.png" alt=" title=" width="487" height="505" class="alignnone size-full wp-image-2190"/></p>
<p><em>The Final Leaderboard</em><br/></p>
<ul>
<li>If you would like to program your own LEGO robot, then a good starting point is the <a rel="nofollow" target="_blank" href="http://cts.businesswire.com/ct/CT?id=smartlink&#038;url=http%3A%2F%2Fwww.mathworks.co.uk%2Facademia%2Flego-mindstorms-nxt-software%2Findex.html&#038;esheet=50592064&#038;lan=en-US&#038;anchor=LEGO+MINDSTORMS+NXT+Support+from+MATLAB+and+Simulink&#038;index=3&#038;md5=bad9049bd1240188c815fbcde5322b73">LEGO MINDSTORMS NXT Support from MATLAB and Simulink</a>.</li>
<li>If you would like to encourage more project-based learning in your local university or high-school, then encourage your lecturers to learn about <a rel="nofollow" target="_blank" href="http://cts.businesswire.com/ct/CT?id=smartlink&#038;url=https%3A%2F%2Fwww.mathworks.co.uk%2Fcompany%2Fevents%2Fwebinars%2Fwbnr69522.html&#038;esheet=50592064&#038;lan=en-US&#038;anchor=Teaching+Mechatronics+with+MATLAB%2C+Simulink%2C+and+Low+Cost+Hardware&#038;index=4&#038;md5=d81367702921866171d96c6d706df906">Teaching Mechatronics with MATLAB, Simulink, and Low Cost Hardware</a>.</li>
<li>See the <a rel="nofollow" target="_blank" href="http://cts.businesswire.com/ct/CT?id=smartlink&#038;url=http%3A%2F%2Fwww.mathworks.co.uk%2Facademia%2Fcontests&#038;esheet=50592064&#038;lan=en-US&#038;anchor=Student+Robot+Challenge&#038;index=2&#038;md5=555368b33ca92ab11fb9df0d178f1035">Student Robot Challenge for further information</a>.</li>
</ul>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/gsMpU_A45ko" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Revisiting dctdemo – part 3</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/c0gCy6KbXzw/</link>
         <description>This is the third part of my plan to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features. I got the idea from Dave Garrison's recent article on writing MATLAB apps.Here's the old app I'm trying to reinvent: And here's what I had working the last time: The [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=809</guid>
         <pubDate>Thu, 21 Mar 2013 20:14:57 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>This is the third part of my plan to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features. I got the idea from Dave Garrison's <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/newsletters/articles/writing-apps-in-matlab.html">recent article</a> on writing MATLAB apps.</p><p>Here's the old app I'm trying to reinvent:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo-screen-shot.png" alt=""> </p><p>And here's what I had working the last time:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dct-compression-v2.png" alt=""> </p><p>The code isn't doing any actual DCT computations yet. The idea is to compute 8-by-8 block DCTs, zero out the least significant DCT coefficients of each block, and then reconstruct the image by computing the inverse DCT of each 8-by-8 block.</p><p>Let me show how this will work on the sample image I'm using for the app:</p><pre class="codeinput">pout = imread(<span class="string">'pout.tif'</span>);
pout2 = pout(1:240,:);
I = im2double(adapthisteq(pout2));
imshow(I)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part3_01.png" alt=""> <p>First, use <tt>blockproc</tt> to compute the 8-by-8 2-D DCTs.</p><pre class="codeinput">f = @(block) dct2(block.data);
A = blockproc(I,[8 8],f);
imshow(A,[])
title(<span class="string">'DCT coefficients'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part3_02.png" alt=""> <p>Second, I want to compute the variances of each of the 64 coefficients. That is, compute the variance of the (1,1) DCT coefficients from each block, the variance of the (1,2) DCT coefficients from each block, and so on. I'll use the computed variances to determine which DCT coefficients to keep and which to zero out. To do this, I'll rearrange the elements from the previous step so that the corresponding DCT coefficients are together in the columns of a 64-column matrix.</p><pre class="codeinput">B = im2col(A,[8 8],<span class="string">'distinct'</span>)';
vars = var(B);
plot(vars)
title(<span class="string">'Variances of the 64 DCT coefficients'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part3_03.png" alt=""> <p>Next, suppose we want to keep the 3 block DCT coefficients with the highest variances. I'll use <tt>sort</tt> to figure out which ones to keep.</p><pre class="codeinput">[~,idx] = sort(vars,<span class="string">'descend'</span>);
keep = idx(1:3)
</pre><pre class="codeoutput">
keep =

     1     9     2

</pre><p>For an 8-by-8 block of DCT coefficients, index values 1, 9, and 2 correspond to the upper-left DCT coefficient and the two coefficients just the right and down from it. Let's keep just those coefficients.</p><pre class="codeinput">B2 = zeros(size(B));
B2(:,keep) = B(:,keep);
</pre><p>Now I'll rearrange the columns back into blocks and reconstruct the image by computing the inverse DCT of each block.</p><pre class="codeinput">C = col2im(B2',[8 8],size(I),<span class="string">'distinct'</span>);
finv = @(block) idct2(block.data);
D = blockproc(C,[8 8],finv);
imshow(D)
title(<span class="string">'Image reconstructed from 3 DCT coefficients per block'</span>)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part3_04.png" alt=""> <p>This algorithm code into a local function to go at the bottom of my app code file, like this:</p><pre>function I2 = reconstructImage(I,n)
% Reconstruct the image from n of the DCT coefficients in each 8-by-8
% block. Select the n coefficients with the largest variance across the
% image.</pre><pre>% Compute 8-by-8 block DCTs.
f = @(block) dct2(block.data);
A = blockproc(I,[8 8],f);</pre><pre>% Compute DCT coefficient variances and decide
% which to keep.
B = im2col(A,[8 8],'distinct')';
vars = var(B);
[~,idx] = sort(vars,'descend');
keep = idx(1:n);</pre><pre>% Zero out the DCT coefficients we are not keeping.
B2 = zeros(size(B));
B2(:,keep) = B(:,keep);</pre><pre>% Reconstruct image using 8-by-8 block inverse
% DCTs.
C = col2im(B2',[8 8],size(I),'distinct');
finv = @(block) idct2(block.data);
I2 = blockproc(C,[8 8],finv);
end</pre><p>I already have an <tt>update</tt> method in my class, so I can add code to that method that will compute the reconstructed image and error image. Here's the revised <tt>update</tt> method:</p><pre>function update(app)
    recon_image = reconstructImage(app.OriginalImage, ...
        app.NumDCTCoefficients);</pre><pre>    diff_image = imabsdiff(app.OriginalImage, recon_image);</pre><pre>    imshow(app.OriginalImage,'Parent',app.OriginalImageAxes);
    title(app.OriginalImageAxes,'Original Image');</pre><pre>    imshow(recon_image,'Parent',app.ReconstructedImageAxes);
    title(app.ReconstructedImageAxes,'Reconstructed Image');</pre><pre>    imshow(diff_image,[],'Parent',app.ErrorImageAxes);
    title(app.ErrorImageAxes,'Error Image');</pre><pre>    imshow(zeros(size(app.OriginalImage)),'Parent',app.MaskAxes);
    title(app.MaskAxes,'DCT Coefficient Mask');
    drawnow;
end</pre><p>Although I don't have all the interactive behavior wired up yet, and don't have the DCT coefficient mask visualization done yet, the app runs and looks a bit more finished than it did before. It now shows the results for reconstructing the image from 3 DCT coefficients per block.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dct-compression-example-v3.png" alt=""> </p><p>I think it'll take just one more post to finish making the rest of this app work.</p>
<div><ul><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/08/revisiting-dctdemo-part-1/">Revisiting dctdemo - part 1</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/21/revisiting-dctdemo-part-2/">Revisiting dctdemo - part 2</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/21/revisiting-dctdemo-part-3/">Revisiting dctdemo - part 3</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/04/12/revisiting-dctdemo-part-4/">Revisiting dctdemo - part 4</a></li></ul></div>
<p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/c0gCy6KbXzw" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Easter</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/3AFxZnw3BlQ/</link>
         <description>Easter Sunday is March 31 this year. Why? How is the date of Easter determined?ContentsEaster DayDon KnuthMetonic cycleMATLAB programReferencesEaster DayEaster Day is one of the most important events in the Christian calendar. It is also one of the most mathematically elusive. In fact, regularization of the observance of Easter was one of the primary motivations [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=549</guid>
         <pubDate>Mon, 18 Mar 2013 17:00:13 +0000</pubDate>
         <content:encoded><![CDATA[<style type="text/css">

h1 {font-size:18pt;}
h2.titlebg {font-size:13pt;}
h3 {color:#4A4F55;padding:0px;margin:5px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:11pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}
h4 {color:#4A4F55;padding:0px;margin:0px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:10pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}

p {padding:0px;margin:0px 0px 20px;}
img {padding:0px;margin:0px 0px 20px;border:none;}
p img, pre img, tt img, li img {margin-bottom:0px;}

ul {padding:0px;margin:0px 0px 20px 23px;list-style:square;}
ul li {padding:0px;margin:0px 0px 7px 0px;background:none;}
ul li ul {padding:5px 0px 0px;margin:0px 0px 7px 23px;}
ul li ol li {list-style:decimal;}
ol {padding:0px;margin:0px 0px 20px 0px;list-style:decimal;}
ol li {padding:0px;margin:0px 0px 7px 23px;list-style-type:decimal;}
ol li ol {padding:5px 0px 0px;margin:0px 0px 7px 0px;}
ol li ol li {list-style-type:lower-alpha;}
ol li ul {padding-top:7px;}
ol li ul li {list-style:square;}

pre, tt, code {font-size:12px;}
pre {margin:0px 0px 20px;}
pre.error {color:red;}
pre.codeinput {padding:10px;border:1px solid #d3d3d3;background:#f7f7f7;}
pre.codeoutput {padding:10px 11px;margin:0px 0px 20px;color:#4c4c4c;}

 _filtered {width:100%;}

span.keyword {color:#0000FF;}
span.comment {color:#228B22;}
span.string {color:#A020F0;}
span.untermstring {color:#B20000;}
span.syscmd {color:#B28C00;}

.footer {width:auto;padding:10px 0px;margin:25px 0px 0px;border-top:1px dotted #878787;font-size:0.8em;line-height:140%;font-style:italic;color:#878787;text-align:left;float:none;}
.footer p {margin:0px;}

</style><div class="content"><p>Easter Sunday is March 31 this year.  Why? How is the date of Easter determined?</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#b0268787-2bdc-4222-8cf5-df42f24bf441">Easter Day</a></li><li><a rel="nofollow" href="#fb7f4943-cb1e-43d7-afa9-92719e951ca6">Don Knuth</a></li><li><a rel="nofollow" href="#ee8ff8af-8d48-44d4-9752-599caf54dd65">Metonic cycle</a></li><li><a rel="nofollow" href="#b2f7c023-ebaf-4191-826d-c5a766fd701e">MATLAB program</a></li><li><a rel="nofollow" href="#d5123200-4ce1-4de5-910c-cf77d13f9a21">References</a></li></ul></div><h4>Easter Day<a rel="nofollow" name="b0268787-2bdc-4222-8cf5-df42f24bf441"></a></h4><p>Easter Day is one of the most important events in the Christian calendar. It is also one of the most mathematically elusive. In fact, regularization of the observance of Easter was one of the primary motivations for calendar reform centuries ago.</p><p>Easter is linked to the Jewish Passover. The informal rule is that Easter Day is the first Sunday after the first full moon after the vernal equinox.  But the ecclesiastical full moon and equinox involved in this rule are not always the same as the corresponding astronomical events, which, after all, depend upon the location of the observer on the earth.  The date varies between March 22 and April 25.</p><p>There is an <a rel="nofollow" target="_blank" href="https://www.mathworks.com/moler/exm/exm/easter.m"><tt>easter</tt></a> program in <a rel="nofollow" target="_blank" href="https://www.mathworks.com/moler/exm/index.html"><i>Experiments with MATLAB</i></a>. Let's check this year.</p><pre class="codeinput">datestr(easter(2013))
</pre><pre class="codeoutput">ans =
31-Mar-2013
</pre><p>How about next year?</p><pre class="codeinput">datestr(easter(2014))
</pre><pre class="codeoutput">ans =
20-Apr-2014
</pre><h4>Don Knuth<a rel="nofollow" name="fb7f4943-cb1e-43d7-afa9-92719e951ca6"></a></h4><p>The <i>EXM</i> program is based on the algorithm presented in the first volume of the classic series by Donald Knuth, <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming">The Art of Computer Programming</a>. Knuth has used it in several publications to illustrate different programming languages.  The task has often been the topic of an exercise in computer programming courses.</p><p>Knuth says that the algorithm is due to the Neapolitan astronomer Aloysius Lilius and the German Jesuit mathematician Christopher Clavious in the late 16th century  and that it is used by most Western churches to determine the date of Easter Sunday for any year after 1582.</p><h4>Metonic cycle<a rel="nofollow" name="ee8ff8af-8d48-44d4-9752-599caf54dd65"></a></h4><p>The earth's orbit around the sun and the moon's orbit around the earth are not in sync.  It takes the earth about 365.2425 days to orbit the sun. This is known as a tropical year.  The moon's orbit around the earth is complicated, but an average orbit takes about 29.53 days.  This is known as a synodic month.  The fraction</p><pre class="codeinput">year = 365.2425;
month = 29.53;
format <span class="string">rat</span>
ratio = year/month
</pre><pre class="codeoutput">ratio =
    6444/521   
</pre><p>is not the ratio of small integers.  However, in the 5th century BC, an astronomer from Athens named Meton observed that the ratio is very close to 235/19.</p><pre class="codeinput">format <span class="string">short</span>
ratio
meton = 235/19
</pre><pre class="codeoutput">ratio =
   12.3685
meton =
   12.3684
</pre><p>In other words, 19 tropical years is close to 235 synodic months. This Metonic cycle was the basis for the Greek calendar and is the key to the algorithm for determining Easter.</p><h4>MATLAB program<a rel="nofollow" name="b2f7c023-ebaf-4191-826d-c5a766fd701e"></a></h4><p>Here is the complete MATLAB program.</p><pre class="codeinput"><span class="comment">% addpath ../../exm</span>
type <span class="string">easter</span>
</pre><pre class="codeoutput">
function dn = easter(y)
% EASTER  Date of Easter.
% EASTER(y) is the datenum of Easter in year y.
% Ref: Donald Knuth, The Art of Computer Programming,
%      Fundamental Algorithms, pp. 155-156.

% Golden number in 19-year Metonic cycle.
g = mod(y,19) + 1;

% Century number.
c = floor(y/100) + 1;

% Corrections for leap years and moon's orbit.
x = floor(3*c/4) - 12;
z = floor((8*c+5)/25) - 5;

% Epact.
e = mod(11*g+20+z-x,30);
if (e==25 &amp;&amp; g&gt;11 || e==24), e = e + 1; end

% Full moon.
n = 44 - e;
if n &lt; 21, n = n + 30; end

% Find a Sunday.
d = floor(5*y/4) - x - 10;

% Easter is a Sunday in March or April.
d = n + 7 - mod(d+n,7);
dn = datenum(y,3,d);

</pre><h4>References<a rel="nofollow" name="d5123200-4ce1-4de5-910c-cf77d13f9a21"></a></h4><p>[1] Donald E. Knuth, The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd edition), pp. 155-156, Addison-Wesley, 1997, ISBN 0-201-89683-4.</p><p>[2] Wikipedia, Primary article on Easter. <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Easter">&lt;http://en.wikipedia.org/wiki/Easter</a>&gt;</p><p>[3] Wikipedia, Computus, details on calculation of Easter. <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Computus">&lt;http://en.wikipedia.org/wiki/Computus</a>&gt;</p><p>[4] Wikipedia, Metonic cycle. <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Metonic_cycle">&lt;http://en.wikipedia.org/wiki/Metonic_cycle</a>&gt;</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/3AFxZnw3BlQ" height="1" width="1"/>]]></content:encoded>
         <category>History</category>
      </item>
      <item>
         <title>Time to Convert to Variant Subsystems</title>
         <link>http://feedproxy.google.com/~r/SethOnSimulink/~3/7VJkSl73KVY/</link>
         <description>If you are a user of Configurable Subsystems, it is time to start thinking about making the switch to Variant Systems. Simulink Variants provide increased functionality over Configurable Subsystems: They exist in two flavors: Model Variants and Subsystem Variants. They can be controlled programmatically via variables in the MATLAB workspace. They are in your model [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/seth/?p=1977</guid>
         <pubDate>Mon, 18 Mar 2013 17:00:05 +0000</pubDate>
         <content:encoded><![CDATA[<p>If you are a user of <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/slref/configurablesubsystem.html">Configurable Subsystems</a>, it is time to start thinking about making the switch to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/ecoder/variant-systems.html">Variant Systems</a>.</p>

<p>Simulink Variants provide increased functionality over Configurable Subsystems: 

<ul>
	<li>They exist in two flavors: <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/modelvariants.html">Model Variants</a> and <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/simulink/slref/variantsubsystem.html">Subsystem Variants</a>.</li>
	<li>They can be controlled programmatically via variables in the MATLAB workspace.</li>
	<li>They are in your model instead of a Simulink Library which simplifies model development.</li>
</ul>

Once you try the Simulink Variants, I guarantee you will immediately see their advantages and understand why we recommend moving away from Configurable Subsystems.</p> 

<p>Here are some tips to help you migrate.</p>

<p><strong>Upgrade Advisor</strong></p>

<p>In R2012b, the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/ug/consulting-the-model-advisor.html#btiimgy-1">Upgrade Advisor </a> includes a check titled <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/slref/simulink-checks_bq6d4aa-1.html#btkt8nb-1">Identify configurable subsystem blocks for converting to variant subsystem blocks</a>.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/upgradeAdvisor.png" alt="Upgrade Advisor"/></p>

<p>If you run the check and a configurable subsystem is found, the result will tell you that "These blocks can be upgraded to variant subsystems as they have better programmatic control and code generation capabilities."</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/checkResult.png" alt="Upgrade Advisor"/></p>

<p><strong>Context Menu</strong></p>

<p>If you right-click on a configurable subsystem (or any subsystem), you will see a new option to convert the subsystem to a variant.</p>

<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/seth/2013Q1/convertToVariant.png"><img src="http://blogs.mathworks.com/images/seth/2013Q1/convertToVariant_small.png" alt="Upgrade Advisor"/></a></p>

<p>A window will allow you to specify some details needed for the conversion.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/configureVariantConversion.png" alt="Converting to Variant"/></p>

<p>and a new model will pop up with your new block converted to a variant subsystem. Notice the different icon in the lower left corner of the block, it indicates that the variant subsystem is configured to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/releases/R2012b/simulink/ug/selecting-the-active-variant.html#bsk8ulq-1">override variant conditions</a> and behaves exactly like the original configurable subsystem.</p>

<p><img src="http://blogs.mathworks.com/images/seth/2013Q1/newVariant.png" alt="New Variant Subsystem"/></p>

<p><strong>Now it's your turn</strong></p>

<p>Are you ready to move to Variant Subsystems? Let us know by leaving a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/seth/?p=1977&#comment">comment here</a></p><img src="http://feeds.feedburner.com/~r/SethOnSimulink/~4/7VJkSl73KVY" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Challenge students with MATLAB practice on Cody</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/3r5Ud9Wu6_g/</link>
         <description>I’ve recently been talking with professors eager to use Cody in the classroom.  From these discussions, I’ve learned of seven great reasons to challenge your students with MATLAB practice problems in Cody: 1.       Great problems to draw on There are already over 900 ready-made MATLAB programming problems, in just the first year online.  Search for [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2159</guid>
         <pubDate>Mon, 18 Mar 2013 16:00:19 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>I’ve recently been talking with professors eager to use <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody">Cody</a> in the classroom.  From these discussions, I’ve learned of seven great reasons to challenge your students with MATLAB practice problems in <em><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody">Cody</a></em>:</em></p>
<p><strong style="font-size:13px;line-height:19px;">1.       </strong><strong style="font-size:13px;line-height:19px;">Great problems to draw on</strong></p>
<p>There are already over <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/?term=&amp;sort=created+asc">900 ready-made MATLAB programming problems</a>, in just the first year online.  Search for your subject matter of interest.  Check back often, as the Community area is growing rapidly.</p>
<p><strong style="font-size:13px;line-height:19px;">2.       </strong><strong style="font-size:13px;line-height:19px;">Fits into your workflow</strong></p>
<p>Navigate to Cody problems by hyperlink directly from your Learning Management System (LMS), HTML syllabus page or simply <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/problems/1-times-2-start-here">link directly into each Cody problem</a> in email to your students.</p>
<p><strong style="font-size:13px;line-height:19px;">3.       </strong><strong style="font-size:13px;line-height:19px;">Engaging for the learner</strong></p>
<p>As <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/videos/2012/01/27/cody-for-learning-matlab/#comment-2981">Jeff points out on the Community Blogs</a>, Cody has an addictive quality you can use to deepen student engagement.</p>
<p><strong style="font-size:13px;line-height:19px;">4.       </strong><strong style="font-size:13px;line-height:19px;">Can use online and/or with MATLAB</strong></p>
<p>Copy the Cody test suite into desktop MATLAB.  Let students write their Cody function with the full power of MATLAB, then paste their answer back into Cody to verify correctness.  For example, the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/problems/1-times-2-start-here">Times 2 problem</a> could be solved in MATLAB as follows:</p>
<p>testsuite.m:<br />
<code>%%<br />
assert(isequal(times2(1),2));<br />
%%<br />
assert(isequal(times2(11),22));<br />
%%<br />
assert(isequal(times2(-3),-6));<br />
%%<br />
assert(isequal(times2(29),58));<br />
</code></p>
<p>times2.m:<br />
<code>function y = times2(x)<br />
% Modify the line below so that the output y is twice the incoming value x<br />
y = 2*x;<br />
% After you fix the code, press the "Submit" button, and you're on your way.<br />
end<br />
</code></p>
<p>Running testsuite.m confirms the function passes each test case, hence success.</p>
<p><strong style="font-size:13px;line-height:19px;">5.       </strong><strong style="font-size:13px;line-height:19px;">Create your own problems</strong></p>
<p>Try <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/problems/new">creating a Cody problem</a> for yourself.</p>
<p><strong style="font-size:13px;line-height:19px;">6.       </strong><strong style="font-size:13px;line-height:19px;">Experiment to see how people try to solve your problems</strong></p>
<p>Draw on the MATLAB Central community to confirm your Cody problem challenges exactly the skills you want students to learn.  We offer you a large population of MATLAB experts eager to try out the latest MATLAB programming puzzle.  Use the Solution Map to see outlier attempts, to better understand how your students could react before offering the practice problem in class.</p>
<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/6.png"><img class="alignnone size-full wp-image-2173" title="6" src="http://blogs.mathworks.com/community/files/6.png" alt="" width="669" height="476"/></a></p>
<p><strong style="font-size:13px;line-height:19px;">7.       </strong><strong style="font-size:13px;line-height:19px;">Identify learning gaps</strong></p>
<p>Using the solution map, keep an eye across multiple problems from the point in time you’ve offered in class.  Compare these across problems to identify subject matter areas meriting more lecture coverage.  For example,</p>
<p><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/problems/7-column-removal">Problem 7: Column Removal</a><br />
<a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/71.png"><img class="alignnone size-full wp-image-2172" title="7" src="http://blogs.mathworks.com/community/files/71.png" alt="" width="660" height="179"/></a><br />
shows a cluster of incorrect attempts worth exploring.  You’ll quickly see which topics need follow-up coverage in class.</p>
<p><em>I’ve also prepared a five minute <a rel="nofollow" target="_blank" href="http://www.mathworks.com/videos/challenge-students-with-matlab-practice-on-cody-77142.html">video</a> to demonstrate the above points.  Please let me know how you’ve found Cody helpful.</em></p>
<p><em>Try Cody for yourself at <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody">www.mathworks.com/matlabcentral/cody</a>, and get your students addicted to learning in MATLAB.</em></p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/3r5Ud9Wu6_g" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Using the MATLAB Unit Testing Infrastructure for Grading Assignments</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/nkzH_P-RoGo/</link>
         <description>Steven Lord, Andy Campbell, and David Hruska are members of the Quality Engineering group at MathWorks who are guest blogging today to introduce a new feature in R2013a, the MATLAB unit testing infrastructure. There are several submissions on the MATLAB Central File Exchange related to unit testing of MATLAB code. Blogger Steve Eddins wrote one [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=649</guid>
         <pubDate>Thu, 14 Mar 2013 15:18:23 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Steven Lord, Andy Campbell, and David Hruska are members of the Quality Engineering group at MathWorks who are guest blogging today to introduce a new feature in R2013a, the MATLAB unit testing infrastructure. There are several submissions on the MATLAB Central File Exchange related to unit testing of <tt>MATLAB</tt> code. Blogger Steve Eddins wrote one highly rated <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework">example</a> back in 2009. In release R2013a, MathWorks included in <tt>MATLAB</tt> itself a <tt>MATLAB</tt> implementation of the industry-standard xUnit testing framework.</p><p>If you're not a software developer, you may be wondering if this feature will be of any use to you. In this post, we will describe one way someone who may not consider themselves a software developer may be able to take advantage of this framework using the example of a professor grading students' homework submissions. That's not to say that the developers in the audience should move on to the next post; you can use these tools to test your own code just like a professor can use them to test code written by his or her students.</p><p>There is a great deal of functionality in this feature that we will not show here. For more information we refer you to the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab-unit-test-framework.html">MATLAB Unit Testing Framework</a> documentation.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#454b2d47-cbbb-48bf-b2ba-50c3891d7f7a">Background</a></li><li><a rel="nofollow" href="#a7a02684-3047-424b-a927-3b218f015807">Problem Statement</a></li><li><a rel="nofollow" href="#eeac7ca5-eb4b-4028-9a87-c969cd27c754">Basic Unit Test</a></li><li><a rel="nofollow" href="#23717901-ce74-47ed-9564-08b52b69c2a4">Running a Test</a></li><li><a rel="nofollow" href="#8cf80ad8-6ac6-4606-951c-441a8ba5bcd7">Test that F(0) Equals 1</a></li><li><a rel="nofollow" href="#15df7917-0f94-4a3f-b915-552df373e33f">Test that F(pi) Throws an Error</a></li><li><a rel="nofollow" href="#3ad5bde5-93a3-4204-b976-8a60edad5fc6">Basic Test for Students, Advanced Tests for Instructor</a></li><li><a rel="nofollow" href="#b8d2ed9f-3356-4308-bc9b-b269f74b93bd">Conclusion</a></li></ul></div><h4>Background<a rel="nofollow" name="454b2d47-cbbb-48bf-b2ba-50c3891d7f7a"></a></h4><p>In order to use this feature, you should be aware of how to define simple <tt>MATLAB</tt> classes in <i>classdef</i> files, how to define a class that inherits from another, and how to specify attributes for methods and properties of those classes. The <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/object-oriented-programming.html">object-oriented programming</a> documentation describes these capabilities.</p><h4>Problem Statement<a rel="nofollow" name="a7a02684-3047-424b-a927-3b218f015807"></a></h4><p>As a professor in an introductory programming class, you want your students to write a program to compute Fibonacci numbers. The exact problem statement you give the students is:</p><pre>Create a function "fib" that accepts a nonnegative integer n and returns
the nth Fibonacci number. The Fibonacci numbers are generated by this
relationship:</pre><pre>F(0) = 1
F(1) = 1
F(n) = F(n-1) + F(n-2) for integer n &gt; 1</pre><pre>Your function should throw an error if n is not a nonnegative integer.</pre><h4>Basic Unit Test<a rel="nofollow" name="eeac7ca5-eb4b-4028-9a87-c969cd27c754"></a></h4><p>The most basic <tt>MATLAB</tt> unit test is a <tt>MATLAB</tt> <i>classdef</i> class file that inherits from the <tt>matlab.unittest.TestCase</tt> class. Throughout the rest of this post we will add additional pieces to this basic framework to increase the capability of this test and will change its name to reflect its increased functionality.</p><pre class="codeinput">dbtype <span class="string">basicTest.m</span>
</pre><pre class="codeoutput">
1     classdef basicTest &lt; matlab.unittest.TestCase
2         
3     end
</pre><pre class="codeinput">test = basicTest
</pre><pre class="codeoutput">test = 
  basicTest with no properties.
</pre><h4>Running a Test<a rel="nofollow" name="23717901-ce74-47ed-9564-08b52b69c2a4"></a></h4><p>To run the test, we can simply pass <tt>test</tt> to the <tt>run</tt> function. There are more advanced ways that make it easier to run a group of tests, but for our purposes (checking one student's answer at a time) this will be sufficient. When you move to checking multiple students' answers at a time, you can use <tt>run</tt> inside a <tt>for</tt> loop.</p><p>Since <tt>basicTest</tt> doesn't actually validate the output from the student's function, it doesn't take very long to execute.</p><pre class="codeinput">results = run(test)
</pre><pre class="codeoutput">results = 
  0x0 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   0 Passed, 0 Failed, 0 Incomplete.
   0 seconds testing time.
</pre><p>Let's say that a student named Thomas submitted a function <tt>fib.m</tt> as his solution to this assignment. Thomas's code is stored in a sub-folder named <tt>thomas</tt>. To set up our test to check Thomas's answer, we add the folder holding his code to the path.</p><pre class="codeinput">addpath(<span class="string">'thomas'</span>);
dbtype <span class="string">fib.m</span>
</pre><pre class="codeoutput">
1     function y = fib(n)
2     if n &lt;= 1
3         y = 1;
4     else
5         y = fib(n-1)+fib(n-2);
6     end

</pre><h4>Test that F(0) Equals 1<a rel="nofollow" name="8cf80ad8-6ac6-4606-951c-441a8ba5bcd7"></a></h4><p>The <tt>basicTest</tt> is a valid test class, and we can run it, but it doesn't actually perform any validation of the student's test file. The methods that will perform that validation need to be written in a <i>methods</i> block that has the attribute <tt>Test</tt> specified.</p><p>The <tt>matlab.unittest.TestCase</tt> class includes qualification methods that you can use to test various qualities of the results returned by the student files. The qualification method that you will likely use most frequently is the <tt>verifyEqual</tt> method, which passes if the two values you pass into it are equal and reports a test failure if they are not.</p><p>The <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/matlab.unittest.testcaseclass.html">documentation</a> for the <tt>matlab.unittest.TestCase</tt> class lists many other qualification methods that you can use to perform other types of validation, including testing the data type and size of the results; matching a string result to an expected string; testing that a given section of code throws a specific errors or issues a specific warning; and many more.</p><p>This simple test builds upon <tt>generalTest</tt> by adding a test method that checks that the student's function returns the value 1 when called with the input 0.</p><pre class="codeinput">dbtype <span class="string">simpleTest.m</span>
</pre><pre class="codeoutput">
1     classdef simpleTest &lt; matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8         end
9     end
</pre><p>Thomas's solution to the assignment satisfies this basic check. We can use the results returned from <tt>run</tt> to display the percentage of the tests that pass.</p><pre class="codeinput">results = run(simpleTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);
</pre><pre class="codeoutput">Running simpleTest
.
Done simpleTest
__________

results = 
  TestResult with properties:

          Name: 'simpleTest/fibonacciOfZeroShouldBeOne'
        Passed: 1
        Failed: 0
    Incomplete: 0
      Duration: 0.0112
Totals:
   1 Passed, 0 Failed, 0 Incomplete.
   0.011168 seconds testing time.
100% Passed.
</pre><h4>Test that F(pi) Throws an Error<a rel="nofollow" name="15df7917-0f94-4a3f-b915-552df373e33f"></a></h4><p>Now that we have a basic positive test in place we can add in a test that checks the behavior of the student's function when passed a non-integer value (like <tt>n = pi</tt>) as input. The assignment stated that when called with a non-integer value, the student's function should error. Since the assignment doesn't require a specific error to be thrown, the test passes as long as <tt>fib(pi)</tt> throws any exception.</p><pre class="codeinput">dbtype <span class="string">errorCaseTest.m</span>
</pre><pre class="codeoutput">
1     classdef errorCaseTest &lt; matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8             function fibonacciOfNonintegerShouldError(testCase)
9                 testCase.verifyError(@()fib(pi), ?MException);
10            end
11        end
12    end
</pre><p>Thomas forgot to include a check for a non-integer valued input in his function, so our test should indicate that by reporting a failure.</p><pre class="codeinput">results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);
</pre><pre class="codeoutput">Running errorCaseTest
.
================================================================================
Verification failed in errorCaseTest/fibonacciOfNonintegerShouldError.

    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyError failed.
    --&gt; The function did not throw any exception.
        
        Expected Exception Type:
            MException
    
    Evaluated Function:
            @()fib(pi)

    ------------------
    Stack Information:
    ------------------
    In C:&#92;Program Files&#92;MATLAB&#92;R2013a&#92;toolbox&#92;matlab&#92;testframework&#92;+matlab&#92;+unittest&#92;+qualifications&#92;Verifiable.m (Verifiable.verifyError) at 637
    In H:&#92;Documents&#92;LOREN&#92;MyJob&#92;Art of MATLAB&#92;errorCaseTest.m (errorCaseTest.fibonacciOfNonintegerShouldError) at 9
================================================================================
.
Done errorCaseTest
__________

Failure Summary:

     Name                                            Failed  Incomplete  Reason(s)
    =============================================================================================
     errorCaseTest/fibonacciOfNonintegerShouldError    X                 Failed by verification.
    
results = 
  1x2 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   1 Passed, 1 Failed, 0 Incomplete.
   0.026224 seconds testing time.
50% Passed.
</pre><p>Another student, Benjamin, checked for a non-integer value in his code as you can see on line 2.</p><pre class="codeinput">rmpath(<span class="string">'thomas'</span>);
addpath(<span class="string">'benjamin'</span>);
dbtype <span class="string">fib.m</span>
</pre><pre class="codeoutput">
1     function y = fib(n)
2     if (n ~= round(n)) || n &lt; 0
3         error('N is not an integer!');
4     elseif n == 0 || n == 1
5         y = 1;
6     else
7         y = fib(n-1)+fib(n-2);
8     end
</pre><p>Benjamin's code passed both the test implemented in the <tt>fibonacciOfZeroShouldBeOne</tt> method (which we copied into <tt>errorCaseTest</tt> from <tt>simpleTest</tt>) and the new test case implemented in the <tt>fibonacciOfNonintegerShouldError</tt> method.</p><pre class="codeinput">results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);
</pre><pre class="codeoutput">Running errorCaseTest
..
Done errorCaseTest
__________

results = 
  1x2 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   2 Passed, 0 Failed, 0 Incomplete.
   0.010132 seconds testing time.
100% Passed.
</pre><h4>Basic Test for Students, Advanced Tests for Instructor<a rel="nofollow" name="3ad5bde5-93a3-4204-b976-8a60edad5fc6"></a></h4><p>The problem statement given earlier in this post is a plain text description of the homework assignment we assigned to the students. We can also state the problem for the students in code (if they're using release R2013a or later) by giving them a test file they can run just like <tt>simpleTest</tt> or <tt>errorCaseTest</tt>. They can directly use this "requirement test" to ensure their functions satisfy the requirements of the assignment.</p><pre class="codeinput">dbtype <span class="string">studentTest.m</span>
</pre><pre class="codeoutput">
1     classdef studentTest &lt; matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8             function fibonacciOfNonintegerShouldError(testCase)
9                 testCase.verifyError(@()fib(pi), ?MException);
10            end
11        end
12    end
</pre><p>In order for the student's code to pass the assignment, it will need to pass the test cases given in the <tt>studentTest</tt> unit test. However, we don't want to use <tt>studentTest</tt> as the <i>only</i> check of the student's code. If we did, the student could write their function to cover only the test cases in the student test file.</p><p>We could solve this problem by having two separate test files, one containing the student test cases and one containing additional test cases the instructor uses in the grading process. Can we avoid having to run both test files manually or duplicating the code from the student test cases in the instructor test? Yes!</p><p>To do so, we write an instructor test file to incorporate, through inheritance, the student test file. We can then add additional test cases to the instructor test file. When we run this test it should run three test cases; two inherited from <tt>studentTest</tt>, <tt>fibonacciOfZeroShouldBeOne</tt> and <tt>fibonacciOfNonintegerShouldError</tt>, and one from <tt>instructorTest</tt> itself, <tt>fibonacciOf5</tt>.</p><pre class="codeinput">dbtype <span class="string">instructorTest.m</span>
</pre><pre class="codeoutput">
1     classdef instructorTest &lt; studentTest
2         % Because the student test file is a matlab.unittest.TestCase and
3         % instructorTest inherits from it, instructorTest is also a
4         % matlab.unittest.TestCase.
5         
6         methods(Test)
7             function fibonacciOf5(testCase)
8                 % Evaluate the student's function for n = 5
9                 result = fib(5);
10                testCase.verifyEqual(result, 8, 'Fibonacci(5) should be 8');
11            end
12        end
13    end
</pre><p>Let's look at Eric's test file that passes the <tt>studentTestFile</tt> test, but in which he completely forgot to implement the <tt>F(n) = F(n-1)+F(n-2)</tt> recursion step.</p><pre class="codeinput">rmpath(<span class="string">'benjamin'</span>);
addpath(<span class="string">'eric'</span>);
dbtype <span class="string">fib.m</span>
</pre><pre class="codeoutput">
1     function y = fib(n)
2     if (n ~= round(n)) || n &lt; 0
3         error('N is not an integer!');
4     end
5     y = 1;

</pre><p>It should pass the student unit test.</p><pre class="codeinput">results = run(studentTest);
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);
</pre><pre class="codeoutput">Running studentTest
..
Done studentTest
__________

100% Passed.
</pre><p>It does NOT pass the instructor unit test because it fails one of the test cases.</p><pre class="codeinput">results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);
</pre><pre class="codeoutput">Running instructorTest
..
================================================================================
Verification failed in instructorTest/fibonacciOf5.

    ----------------
    Test Diagnostic:
    ----------------
    Fibonacci(5) should be 8

    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyEqual failed.
    --&gt; NumericComparator failed.
        --&gt; The values are not equal using "isequaln".
    
    Actual Value:
             1
    Expected Value:
             8

    ------------------
    Stack Information:
    ------------------
    In C:&#92;Program Files&#92;MATLAB&#92;R2013a&#92;toolbox&#92;matlab&#92;testframework&#92;+matlab&#92;+unittest&#92;+qualifications&#92;Verifiable.m (Verifiable.verifyEqual) at 411
    In H:&#92;Documents&#92;LOREN&#92;MyJob&#92;Art of MATLAB&#92;instructorTest.m (instructorTest.fibonacciOf5) at 10
================================================================================
.
Done instructorTest
__________

Failure Summary:

     Name                         Failed  Incomplete  Reason(s)
    ==========================================================================
     instructorTest/fibonacciOf5    X                 Failed by verification.
    
results = 
  1x3 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   2 Passed, 1 Failed, 0 Incomplete.
   0.028906 seconds testing time.
66.6667% Passed.
</pre><p>Benjamin, whose code we tested above, wrote a correct solution to the homework problem.</p><pre class="codeinput">rmpath(<span class="string">'eric'</span>);
addpath(<span class="string">'benjamin'</span>);

results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), <span class="string">'% Passed.'</span>]);

rmpath(<span class="string">'benjamin'</span>);
</pre><pre class="codeoutput">Running instructorTest
...
Done instructorTest
__________

results = 
  1x3 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   3 Passed, 0 Failed, 0 Incomplete.
   0.015946 seconds testing time.
100% Passed.
</pre><h4>Conclusion<a rel="nofollow" name="b8d2ed9f-3356-4308-bc9b-b269f74b93bd"></a></h4><p>In this post, we showed you the basics of using the new MATLAB unit testing infrastructure using homework grading as a use case.</p><p>We checked that the student's code worked (by returning the correct answer) for one valid value and worked (by throwing an error) for one invalid value. We also showed how you can use this infrastructure to provide an aid/check for the students that you can also use as part of your grading.</p><p>We hope this brief introduction to the unit testing framework has shown you how you can make use of this feature even if you don't consider yourself a software developer. Let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using matlab.unittest, let us know about your experiences <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=649#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/nkzH_P-RoGo" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Persistent variables in MATLAB</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/vEcPRmT-rr0/</link>
         <description>There are situations where you want MATLAB to remember the value of a variable from one call of a function to another call of that function. We show to use a persistent value to accomplish this. This approach is convenient when calling the same function from several different places, or in callbacks, such as when [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1059</guid>
         <pubDate>Thu, 14 Mar 2013 13:59:23 +0000</pubDate>
         <content:encoded><![CDATA[There are situations where you want MATLAB to remember the value of a variable from one call of a function to another call of that function.  We show to use a persistent value to accomplish this.  This approach is convenient when calling the same function from several different places, or in callbacks, such as when coding an app or a timer.

<p>
<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate301" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div><img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/vEcPRmT-rr0" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>MATLAB software testing tools – old and new (R2013a!)</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/6qwsaNJpkOE/</link>
         <description>R2013a, the latest semi-annual MathWorks product release, just went live. One of the significant new capabilities in the MATLAB release is a new unit test framework (overview video, documentation). I am very happy to see this!Long-time blog readers might be wondering, though, what about MATLAB xUnit? This is a unit test framework that I created [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=805</guid>
         <pubDate>Tue, 12 Mar 2013 18:45:14 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>R2013a, the latest <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/new_products/release_model.html">semi-annual MathWorks product release</a>, just went live. One of the significant new capabilities in the MATLAB release is a new unit test framework (<a rel="nofollow" target="_blank" href="http://www.mathworks.com/videos/matlab-unit-testing-framework-74975.html">overview video</a>, <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab-unit-test-framework.html">documentation</a>). I am very happy to see this!</p><p>Long-time blog readers might be wondering, though, what about MATLAB xUnit? This is a unit test framework that I created and put on the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework">File Exchange</a>. I first wrote about it in this space in <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2009/02/03/mtest-a-unit-test-harness-for-matlab-code/">2009</a>. It is my second most popular File Exchange contribution (over 200 downloads in the last 30 days).</p><p>Today I want to recap how MATLAB xUnit came to be, explain what will probably happen to it, and convince its users to give the new "official" unit test framework in R2013a a try.</p><p>I learned to write unit tests when I came to MathWorks in 1993 as a new software developer. I've used several generations of test frameworks created for internal use here. Until recently, our internal testing machinery was tightly coupled to the entire system we used to build, test, and release our products, and so it was impractical to use it for small projects. This became an issue for me sometime around 2002-2003, as I was working on the first edition of <a rel="nofollow" target="_blank" href="http://imageprocessingplace.com/DIPUM-2E/dipum2e_main_page.htm"><i>Digital Image Processing Using MATLAB</i></a>. As the "software guy" among the three coauthors, I was responsible for overseeing the MATLAB functions in the book, including making sure that everything was working OK. So I wrote a simple test harness that exercised the book's examples and some of the functions.</p><p>Later, the MATLAB R2008a release included the new generation of object-oriented language features. I was interested in learning more about it. Coincidentally, I had just read Kent Beck's <i>Test-Driven Development</i>, which included a case study on using test-driven development methods to create an xUnit-style test harness. I decided that would be an excellent project with which to learn about test-driven development as well as the R2008a MATLAB language changes. (With the wisdom of hindsight, I have to say here that I don't actually recommend learning test-driven development by using test-driven development to develop a test harness. It hurt my brain too much.)</p><p>Anyway, sometime in the spring on 2008 I had something pretty basic working. At about that time, <a rel="nofollow" target="_blank" href="http://third-bit.com/">Greg Wilson</a> (original creator of <a rel="nofollow" target="_blank" href="http://software-carpentry.org/index.html">Software Carpentry</a>) visited MathWorks to give a talk about his edited book, <i>Beautiful Code</i>. I met Greg then, and we talked about the needs of MATLAB scientific users. Greg encouraged me to turn my fledgling tool into something real. He also invited me to write up something for the IEEE magazine, <i>Computing in Science and Engineering</i>. That became the article <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/steve/2010/Automated%20Software%20Testing%20for%20MATLAB%20(2009).pdf">"Automated Software Testing for MATLAB"</a>, published in the November/December 2009 issue.</p><p>The MATLAB xUnit package raised the visibility of unit testing tools in MATLAB, and its popularity helped make the case for putting something like it in MATLAB. At the same time, our testing tools team was looking to modernize our testing infrastructure. They wanted to take advantage of the latest test framework design principles, and they wanted to decouple the testing machinery from the rest of our complex systems for building and releasing products. So an idea was born: let's make a test framework that can stand on its own, that can test our own software, that can test customer code, and that we can ship in MATLAB!</p><p>And now, here it finally is!</p><p>Here are a few examples that I've taken from the documentation to illustrate. The first example shows how to write a couple of tests for a hypothetical function called <tt>quadraticSolver</tt>.</p><pre>classdef SolverTest &lt; matlab.unittest.TestCase
    % SolverTest tests solutions to the quadratic equation
    % a*x^2 + b*x + c = 0</pre><pre>    methods (Test)
        function testRealSolution(testCase)
            actSolution = quadraticSolver(1,-3,2);
            expSolution = [2,1];
            testCase.verifyEqual(actSolution,expSolution);
        end
        function testImaginarySolution(testCase)
            actSolution = quadraticSolver(1,2,10);
            expSolution = [-1+3i, -1-3i];
            testCase.verifyEqual(actSolution,expSolution);
        end
    end</pre><pre>end</pre><p>If you need to define setup and teardown methods for your test cases, here's how you do it. (I've just shown the relevant portion of the entire test file.)</p><pre>properties
    TestFigure
end</pre><pre>methods(TestMethodSetup)
    function createFigure(testCase)
        %comment
        testCase.TestFigure = figure;
    end
end</pre><pre>methods(TestMethodTeardown)
    function closeFigure(testCase)
        close(testCase.TestFigure);
    end
end</pre><p>Someone asked me just this week about enhancing MATLAB xUnit to provide for setup and teardown methods that get executed just once for all the methods in a test file, instead of being executed once for every individual test method. MATLAB xUnit does not have this capability, but the new unit test framework in R2013a does. A class-level setup method is identified by using the <tt>TestClassSetup</tt> method attribute, like this:</p><pre>methods (TestClassSetup)
    function doSomethingBeforeAllTestMethodsAreExecuted(testCase)
        disp('Hi, Mom!')
    end
end</pre><p>There are lots of new capabilities in this framework. A little birdie told me that more information about <tt>matlab.unittest</tt> may appear pretty soon in <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren">Loren's blog</a>. For now, though, I'd like to point you to the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/videos/matlab-unit-testing-framework-74975.html">overview video</a> and to the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/matlab-unit-test-framework.html">documentation</a>.</p><p>That brings me back to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework">MATLAB xUnit</a> and its fate. Well, this little package is entering its "retirement phase." I imagine it will remain on the File Exchange for quite a while because it can take a long time for the user community to adopt a new release, and also because there's a lot of customer-written code out there that uses it. However, I do not plan to work on it anymore. Our testing tools team is an excellent group of engineers, and they can move matlab.unittest forward better and faster than I could ever do with my little side project.</p><p>So, if you're interested in unit testing and you get your hands on MATLAB R2013a, please give it a try.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/6qwsaNJpkOE" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Major New Release at Chebfun – Two Dimensional Capabilities</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/OR8K3v-7o9U/</link>
         <description>Perhaps you've read about Chebfun before here or on Cleve''s blog. Chebfun allows you to do numerical computing with functions and not simply numbers. If not, you might want to investigate. If so, you may be very interested in new capabilities available.ContentsMajor New CapabilityMany ExamplesMajor New CapabilityJust recently, the Chebfun team released a major new [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=643</guid>
         <pubDate>Wed, 06 Mar 2013 14:25:46 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Perhaps you've read about <a rel="nofollow" target="_blank" href="http://www2.maths.ox.ac.uk/chebfun/">Chebfun</a> before <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/2011/06/21/update-on-the-chebfun-project/">here</a> or on <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/cleve/2012/10/01/chebfun-numerical-computing-with-functions/">Cleve''s blog</a>.  Chebfun allows you to do numerical computing with functions and not simply numbers.  If not, you might want to investigate. If so, you may be very interested in new capabilities available.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#2cc21f9d-c30a-4db0-a793-5f05df419544">Major New Capability</a></li><li><a rel="nofollow" href="#ad6aad99-6990-4336-b8ee-1f335655af29">Many Examples</a></li></ul></div><h4>Major New Capability<a rel="nofollow" name="2cc21f9d-c30a-4db0-a793-5f05df419544"></a></h4><p>Just recently, the Chebfun team released a major new capability on their site.  While Chebfun is extremely useful, it was restricted to solving problems in one dimension.  Now you may solve problems with two independent variables using <a rel="nofollow" target="_blank" href="http://www2.maths.ox.ac.uk/chebfun/chebfun2/">Chebfun2</a>! As before, their website includes code you can freely download and many interesting examples.  The examples are well documented and easy to learn from.  I will soon have time to explore Chebfun2 because of an irrational amount of airline time.</p><p>I also love how easy it is to install - you can do it from MATLAB. They kindly post the code right on the website so you can paste it into your running session.</p><h4>Many Examples<a rel="nofollow" name="ad6aad99-6990-4336-b8ee-1f335655af29"></a></h4><p>They have many examples included in the software, and posted on their web site, using the <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/publish.html"><tt>publish</tt></a> command in MATLAB.  The high-level examples are organized into these categories:</p><div><ol><li>Approximation</li><li>Complex Analysis</li><li>Geometry</li><li>Optimization</li><li>Statistics</li><li>Rootfinding</li><li>Vector Calculus</li><li>Fun !</li></ol></div><p>I hope with this breadth of examples, you are able to find ones interesting or relevant (or both) to you.  Once you've gotten a chance to try out Chebfun2, I'd love to hear about your experiences.  Post them <a rel="nofollow">here</a> to share with us.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/OR8K3v-7o9U" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Adding UICONTROLS to MATLAB without GUIDE for simple interactive figures</title>
         <link>http://feedproxy.google.com/~r/DougsMatlabVideoTutorials/~3/RWZmFZ4SOAw/</link>
         <description>There are often small tweaks to functionality that you would like for a figure in MATLAB. This video shows how to add a button to a figure that will allow you to toggle the units of a y axes between inches and centimeters.</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/videos/?p=1052</guid>
         <pubDate>Tue, 05 Mar 2013 15:42:07 +0000</pubDate>
         <content:encoded><![CDATA[There are often small tweaks to functionality that you would like for a figure in MATLAB.  This video shows how to add a button to a figure that will allow you to toggle the units of a y axes between inches and centimeters.
<p>
<p>
<div class="video" style="width:660;height:410;">
       
       
              <div id="videoalternate300" style="width:660px;height:410px;">
                     <a rel="nofollow" target="_blank" href="http://www.adobe.com/go/getflashplayer">


                     <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
              </a>
              </div>
 </div><img src="http://feeds.feedburner.com/~r/DougsMatlabVideoTutorials/~4/RWZmFZ4SOAw" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Wilkinson’s Polynomials</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/GGSOrzFNcs4/</link>
         <description>Wilkinson's polynomials are a family of polynmials with deceptively sensitive roots.Contents$P_n$$P_{20}$CoefficientsSymbolic formDouble precisionDouble precision rootsWilkinson's perturbationSensitivityNote added March 10, 2013.$P_n$The Wilkinson polynomial of degree $n$ has as roots the integers from $1$ to $n$.$$ P_n(x) = &amp;#92;prod_{k=1}^{n} (x-k) $$$P_{20}$The usual value of $n$ is 20.format compact n = 20 syms x P20 = prod(x-(1:n)) n [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=538</guid>
         <pubDate>Mon, 04 Mar 2013 17:00:17 +0000</pubDate>
         <content:encoded><![CDATA[<style type="text/css">

h1 {font-size:18pt;}
h2.titlebg {font-size:13pt;}
h3 {color:#4A4F55;padding:0px;margin:5px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:11pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}
h4 {color:#4A4F55;padding:0px;margin:0px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:10pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}

p {padding:0px;margin:0px 0px 20px;}
img {padding:0px;margin:0px 0px 20px;border:none;}
p img, pre img, tt img, li img {margin-bottom:0px;}

ul {padding:0px;margin:0px 0px 20px 23px;list-style:square;}
ul li {padding:0px;margin:0px 0px 7px 0px;background:none;}
ul li ul {padding:5px 0px 0px;margin:0px 0px 7px 23px;}
ul li ol li {list-style:decimal;}
ol {padding:0px;margin:0px 0px 20px 0px;list-style:decimal;}
ol li {padding:0px;margin:0px 0px 7px 23px;list-style-type:decimal;}
ol li ol {padding:5px 0px 0px;margin:0px 0px 7px 0px;}
ol li ol li {list-style-type:lower-alpha;}
ol li ul {padding-top:7px;}
ol li ul li {list-style:square;}

pre, tt, code {font-size:12px;}
pre {margin:0px 0px 20px;}
pre.error {color:red;}
pre.codeinput {padding:10px;border:1px solid #d3d3d3;background:#f7f7f7;}
pre.codeoutput {padding:10px 11px;margin:0px 0px 20px;color:#4c4c4c;}

 _filtered {width:100%;}

span.keyword {color:#0000FF;}
span.comment {color:#228B22;}
span.string {color:#A020F0;}
span.untermstring {color:#B20000;}
span.syscmd {color:#B28C00;}

.footer {width:auto;padding:10px 0px;margin:25px 0px 0px;border-top:1px dotted #878787;font-size:0.8em;line-height:140%;font-style:italic;color:#878787;text-align:left;float:none;}
.footer p {margin:0px;}

</style><div class="content"><p>Wilkinson's polynomials are a family of polynmials with deceptively sensitive roots.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#c06781ed-5c04-4bc2-a995-a97a9375e1a8">$P_n$</a></li><li><a rel="nofollow" href="#0ef11e99-e8c3-4bcf-9cbc-1060cf7e1ba7">$P_{20}$</a></li><li><a rel="nofollow" href="#08c9a106-718c-4073-9824-4cfe53418dd5">Coefficients</a></li><li><a rel="nofollow" href="#ae75acb0-6dc5-4c82-923b-daa852d4ec51">Symbolic form</a></li><li><a rel="nofollow" href="#ebaccbdf-d4f0-4adc-bd87-05436ba95bfc">Double precision</a></li><li><a rel="nofollow" href="#88810d87-ef68-452f-8fb5-aecb7e711501">Double precision roots</a></li><li><a rel="nofollow" href="#4e933ac9-12f6-4685-af5a-d59152175246">Wilkinson's perturbation</a></li><li><a rel="nofollow" href="#aeb2589c-c6bb-44c1-8ea7-73c838dbf237">Sensitivity</a></li><li><a rel="nofollow" href="#02259bc3-4e57-4579-9790-3f23b2535e68">Note added March 10, 2013.</a></li></ul></div><h4>$P_n$<a rel="nofollow" name="c06781ed-5c04-4bc2-a995-a97a9375e1a8"></a></h4><p>The Wilkinson polynomial of degree $n$ has as roots the integers from $1$ to $n$.</p><p>$$ P_n(x) = &#92;prod_{k=1}^{n} (x-k) $$</p><h4>$P_{20}$<a rel="nofollow" name="0ef11e99-e8c3-4bcf-9cbc-1060cf7e1ba7"></a></h4><p>The usual value of $n$ is 20.</p><pre class="codeinput">format <span class="string">compact</span>
n = 20
syms <span class="string">x</span>
P20 = prod(x-(1:n))
</pre><pre class="codeoutput">n =
    20
P20 =
(x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5)*(x - 6)*(x - 7)*(x - 8)*(x - 9)*(x - 10)*(x - 11)*(x - 12)*(x - 13)*(x - 14)*(x - 15)*(x - 16)*(x - 17)*(x - 18)*(x - 19)*(x - 20)
</pre><p>Expressed in this form, the polynomial is well behaved.</p><h4>Coefficients<a rel="nofollow" name="08c9a106-718c-4073-9824-4cfe53418dd5"></a></h4><p>It gets interesting when $P_n(x)$ is expanded in the monomial basis, $&#92;{x^j&#92;}$.</p><pre class="codeinput">P = expand(P20)
</pre><pre class="codeoutput">P =
x^20 - 210*x^19 + 20615*x^18 - 1256850*x^17 + 53327946*x^16 - 1672280820*x^15 + 40171771630*x^14 - 756111184500*x^13 + 11310276995381*x^12 - 135585182899530*x^11 + 1307535010540395*x^10 - 10142299865511450*x^9 + 63030812099294896*x^8 - 311333643161390640*x^7 + 1206647803780373360*x^6 - 3599979517947607200*x^5 + 8037811822645051776*x^4 - 12870931245150988800*x^3 + 13803759753640704000*x^2 - 8752948036761600000*x + 2432902008176640000
</pre><p>The coefficients are huge.  The constant term is $20!$, and that's not even the largest coefficient.</p><pre class="codeinput">C = flipud(coeffs(P)')
</pre><pre class="codeoutput">C =
                     1
                  -210
                 20615
              -1256850
              53327946
           -1672280820
           40171771630
         -756111184500
        11310276995381
      -135585182899530
      1307535010540395
    -10142299865511450
     63030812099294896
   -311333643161390640
   1206647803780373360
  -3599979517947607200
   8037811822645051776
 -12870931245150988800
  13803759753640704000
  -8752948036761600000
   2432902008176640000
</pre><h4>Symbolic form<a rel="nofollow" name="ae75acb0-6dc5-4c82-923b-daa852d4ec51"></a></h4><p>Let's have the Symbolic Toolbox generate LaTeX and cut and paste the result into the source for the blog.</p><pre class="codeinput">L = latex(P);
<span class="comment">% edit(L)</span>
</pre><p>$$ x^{20} - 210&#92;, x^{19} + 20615&#92;, x^{18} &#92;&#92;
- 1256850&#92;, x^{17} + 53327946&#92;, x^{16} - 1672280820&#92;, x^{15} &#92;&#92;
+ 40171771630&#92;, x^{14} - 756111184500&#92;, x^{13} + 11310276995381&#92;, x^{12} &#92;&#92;
- 135585182899530&#92;, x^{11} + 1307535010540395&#92;, x^{10} - 10142299865511450&#92;, x^9 &#92;&#92;
+ 63030812099294896&#92;, x^8 - 311333643161390640&#92;, x^7 + 1206647803780373360&#92;, x^6 &#92;&#92;
- 3599979517947607200&#92;, x^5 + 8037811822645051776&#92;, x^4 - 12870931245150988800&#92;, x^3 &#92;&#92;
+ 13803759753640704000&#92;, x^2 - 8752948036761600000&#92;, x + 2432902008176640000 $$</p><p>With the monomial basis the Wilkinson polynomial does not look so innocent. The spacing between the roots is tiny relative to these coefficients. But the toolbox can easily find the roots $1$ to $20$ with no error.</p><pre class="codeinput">Z = sort(solve(P))'
</pre><pre class="codeoutput">Z =
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
</pre><h4>Double precision<a rel="nofollow" name="ebaccbdf-d4f0-4adc-bd87-05436ba95bfc"></a></h4><p>Convert the symbolic form to double precision floating point.</p><pre class="codeinput">format <span class="string">long</span> <span class="string">e</span>
p = sym2poly(P)';
c = flipud(coeffs(poly2sym(p))')
</pre><pre class="codeoutput">c =
                     1
                  -210
                 20615
              -1256850
              53327946
           -1672280820
           40171771630
         -756111184500
        11310276995381
      -135585182899530
      1307535010540395
    -10142299865511450
     63030812099294896
   -311333643161390656
   1206647803780373248
  -3599979517947607040
   8037811822645051392
 -12870931245150988288
  13803759753640704000
  -8752948036761600000
   2432902008176640000
</pre><p>Five of the coefficients cannot be represented in double precision format. They have been perturbed.</p><pre class="codeinput">delta = C-c
</pre><pre class="codeoutput">delta =
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
   16
  112
 -160
  384
 -512
    0
    0
    0
</pre><h4>Double precision roots<a rel="nofollow" name="88810d87-ef68-452f-8fb5-aecb7e711501"></a></h4><p>The roots of the polynomial with the double precision coefficients are no longer <tt>1:20</tt>. The largest perturbations occur to the roots at <tt>16</tt> and <tt>17</tt>.</p><pre class="codeinput">z = sort(roots(p));
fmt = <span class="string">'%25.16f&#92;n'</span>;
fprintf(fmt,z)
</pre><pre class="codeoutput">       0.9999999999997972
       2.0000000000475513
       2.9999999973842115
       4.0000000600349486
       4.9999992200080809
       6.0000064898423089
       6.9999645183068031
       8.0001214537649652
       8.9997977879058215
       9.9997884273944386
      11.0021078422257670
      11.9944660326764140
      13.0076639325972590
      13.9958171375909190
      14.9955431043450050
      16.0114122070902880
      16.9888815075391190
      18.0060272186900080
      18.9981637365860050
      20.0002393259700360
</pre><h4>Wilkinson's perturbation<a rel="nofollow" name="4e933ac9-12f6-4685-af5a-d59152175246"></a></h4><p>Wilkinson made a different perturbation, a deliberate roundoff error on his machine to the second coefficient, the $-210$.  He changed this coefficient by $2^{-23}$ and discovered that several of the roots were driven into the complex plane.</p><p>I am not sure $^&#92;dagger$ about the sign of Wilkinson's perturbation, so let's do both. Here is a movie, an animated GIF, of the root locus in the complex plane produced by perturbations like his.  It shows the trajectories of the roots from $9$ to $20$ of</p><p>$$ P_{20}(x) - &#92;alpha x^{19} $$</p><p>as we vary $&#92;alpha$ over the range</p><p>$$ &#92;alpha = &#92;pm 2^{-k}, k = 23, ..., 36 $$ The roots $1$ to $8$ stay real for perturbations in this range. Wilkinson's result is at the end of either the red or the black trajectories.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/P20_movie.gif" alt=""> </p><h4>Sensitivity<a rel="nofollow" name="aeb2589c-c6bb-44c1-8ea7-73c838dbf237"></a></h4><p>With a little calculus, we can get an analytic expression for the sensitivity of the roots with Wilkinson's perturbation. Regard each root $x$ as function of $&#92;alpha$ and differentiate the following equation with respect to $&#92;alpha$.</p><p>$$ P_{20}(x) - &#92;alpha x^{19} = 0 $$</p><p>At $&#92;alpha = 0$, we have</p><p>$$ &#92;frac{dx}{d&#92;alpha} = &#92;frac{x^{19}}{P_{20}'(x)} $$</p><p>This is easy to evaluate.</p><pre class="codeinput">pprime = sym2poly(diff(P20));
xdot = zeros(n,1);
<span class="keyword">for</span> k = 1:n
   xdot(k) = k^19/polyval(pprime,k);
<span class="keyword">end</span>
format <span class="string">short</span> <span class="string">e</span>
xdot
</pre><pre class="codeoutput">xdot =
  -8.2206e-18
   8.1890e-11
  -1.6338e-06
   2.1896e-03
  -6.0774e-01
   5.8248e+01
  -2.5424e+03
   5.9698e+04
  -8.3916e+05
   7.5994e+06
  -4.6378e+07
   1.9894e+08
  -6.0434e+08
   1.3336e+09
  -2.1150e+09
   2.4094e+09
  -1.9035e+09
   9.9571e+08
  -3.0901e+08
   4.3100e+07
</pre><p>The sensitivities vary over 27 orders of magnitude, with the largest values again at $16$ and $17$.  Here is a log plot.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/P20_prime.png" alt=""> </p><p>This is a different perturbation than the one from symbolic to double, but the qualitative effect is the same.</p><h4>Note added March 10, 2013.<a rel="nofollow" name="02259bc3-4e57-4579-9790-3f23b2535e68"></a></h4><p>$^&#92;dagger$ I am back in the office where I have access to Wilkinson's <i>The Algebraic Eigenvalue Problem</i>.  This polynomial is discussed, among other places, on pages 417 and 418.  The perturbation he makes is negative, so the coefficient of $x^{19}$ becomes $-210 - 2^{-23}$ and the resulting roots are at the ends of our red trajectories.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/GGSOrzFNcs4" height="1" width="1"/>]]></content:encoded>
         <category>Precision</category>
      </item>
      <item>
         <title>Dancing in the spotlight – The intersection between robotics, video processing and art</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/RAemaE8Dtes/</link>
         <description>This week I&amp;#8217;d like to introduce guest blogger Joachim Schlosser. Joachim leads the team of Education Technical Specialists in Europe, supporting professors and teaching staff using MATLAB &amp;#38; Simulink in education. His mission is to serve development organizations, universities, professors and engineers in all stages of their career to best leverage their proficiency by finding [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2137</guid>
         <pubDate>Mon, 04 Mar 2013 14:00:52 +0000</pubDate>
         <content:encoded><![CDATA[<p><em>This week I&#8217;d like to introduce guest blogger Joachim Schlosser. Joachim leads the team of Education Technical Specialists in Europe, supporting professors and teaching staff using MATLAB &amp; Simulink in education. His mission is to serve development organizations, universities, professors and engineers in all stages of their career to best leverage their proficiency by finding out what kind of methodology and tools are of greatest use for them. You can find Joachim on <a rel="nofollow" target="_blank" href="http://twitter.com/schlosi">Twitter</a>, <a rel="nofollow" target="_blank" href="http://www.linkedin.com/in/jschlosser">LinkedIn</a> and <a rel="nofollow" target="_blank" href="http://plus.google.com/108573450649244839154?rel=author">Google+</a>.</em></p>
<h2>Dancing in the Spotlight</h2>
<p><em>by Joachim Schlosser</em></p>
<p>I love trade shows and conferences, because you get the opportunity to speak with people creating very different things all on one day. The Embedded World trade show, held each year end of February in Nuremberg, Germany, is such an event. Every time it is amazing to see the breadth of topics that people approach us on, and it is fun to discuss and find out which of our tools around MATLAB &amp; Simulink can make them successful.</p>
<h2>Dancing: Enter Anna.</h2>
<p>People might stop because they see our hostess Anna making the cute little Nao robot dance, but they come into discussion because they get the vision about what <em>they</em> could achieve themselves. What they see on the booth is just a catalyst for people&#8217;s own insight and needs, just a starting point to evaluate which tools serve best their applications.</p>
<p><img src="http://blogs.mathworks.com/community/files/anna.jpg" alt="" title="anna" width="500" height="322" class="alignnone size-full wp-image-2141"/><br />
<br/><span style="font-size:8px;"><em>Photo courtesy Joachim Schlosser.</em></span></p>
<h2>Movement: Enter John.</h2>
<p>Enter booth visitor John (not his real name) from Ynapmoc, Inc. (not his real company), a small to mid size manufacturer with 40 years of experience in the area of medical devices (not his real industry). When he approached me, he said he stopped because he noticed we somehow analyze the real picture data, and he was curious to find out more. He then found yet another demonstration in the booth where a Simulink model made an Arduino board with a webcam track and follow a colored ball. Think of it as a stripped down version of <a rel="nofollow" target="_blank" href="http://www.youtube.com/watch?v=paytCdcLRno">this one</a>, but you get the idea. </p>
<p>Now the reason John was curious is because they are abstracting movements of people filmed in their lab to detect anomalies in their muscle tissue functions and provide a self-assessment tool (not his real application). They had been coding it by hand, with little possibility to do fast prototyping, and with additional effort to adapt the functionality each time they got another camera, each time they have another idea to make the algorithm better. To see that he could do <a rel="nofollow" target="_blank" href="http://www.mathworks.com/image-video-processing/">video processing in Simulink</a> was a relief to him, since he knew it from his engineering studies. To see additionally that he could <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/arduino-software/">real-time prototype on a low cost Arduino board</a> made John enthusiastic.</p>
<h2>Grid stability: Enter Lynn.</h2>
<p>Enter Lynn (not her real name), engineer from Sunshine Corp (not her real company), who works on electrical energy generators used in production plants as backup to the regular power grid (not her real application). She had seen our offerings around <a rel="nofollow" target="_blank" href="http://www.mathworks.com/products/simpower/">simulating electrical systems</a> and wondered whether this would not just work for simulating an isolated device but the production plant&#8217;s power grid as a whole. </p>
<p>Well, it&#8217;s not just possible to simulate an entire plant&#8217;s grid, Transpower from New Zealand went a bit further and <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/user_stories/Transpower-Ensures-Reliability-of-New-Zealand-National-Grid-with-Reserve-Management-Tool.html">simulated the entire national grid</a>. They do this to calculate the reserve they need to provide in order to maintain grid stability. So, Lynn has made her next step in solving her challenge, discussing the scenario with one of our Application Engineers to find out the exact needs and a plan for implementing the solution.</p>
<p>Now what if you combine both, image processing and control?</p>
<h2>3D Imaging: Enter Nao.</h2>
<p>Enter <a rel="nofollow" target="_blank" href="http://www.aldebaran-robotics.com/en">Nao</a> (its real name) from Aldebaran (its real company). Nao is the little robot from the beginning of this story. Think of movement. Think of control theory. Think of feedback control. Think of Simulink. And now attach <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/kinect/">Microsoft® Kinect® with its support in MATLAB &amp; Simulink</a>, one of the many <a rel="nofollow" target="_blank" href="http://www.mathworks.com/academia/hardware-resources/">hardware resources for project-based learning</a>. Kinect provides a 3D image of a person, which is transformed into a mesh in MATLAB &amp; Simulink, allowing it to calculate trajectories for the robot. The rest is <em>normal</em> control system theory with Model-Based Design. </p>
<p><img src="http://blogs.mathworks.com/community/files/kinect.jpg" alt="" title="kinect" width="500" height="420" class="alignnone size-full wp-image-2142"/></p>
<p>You get: A dancing machine being able to mimic movements of a human. A lot of fun in the realms of engineering, science, commercial and education developments, controls, video, data analysis. And lots of nice discussions with bright people of different disciplines who either are already using MATLAB &amp; Simulink or are exploring their way into doing so. To live and breathe their art.</p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/RAemaE8Dtes" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Your MATLAB Files on the Cloud. And more.</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/vA6JHAYMCOQ/</link>
         <description>Happy 2013! 2012 was an eventful year for MATLAB Mobile, with releases for the iPad, the Android platform, and several enhancements to graphics and usability. To kick off 2013 on a high note, we are making connecting to the cloud even better. Introducing… MATLAB Cloud Storage You can now upload MATLAB files and data to [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2051</guid>
         <pubDate>Mon, 25 Feb 2013 17:40:50 +0000</pubDate>
         <content:encoded><![CDATA[<p style="text-align:justify;">Happy 2013!</p>
<p style="text-align:justify;">2012 was an eventful year for MATLAB Mobile, with releases for the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2012/01/16/matlab-mobile-ipad-app/">iPad</a>, the <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/2012/10/18/matlab-mobile-for-android/">Android</a> platform, and several enhancements to graphics and usability.</p>
<p style="text-align:justify;">To kick off 2013 on a high note, we are making connecting to the cloud even better.</p>
<p style="text-align:justify;"><strong>Introducing… MATLAB Cloud Storage</strong></p>
<p style="text-align:justify;">You can now upload MATLAB files and data to MathWorks Cloud and run them from MATLAB Mobile. You can also download your files from the cloud and save them to your computer.</p>
<p style="text-align:left;">To upload your files, navigate to the MATLAB Cloud Storage page at <a rel="nofollow" target="_blank" href="https://www.mathworks.com/mobile/cloud-storage.html">https://www.mathworks.com/mobile/cloud-storage.html</a>. To access this page, you will need to have a valid MathWorks Account associated with a license that is current on maintenance. You will also need to have created a user ID on MATLAB Mobile.</p>
<div>
<p style="text-align:left;">Once your files have been uploaded, you can execute them from your mobile device running MATLAB Mobile. For more information, please refer to <a rel="nofollow" target="_blank" href="http://www.mathworks.com/mobile/store-files-on-cloud.html">Store MATLAB files on the cloud</a>.<a rel="nofollow" style="text-align:center;" target="_blank" href="http://blogs.mathworks.com/community/files/cloudstorage1.png"><img class="size-full wp-image-2084" title="Cloud Storage for MATLAB Mobile" src="http://blogs.mathworks.com/community/files/cloudstorage1.png" alt="" width="539" height="282"/></a></p>
<p>&nbsp;</p>
<p style="text-align:justify;"><strong>But wait, there&#8217;s more!</strong></p>
<p style="text-align:justify;">- When you connect to MathWorks cloud, you can now access all your licensed MathWorks products.</p>
<p style="text-align:justify;">- We’ve also added a customized keyboard for the Android platform, making it easy for you to enter MATLAB commands without having to switch between multiple screens. The keyboard provides easy access to commonly used MATLAB characters like parenthesis, indexing operators, arithmetic operators and the like. You can also access previously entered commands with the touch of a single key. Tapping and holding on selected keys displays additional characters. For instance, a long tap on the ‘.’ key displays the list of characters in blue.</p>
<p><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/keyboard2_framed.png"><img class="alignnone size-large wp-image-2055" title="Custom Keyboard for Android" src="http://blogs.mathworks.com/community/files/keyboard2_framed-613x1024.png" alt="" width="258" height="430"/></a><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/files/keyboard1_framed.png"><img class="alignnone size-large wp-image-2054" title="Tap and Hold for Additional Characters" src="http://blogs.mathworks.com/community/files/keyboard1_framed-613x1024.png" alt="" width="258" height="430"/></a></p>
<p style="text-align:justify;">- MATLAB Mobile for iOS now supports iPhone 5 and iPad mini.</p>
<p style="text-align:justify;">To download the latest version of MATLAB Mobile, visit the <a rel="nofollow" target="_blank" href="https://itunes.apple.com/us/app/matlab-mobile/id370976661?mt=8">App Store</a> or <a rel="nofollow" target="_blank" href="https://play.google.com/store/apps/details?id=com.mathworks.matlabmobile">Google Play</a>.</p>
<p style="text-align:justify;">With cloud storage, what files are you running from your mobile device? How is the new Android keyboard helping you? Leave us a comment <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/community/?p=2051#respond">here </a>with your thoughts.</p>
</div>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/vA6JHAYMCOQ" height="1" width="1"/>]]></content:encoded>
      </item>
      <item>
         <title>Revisiting dctdemo – part 2</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/-yRD2wr_FOs/</link>
         <description>This is the second part of my plan to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features.Recall the old app I'm trying to reinvent: The idea is to experiment with the basic principles of DCT-based image compression. I've decided that I don't want to copy this original [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=766</guid>
         <pubDate>Thu, 21 Feb 2013 22:15:45 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>This is the second part of my plan to rewrite an Image Processing Toolbox example from 20 years ago using more modern MATLAB language features.</p><p>Recall the old app I'm trying to reinvent:</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo-screen-shot.png" alt=""> </p><p>The idea is to experiment with the basic principles of DCT-based image compression. I've decided that I don't want to copy this original layout and functionality exactly. For one thing, computers (and MATLAB!) are a lot faster than they were 20 years ago, and I think we really don't need a separate "Apply" button.</p><p>Here's my first attempt at sketching what I'd like to make this time around.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dct-compression-sketch.jpg" alt=""> </p><p>The truth, is, I'm making the code and these posts up as I go along. So far I've only had a chance to get some of the initial pieces up and working. But it's enough to start exploring some of the coding ideas.</p><p>Here's what happens when I call the app class, which I've called (for now) <tt>dctCompressionExample_v2</tt>.</p><pre class="codeinput">app = dctCompressionExample_v2
</pre><pre class="codeoutput">
app = 

  dctCompressionExample_v2 handle

  Properties:
         OriginalImage: [240x240 double]
    ReconstructedImage: []
            ErrorImage: []
    DCTCoefficientMask: []
    NumDCTCoefficients: 10


</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo_part2_01.png" alt=""> <p>You can see I got some output in the Command Window, and I also got a new figure on the screen.</p><p>Here's the code so far.</p><pre>classdef dctCompressionExample_v2 &lt; handle</pre><pre>    properties (SetAccess = private)
        OriginalImage
        ReconstructedImage
        ErrorImage
        DCTCoefficientMask
    end</pre><pre>    properties
        NumDCTCoefficients = 10
    end</pre><pre>    properties (Access = private)
        Slider
        OriginalImageAxes
        ReconstructedImageAxes
        ErrorImageAxes
        MaskAxes
    end</pre><pre>    methods
        function this_app = dctCompressionExample_v2
            this_app.OriginalImage = initialImage;
            layoutApp(this_app);
            update(this_app);
        end</pre><pre>        function layoutApp(app)
            f = figure;
            app.OriginalImageAxes = axes('Parent',f, ...
                'Position',[0.12 0.56 0.28 0.28]);
            app.ReconstructedImageAxes = axes('Parent',f, ...
                'Position',[0.60 0.56 0.28 0.28]);
            app.MaskAxes = axes('Parent',f, ...
                'Position',[0.12 0.16 0.28 0.28]);
            app.ErrorImageAxes = axes('Parent',f, ...
                'Position',[0.60 0.16 0.28 0.28]);
            app.Slider = uicontrol('Style','slider', ...
                'Value',app.NumDCTCoefficients/64, ...
                'Units','normalized', ...
                'Position',[0.12 0.08 0.28 0.04], ...
                'Callback',@(~,~,~) app.reactToSliderChange);</pre><pre>        end</pre><pre>        function reactToSliderChange(app)
            v = get(app.Slider,'Value');
            app.NumDCTCoefficients = round(64*v);
            update(app);
        end</pre><pre>        function update(app)
            imshow(app.OriginalImage,'Parent',app.OriginalImageAxes);
            title(app.OriginalImageAxes,'Original Image');</pre><pre>            imshow(app.OriginalImage,'Parent',app.ReconstructedImageAxes);
            title(app.ReconstructedImageAxes,'Reconstructed Image');</pre><pre>            imshow(zeros(size(app.OriginalImage)),'Parent',app.ErrorImageAxes);
            title(app.ErrorImageAxes,'Error Image');</pre><pre>            imshow(zeros(size(app.OriginalImage)),'Parent',app.MaskAxes);
            title(app.MaskAxes,'DCT Coefficient Mask');
            drawnow;
        end
    end</pre><pre>end</pre><pre>function I = initialImage
pout = imread('pout.tif');
pout2 = pout(1:240,:);
I = im2double(adapthisteq(pout2));
end</pre><p>At this point I'll remind you of Dave Garrison's <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/newsletters/articles/writing-apps-in-matlab.html">article</a> that I mentioned last time. This article teaches about how this kind of code works. I don't intend to repeat all of that article here. I'll just point out a few things.</p><p>Here's the function that runs when you launch the app.</p><pre>        function this_app = dctCompressionExample_v2
            this_app.OriginalImage = initialImage;
            layoutApp(this_app);
            update(this_app);
        end</pre><p><tt>initialImage</tt> is a little function I stuck at the bottom of the file. It's purpose is to create our sample image, which for the purpose of this simple DCT demonstration needs to be a multiple of 8-by-8 in size. (Plus, I threw in a call to <tt>adapthisteq</tt> because the original image has low contrast.)</p><pre>function I = initialImage
pout = imread('pout.tif');
pout2 = pout(1:240,:);
I = im2double(adapthisteq(pout2));
end</pre><p>Then there's the properties block.</p><pre>    properties (SetAccess = private)
        OriginalImage
        ReconstructedImage
        ErrorImage
        DCTCoefficientMask
    end</pre><pre>    properties
        NumDCTCoefficients = 10
    end</pre><pre>    properties (Access = private)
        Slider
        OriginalImageAxes
        ReconstructedImageAxes
        ErrorImageAxes
        MaskAxes
    end</pre><p>Some of the properties, such as <tt>OriginalImage</tt>, I want to make accessible but read-only. Some of them, such as <tt>OriginalImageAxes</tt>, are private because they are only needed by the guts of the app. Notice that one of them, <tt>NumDCTCoefficients</tt>, is both readable <b>and</b> settable. I wanted to explore the idea of giving this app a little programmable interface so that you can write code to make it change.</p><p>I would like to make it so that the <tt>NumDCTCoefficients</tt> property changes when you drag the slider. Here's how to accomplish that:</p><pre>            app.Slider = uicontrol('Style','slider', ...
                'Value',app.NumDCTCoefficients/64, ...
                'Units','normalized', ...
                'Position',[0.12 0.08 0.28 0.04], ...
                'Callback',@(~,~,~) app.reactToSliderChange);</pre><p>Setting the <tt>'Callback'</tt> property of the slider like this causes the app's function <tt>reactToSliderChange</tt> to get called whenever the slider is dragged. Here's what <tt>reactToSliderChange</tt> does:</p><pre>        function reactToSliderChange(app)
            v = get(app.Slider,'Value');
            app.NumDCTCoefficients = round(64*v);
            update(app);
        end</pre><p>Now we're starting to get a little interactivity going in our app.</p><p>That's about as far as I got this week. Next time we'll continue wiring things up and maybe start putting in some algorithmic DCT block processing code.</p>
<div><ul><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/08/revisiting-dctdemo-part-1/">Revisiting dctdemo - part 1</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/21/revisiting-dctdemo-part-2/">Revisiting dctdemo - part 2</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/21/revisiting-dctdemo-part-3/">Revisiting dctdemo - part 3</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/04/12/revisiting-dctdemo-part-4/">Revisiting dctdemo - part 4</a></li></ul></div>
<p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/-yRD2wr_FOs" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Logical Indexing – Multiple Conditions</title>
         <link>http://feedproxy.google.com/~r/mathworks/loren/~3/LddjaaOsw6M/</link>
         <description>I've talked about logical indexing before in some of the linked posts, but recent work makes me want to show it off again. One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.ContentsWhat is Logical [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=637</guid>
         <pubDate>Wed, 20 Feb 2013 13:48:52 +0000</pubDate>
         <content:encoded><![CDATA[<style type="text/css">

h1 {font-size:18pt;}
h2.titlebg {font-size:13pt;}
h3 {color:#4A4F55;padding:0px;margin:5px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:11pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}
h4 {color:#4A4F55;padding:0px;margin:0px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:10pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}

p {padding:0px;margin:0px 0px 20px;}
img {padding:0px;margin:0px 0px 20px;border:none;}
p img, pre img, tt img, li img {margin-bottom:0px;}

ul {padding:0px;margin:0px 0px 20px 23px;list-style:square;}
ul li {padding:0px;margin:0px 0px 7px 0px;background:none;}
ul li ul {padding:5px 0px 0px;margin:0px 0px 7px 23px;}
ul li ol li {list-style:decimal;}
ol {padding:0px;margin:0px 0px 20px 0px;list-style:decimal;}
ol li {padding:0px;margin:0px 0px 7px 23px;list-style-type:decimal;}
ol li ol {padding:5px 0px 0px;margin:0px 0px 7px 0px;}
ol li ol li {list-style-type:lower-alpha;}
ol li ul {padding-top:7px;}
ol li ul li {list-style:square;}

pre, tt, code {font-size:12px;}
pre {margin:0px 0px 20px;}
pre.error {color:red;}
pre.codeinput {padding:10px;border:1px solid #d3d3d3;background:#f7f7f7;}
pre.codeoutput {padding:10px 11px;margin:0px 0px 20px;color:#4c4c4c;}

 _filtered {width:100%;}

span.keyword {color:#0000FF;}
span.comment {color:#228B22;}
span.string {color:#A020F0;}
span.untermstring {color:#B20000;}
span.syscmd {color:#B28C00;}

.footer {width:auto;padding:10px 0px;margin:25px 0px 0px;border-top:1px dotted #878787;font-size:0.8em;line-height:140%;font-style:italic;color:#878787;text-align:left;float:none;}
.footer p {margin:0px;}

</style><div class="content"><p>I've talked about logical <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/category/indexing/">indexing</a> before in some of the linked posts, but recent work makes me want to show it off again.  One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#33f0748f-5b6e-4605-9d0d-a86827bdb8a3">What is Logical Indexing?</a></li><li><a rel="nofollow" href="#ef412173-88ef-43d1-81ab-b2df3d7dde77">Compound conditions.</a></li><li><a rel="nofollow" href="#f4e56162-08ec-44b0-a4e8-7086976be875">Find Values Meeting More Than One Condition</a></li><li><a rel="nofollow" href="#a554527a-320f-40bd-95dc-42695925b486">Did You Notice?</a></li><li><a rel="nofollow" href="#e9531c73-0182-4f21-8bf5-c11a0970562d">A Recent Application</a></li><li><a rel="nofollow" href="#14ef4d77-81f6-4722-a6ce-3cd56ca4d31b">Have You Used Compound Indexing?</a></li></ul></div><h4>What is Logical Indexing?<a rel="nofollow" name="33f0748f-5b6e-4605-9d0d-a86827bdb8a3"></a></h4><p>Suppose I have an array of integers, not sorted, and want to find the ones that are less than a certain number.  Here's how I can do it using the function <a rel="nofollow" target="_blank" href="http://www.mathworks.com/help/matlab/ref/find.html"><tt>find</tt></a>.</p><pre class="codeinput">X = randperm(20)
target = 5;
</pre><pre class="codeoutput">X =
  Columns 1 through 13
     3     7     1    16    20    15    13     9    14     8    11    19    18
  Columns 14 through 20
     4    10     5     6    17    12     2
</pre><pre class="codeinput">ind = find(X &lt; target)
</pre><pre class="codeoutput">ind =
     1     3    14    20
</pre><p>You can see that find returns the indices into the array <tt>X</tt> that have values less than the <tt>target</tt>.  And we can use these to extract the values.</p><pre class="codeinput">Xtarget = X(ind)
</pre><pre class="codeoutput">Xtarget =
     3     1     4     2
</pre><p>Another way to accomplish the same outcome is to use the logical expression to directly perform the indexing operation.  Here's what I mean.</p><pre class="codeinput">logInd = X &lt; target
</pre><pre class="codeoutput">logInd =
  Columns 1 through 13
     1     0     1     0     0     0     0     0     0     0     0     0     0
  Columns 14 through 20
     1     0     0     0     0     0     1
</pre><p>MATLAB returns an array that matches the elements of the array <tt>X</tt>, element-by-element holding 1s where the matching values in <tt>X</tt> are the desired values, and 0s otherwise.  The array <tt>logInd</tt> is not an array of double numbers, but have the class <tt>logical</tt>.</p><pre class="codeinput">whos <span class="string">logInd</span>
</pre><pre class="codeoutput">  Name        Size            Bytes  Class      Attributes

  logInd      1x20               20  logical              

</pre><p>I can now use this array to extract the desired values from <tt>X</tt>.</p><pre class="codeinput">XtargetLogical = X(logInd)
</pre><pre class="codeoutput">XtargetLogical =
     3     1     4     2
</pre><p>Both methods return the results.</p><pre class="codeinput">isequal(Xtarget, XtargetLogical)
</pre><pre class="codeoutput">ans =
     1
</pre><h4>Compound conditions.<a rel="nofollow" name="ef412173-88ef-43d1-81ab-b2df3d7dde77"></a></h4><p>Let me create an anonymous function that returns true (<tt>logical(1)</tt>) for values that are even integers.</p><pre class="codeinput">iseven = @(x) ~logical(rem(x,2))
</pre><pre class="codeoutput">iseven = 
    @(x)~logical(rem(x,2))
</pre><p>Test <tt>iseven</tt>.</p><pre class="codeinput">iseven(1:5)
</pre><pre class="codeoutput">ans =
     0     1     0     1     0
</pre><h4>Find Values Meeting More Than One Condition<a rel="nofollow" name="f4e56162-08ec-44b0-a4e8-7086976be875"></a></h4><p>Now I would like to find the values in <tt>X</tt> that are less than <tt>target</tt> and are even. This is very natural to do with logical indexing.  We have the pieces of code we need already.</p><pre class="codeinput">compoundCondInd = (X &lt; target) &amp; iseven(X)
</pre><pre class="codeoutput">compoundCondInd =
  Columns 1 through 13
     0     0     0     0     0     0     0     0     0     0     0     0     0
  Columns 14 through 20
     1     0     0     0     0     0     1
</pre><p>We can see we found suitable values at locations 3 and 19.  And we can extract those values next.</p><pre class="codeinput">X(compoundCondInd)
</pre><pre class="codeoutput">ans =
     4     2
</pre><h4>Did You Notice?<a rel="nofollow" name="a554527a-320f-40bd-95dc-42695925b486"></a></h4><p>Did you see how easy it is to combine multiple conditions?  I simply look for each of condition, getting back logical arrays, and then compute a logical array where the two input arrays are both true (via <tt>&amp;</tt>). I could, of course, calculate a compound condition where only either one or the other condition needs to be true using logical or (via |).</p><h4>A Recent Application<a rel="nofollow" name="e9531c73-0182-4f21-8bf5-c11a0970562d"></a></h4><p>I recently used this in the context of finding suspect data values.  I had 2 arrays, hourly temperature and speed.  The problem is that when the temperature gets near or below freezing, the speed sensor might freeze. But I didn't want to delete ALL the values below freezing.  So I looked for data where the temperature was sufficiently low AND the speed was very low (which could potentially mean the sensor was frozen).  That way, I did not need to discard all data at low temperatures.</p><h4>Have You Used Compound Indexing?<a rel="nofollow" name="14ef4d77-81f6-4722-a6ce-3cd56ca4d31b"></a></h4><p>Did you do it like I did, using logical expressions?  Or did you use some other techniques?  What were you trying to achieve with your compound indexing?  Let me know <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren/?p=637#respond">here</a>.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/LddjaaOsw6M" height="1" width="1"/>]]></content:encoded>
         <category>Indexing</category>
      </item>
      <item>
         <title>Jim Wilkinson</title>
         <link>http://feedproxy.google.com/~r/mathworks/moler/~3/sjE2IDAmFWM/</link>
         <description>I have already made several posts about gatlin, the image distributed with MATLAB of the organizing committee for the Gatlinburg III conference. From the MATLAB point of view, the first man on the left in the photo, J. H. Wilkinson, is by far the most important. From the early days of computers in the 1950s [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/cleve/?p=498</guid>
         <pubDate>Mon, 18 Feb 2013 17:00:55 +0000</pubDate>
         <content:encoded><![CDATA[<style type="text/css">

h1 {font-size:18pt;}
h2.titlebg {font-size:13pt;}
h3 {color:#4A4F55;padding:0px;margin:5px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:11pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}
h4 {color:#4A4F55;padding:0px;margin:0px 0px 5px;font-family:Arial, Helvetica, sans-serif;font-size:10pt;font-weight:bold;line-height:140%;border-bottom:1px solid #d6d4d4;display:block;}

p {padding:0px;margin:0px 0px 20px;}
img {padding:0px;margin:0px 0px 20px;border:none;}
p img, pre img, tt img, li img {margin-bottom:0px;}

ul {padding:0px;margin:0px 0px 20px 23px;list-style:square;}
ul li {padding:0px;margin:0px 0px 7px 0px;background:none;}
ul li ul {padding:5px 0px 0px;margin:0px 0px 7px 23px;}
ul li ol li {list-style:decimal;}
ol {padding:0px;margin:0px 0px 20px 0px;list-style:decimal;}
ol li {padding:0px;margin:0px 0px 7px 23px;list-style-type:decimal;}
ol li ol {padding:5px 0px 0px;margin:0px 0px 7px 0px;}
ol li ol li {list-style-type:lower-alpha;}
ol li ul {padding-top:7px;}
ol li ul li {list-style:square;}

pre, tt, code {font-size:12px;}
pre {margin:0px 0px 20px;}
pre.error {color:red;}
pre.codeinput {padding:10px;border:1px solid #d3d3d3;background:#f7f7f7;}
pre.codeoutput {padding:10px 11px;margin:0px 0px 20px;color:#4c4c4c;}

 _filtered {width:100%;}

span.keyword {color:#0000FF;}
span.comment {color:#228B22;}
span.string {color:#A020F0;}
span.untermstring {color:#B20000;}
span.syscmd {color:#B28C00;}

.footer {width:auto;padding:10px 0px;margin:25px 0px 0px;border-top:1px dotted #878787;font-size:0.8em;line-height:140%;font-style:italic;color:#878787;text-align:left;float:none;}
.footer p {margin:0px;}

</style><div class="content"><p>I have already made several posts about <tt>gatlin</tt>, the image distributed with MATLAB of the organizing committee for the Gatlinburg III conference. From the MATLAB point of view, the first man on the left in the photo, J. H. Wilkinson, is by far the most important.  From the early days of computers in the 1950s until his death in 1986, Wilkinson was the world's authority on matrix computation.  His research on eigenvalue algorithms and their implementation in Algol led directly to EISPACK, the mathematical foundation for the first MATLAB.</p><h3>Contents</h3><div><ul><li><a rel="nofollow" href="#c839cba7-1835-489b-b5b2-c4138227bddb">Early Life</a></li><li><a rel="nofollow" href="#7697cfd4-bf2d-4868-a06f-a99411e8ed82">World War II</a></li><li><a rel="nofollow" href="#1ba48215-3231-4a06-b4df-55308506f3d1">Leslie Fox</a></li><li><a rel="nofollow" href="#f6108dfd-13d3-4855-ba1b-25dd967898f8">Pilot Ace</a></li><li><a rel="nofollow" href="#26584b98-8ffa-48a9-beb7-5393280a0a4b">Ann Arbor</a></li><li><a rel="nofollow" href="#b7e60741-7819-4771-8fc0-3edbcf0571a2">Stanford</a></li><li><a rel="nofollow" href="#de678b2e-fe46-47ab-bb77-f2632eb61aef">Handbook</a></li><li><a rel="nofollow" href="#8fd4acb8-eeac-4df6-8443-8580138b4db6">Argonne</a></li><li><a rel="nofollow" href="#d7540d79-277a-415f-acce-c8017bd36ba9">References</a></li></ul></div><pre class="codeinput">load <span class="string">gatlin</span>
image(X)
colormap(map)
axis <span class="string">image</span>
axis <span class="string">off</span>
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/jhw_1_01.png" alt=""> <h4>Early Life<a rel="nofollow" name="c839cba7-1835-489b-b5b2-c4138227bddb"></a></h4><p>James Hardy Wilkinson was born in 1919 in Strood, England, a small town east of London, on the way towards Canterbury and Dover. The family owned a small dairy.</p><p>When Jim was only eleven years old he received a scholarship to Sir Joseph Williamson's Mathematical School in nearby Rochester. When he was barely 17, two years earlier than average, he entered Cambridge on a Trinity Major Scholarship in Mathematics. At Cambridge, his tutors included the famous mathematicians G. H. Hardy, J. E. Littlewood and A. S. Besicovitch. Besicovitch characterized Jim's performance on the Tripos exams, which are the culminatation of the undergraduate mathematics program at Cambridge, as "easily at the top of the First Class".</p><h4>World War II<a rel="nofollow" name="7697cfd4-bf2d-4868-a06f-a99411e8ed82"></a></h4><p>In the early years of World War II Wilkinson joined a team of mathematicians in an office at Cambridge.  They computed trajectories of artillery shells using mechanical desk calculators. Later he transferred to a laboratory at Fort Halstead to work on the thermodynamics of explosions.</p><p>At Fort Halsead, he met Heather Ware, a mathematician from King's College. They soon married and lived happily together for over 40 years.</p><p>At the end of the war, Jim transferred to the National Physical Laboratory, where he would remain for the rest of his career.  NPL is located just west of London, not far from Heathrow airport, and is like a British version of the American National Bureau of Standards.</p><h4>Leslie Fox<a rel="nofollow" name="1ba48215-3231-4a06-b4df-55308506f3d1"></a></h4><p>One of Jim's colleagues at NPL, who became his lifelong friend, was Leslie Fox.  Leslie was a year older than Jim, had been educated at Oxford, and returned there as a professor after eleven years at NPL.  After Jim's death, Leslie wrote a 40 page <i>biographical memoir</i> for the British Royal Society.  I am using that memoir as a reference for this blog.</p><p>I bring up Fox at this point because I was so impressed by his remark in the memoir that in their early days at NPL the two of them, together with E. T. Goodwin, solved an 18-by-18 set of simultaneous linear equations using desk computing equipment.  It took them two weeks!  It was one of the reasons they decided to build an automatic computer.</p><h4>Pilot Ace<a rel="nofollow" name="f6108dfd-13d3-4855-ba1b-25dd967898f8"></a></h4><p>The famous mathematician Alan Turing was at NPL at the time and proposed the construction of a elaborate machine known as the Automatic Computing Engine, or ACE.  Wilkinson became an assistant to Turing. After some disagreements with the Laboratory management, Turing departed for the University of Manchester and Jim was put in charge of the project. The team built only a portion of Turing's design, the Pilot ACE.  Jim actually did some of the soldering.  The Pilot ACE proved to be a useful machine on its own and was used for several years.  A commercial version was produced by the English Electric Company under the name DEUCE.</p><p>Here is Jim at the console of the Pilot Ace, probably at its public debut in November 1950.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/PilotAce_small.jpg" alt=""> </p><h4>Ann Arbor<a rel="nofollow" name="26584b98-8ffa-48a9-beb7-5393280a0a4b"></a></h4><p>Beginning in the late 1950's, the University of Michigan offered a summer short course in computing.  At first it was just one course, but it soon grew to be several courses in different aspects of computing -- programming, compilers, systems, numerical methods.</p><p>Bob Bartels was both a professor of mathematics and director of the University of Michigan computing center.  Bob invited eminent numerical analysts to give the lectures in the numerical methods short course. Starting around 1958, Alston Householder and Jim Wilkinson were regular lecturers in the course and came to Ann Arbor for two weeks every summer.</p><p>In 1965, Bartels decided that running the computing center had become a full time job and that he had to give up his regular teaching duties.  So the university recruited someone to replace him and I became an Assistant Professor of Mathematics at the University of Michigan in the fall of 1966. I also took over organizing the summer numerical methods short course. I was pleased that Alston and Jim continued to participate. Jim's notes for the Michigan summer course became the basis for his now classic 1965 book, <i>The Algebraic Eigenvalue Problem</i>.</p><p>Wilkinson and Householder knew all the restaurants in Ann Arbor, including the Pretzel Bell and the Old German, where the short course lecturers would usually order beer by the pitcher.  Olga Taussky-Todd, who accompanied her husband John Todd to these dinners, had a fairly reserved manner. One day she planned to take a visiting friend to the Pretzel Bell for lunch and she asked Jim, "Is it possible to order beer in more modest quantities?"  Jim replied, "Yes, but it has never been one of my ambitions."</p><h4>Stanford<a rel="nofollow" name="b7e60741-7819-4771-8fc0-3edbcf0571a2"></a></h4><p>I took my first numerical analysis course in grad school at Stanford from George Forsythe in 1962-63.  There were only a handful of students in the class.  Forsythe was editor of the Prentice-Hall Series in Automatic Computation and was preparing Wilkinson's book <i>Rounding Errors in Algebraic Processes</i> for publication.  He gave us the galley proofs to both read as course notes and check for typographical errors.  Forsythe was a fastidious editor, so I suspect the class did not find any typos that he had not already caught.</p><p>Sometime after I left Stanford in 1965 Wilkinson was appointed to a part time professorship there.  He visited perhaps one quarter a year. I'm not sure if he ever taught a regular course.  He was a terrific lecturer for a seminar or a short course and wonderful in one-on-one discussions, but he was never anxious to be a full time academic.</p><h4>Handbook<a rel="nofollow" name="de678b2e-fe46-47ab-bb77-f2632eb61aef"></a></h4><p>Much of Wilkinson's research was published in a series of papers in the journal <i>Numerische Mathematik</i> in the late 1960's.  The papers described algorithms for matrix computation and included programs in Algol 60, the International Algorithmic Language.  A number of other authors contributed papers and programs to the series, which was known as the Handbook Series.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/WandRcover_small.jpg" alt=""> </p><p>All of the papers in the Handbook Series were eventually collected in an actual handbook, edited by Wilkinson and Christian Reinsch, and published by Springer-Verlag in 1971.  Even today this Wilkinson and Reinsch handbook remains an important resource for work in matrix computation. The Algol codes provide a readable description of the techniques that lie at the heart of the matrix library in MATLAB.</p><h4>Argonne<a rel="nofollow" name="8fd4acb8-eeac-4df6-8443-8580138b4db6"></a></h4><p>Argonne National Laboratory is a located in a forest preserve 25 miles southwest of Chicago.  A herd of white deer roam freely on the grounds. The laboratory carries out a program of primarily unclassified research for the U.S. Department of Energy on basic science, energy, transportation, environmental issues, computing and national security.</p><p>Very few people could actually run the programs in the Handbook because very few computer centers had Algol compilers.  Around 1970, the Mathematics and Computer Science Division, MCS, at Argonne began a project to translate a portion of the Handbook into Fortran, and to study the subsequent testing, distribution and support of the software.  The project involved the subset of the Handbook devoted to eigenvalue computation because most computer center libraries already had satisfactory linear equation solvers, but few had the new eigenvalue methods that Wilkinson  and colleagues had developed.</p><p>The project was called NATS, National Activity to Test Software.  It was supported by the National Science Foundation and what was then called the Atomic Energy Commission.  The stated objective of the project was research into the software development, testing and distribution process.  The software itself, which became known as EISPACK, for Eigensysem Package, was just a byproduct.  Simply writing good software wasn't regarded as supportable research.  It wasn't in 1970, and still isn't in 2013.</p><p>Jim was an important participant in the NATS/EISPACK project.  He visited Argonne at least once a year, usually after the Michigan summer course. He didn't write any Fortran code, but he was an active consultant in the process of rewriting what was mostly his Algol.  And, the testing process in those days was more complicated because there were so many machines with different arithmetic behavior.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/wilkie2_small.jpg" alt=""> </p><p>If you were involved in mathematical software back then, Argonne was <b>the</b> place to visit.  I moved to the University of New Mexico in 1972 and came to Argonne for most of every summer.  (When I walked in, Jim Boyle would say, "Moler is here, it must be June.")  There were always lots of international visitors.  In addition to Wilkinson, there were many other Brits.  MCS had a close connection with NAG, the Numerical Algorithms Group in the UK.  At the annual picnic one summer, we got the NAG chaps to play softball.  That resulted in a challenge to try cricket and they brought the necessary equipment with them the next summer. Jim was a cricket connoisseur.  He gave us a lecture on cricket strategy at the same blackboard he is using in the photo above.  A day or two later at the next picnic, he continued the lecture.  Jack Dongarra found this faded color photo in one of his shoe boxes.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/cleve/picnic_small.jpg" alt=""> </p><p>The EISPACK project was followed by the LINPACK project, also centered at Argonne.  These two projects motivated the first MATLAB.  Wilkinson wasn't directly involved in MATLAB, but he certainly was the primary source of the algorithms that formed its original mathematical core.</p><h4>References<a rel="nofollow" name="d7540d79-277a-415f-acce-c8017bd36ba9"></a></h4><p>[1] Leslie Fox, <i>James Hardy Wilkinson</i>, Biographical Memoirs of Fellows of the Royal Society 33 (1987): 669-708. <a rel="nofollow" target="_blank" href="http://rsbm.royalsocietypublishing.org/content/33/670">&lt;http://rsbm.royalsocietypublishing.org/content/33/670</a>&gt;</p><p>[2] Nick Higham's Gallery of Wilkinson Photos, <a rel="nofollow" target="_blank" href="http://www.maths.manchester.ac.uk/~higham/photos/wilkinson/index.htm">&lt;http://www.maths.manchester.ac.uk/~higham/photos/wilkinson/index.htm</a>&gt;.</p><p>[3] History of Householder Symposia, <a rel="nofollow" target="_blank" href="http://sites.uclouvain.be/HHXIX/SymposiumHistory">&lt;http://sites.uclouvain.be/HHXIX/SymposiumHistory</a>&gt;.</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/mathworks/moler/~4/sjE2IDAmFWM" height="1" width="1"/>]]></content:encoded>
         <category>People</category>
      </item>
      <item>
         <title>Visualizing Cody</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/ad1GvG4zaXU/</link>
         <description>Because of the amount of traffic that it gets, Cody generates a tremendous amount of interesting data every day. Most of it gets silently stored, because we haven&amp;#8217;t found good ways to reflect it directly in the application yet. I decided it was time to try out some Javascript visualization techniques on the data. This [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2047</guid>
         <pubDate>Mon, 11 Feb 2013 23:45:50 +0000</pubDate>
         <content:encoded><![CDATA[<p>Because of the amount of traffic that it gets, <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/">Cody</a> generates a tremendous amount of interesting data every day. Most of it gets silently stored, because we haven&#8217;t found good ways to reflect it directly in the application yet. I decided it was time to try out some Javascript visualization techniques on the data. This is the result: <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/images/desktop/viz/cody_viz.html">Cody Data Visualizer</a>.</p>
<p><img src="http://blogs.mathworks.com/community/files/cody-vis.png" alt="" title="cody-vis" width="373" height="364" class="alignnone size-full wp-image-2088"/></p>
<p>Go play around with it and tell me what you find. Shown above is one view: author ID vs. problem ID. It shows patterns of how problem authors contribute. The size of the dots is relative to the number of comments on the problem. That horizontal stripe across this middle at around author_id = 3000 is super contributor (and current Cody front runner) <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/cody/players/2789428-richard-zapor">Richard Zapor</a>, who has single-handedly contributed 122 problems!</p>
<p>This tool loads a relatively large (200 KB) data set when it starts up, so please be patient as it loads! Also, please note that this is an experimental tool that works with an archived static data set from February 8, 2013. It won&#8217;t reflect changes in Cody after that date.</p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/ad1GvG4zaXU" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Revisiting dctdemo – Part 1</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/_EiKStN3EpU/</link>
         <description>Last month, Dave Garrison wrote a nice article on the MathWorks web site about coding an app (or GUI) by defining a class.Curiously, this article made me think of a day back in September 1993. I arrived at MathWorks on that day to interview for a job as an image processing software developer. Sometime in [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=761</guid>
         <pubDate>Fri, 08 Feb 2013 15:19:06 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>Last month, Dave Garrison wrote a <a rel="nofollow" target="_blank" href="http://www.mathworks.com/company/newsletters/articles/writing-apps-in-matlab.html">nice article</a> on the MathWorks web site about coding an app (or GUI) by defining a class.</p><p>Curiously, this article made me think of a day back in September 1993. I arrived at MathWorks on that day to interview for a job as an image processing software developer. Sometime in the afternoon I found myself in an office with the two developers of version 1.0 of the Image Processing Toolbox. (One of those developers, Loren Shure, was the first employee hired by the MathWorks founders. You can find her over at <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/loren">Loren on the Art of MATLAB</a>.)</p><p>Anyway, the Image Processing Toolbox was about to ship, and the developers were trying to think of some demo ideas. I joined in a brainstorming session in front of a whiteboard. One of my ideas that day became the product demo called <tt>dctdemo</tt>. Here is a screen shot.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/dctdemo-screen-shot.png" alt=""> </p><p>(That's a picture of Loren, by the way.)</p><p>Prompted by Dave's article, I thought it might be a good time to revisit this oldie-but-goodie demo. It was originally written using MATLAB 4, and the programming techniques available at that time for doing this sort of thing were relatively crude. My plan is to take a fresh look at this demo and reimplement it using the techniques described by Dave.</p><p>Here's a start:</p><pre class="language-matlab"><span class="keyword">classdef</span> dctCompressionDemo &lt; handle
</pre><pre class="language-matlab"><span class="keyword">end</span>
</pre><p>That's enough code to actually execute.</p><pre class="codeinput">dctCompressionDemo
</pre><pre class="codeoutput">
ans = 

  dctCompressionDemo handle with no properties.

</pre><p>And that's about all it does (for now). Next time we'll start filling in the details.</p>
<div><ul><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/08/revisiting-dctdemo-part-1/">Revisiting dctdemo - part 1</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/02/21/revisiting-dctdemo-part-2/">Revisiting dctdemo - part 2</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/03/21/revisiting-dctdemo-part-3/">Revisiting dctdemo - part 3</a></li><li><a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2013/04/12/revisiting-dctdemo-part-4/">Revisiting dctdemo - part 4</a></li></ul></div>
<p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/_EiKStN3EpU" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>George Forsythe is inside the default MATLAB image</title>
         <link>http://feedproxy.google.com/~r/SteveOnImageProcessing/~3/RcXYG0kN6v4/</link>
         <description>A couple of weeks ago, Cleve wrote a post about George Forsythe, Cleve's &quot;thesis advisor, colleague, and friend.&quot;In that post, Cleve showed some MATLAB code to load in and display a 1964 picture of the organizing committee of the Gatlinburg conferences on numerical algebra.load gatlin image(X) colormap(map) axis image axis off As Cleve mentioned, this [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/steve/?p=754</guid>
         <pubDate>Mon, 28 Jan 2013 21:13:36 +0000</pubDate>
         <content:encoded><![CDATA[<div class="content"><p>A couple of weeks ago, <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/cleve">Cleve</a> wrote a <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/cleve/2013/01/07/george-forsythe/">post about George Forsythe</a>, Cleve's "thesis advisor, colleague, and friend."</p><p>In that post, Cleve showed some MATLAB code to load in and display a 1964 picture of the organizing committee of the Gatlinburg conferences on numerical algebra.</p><pre class="codeinput">load <span class="string">gatlin</span>
image(X)
colormap(map)
axis <span class="string">image</span>
axis <span class="string">off</span>
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/default_image_again_01.png" alt=""> <p>As Cleve mentioned, this picture is one of the very first images distributed with MATLAB. (I recall getting the first MATLAB version capable of image display sometime around 1990. It was very exciting!)</p><p>As it turns out, there is another interesting method in MATLAB to display this picture (or at least a cropped, low-resolution version of it):</p><pre class="codeinput">default_image = pow2(get(0,<span class="string">'DefaultImageCData'</span>),47);
numbits = 12 - 9 + 1;
b = bitshift(default_image,-9);
b = fix(b);
b = bitand(b,bitcmp(0,4));
b = b/max(b(:));

imshow(b,<span class="string">'InitialMagnification'</span>,200)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/default_image_again_02.png" alt=""> <p>Forsythe is on the right of the cropped version.</p><p>So, what's going on here? Well, it turns out that, if you call <tt>image</tt> with no input arguments (no data), an image with "default" pixel values gets displayed. Furthermore, that image has many images "hidden" within it. For the full story, see <a rel="nofollow" target="_blank" href="http://blogs.mathworks.com/steve/2006/10/17/the-story-behind-the-matlab-default-image/">"The Story Behind the Default MATLAB Image."</a></p><p>Cleve knew that I was working on this little hidden-image project in the mid-1990s, and I asked him for suggestions about images to include. He suggested this Gatlinburg Conference picture, as well as the 4-by-4 Durer magic square.</p><pre class="codeinput">c = bitshift(default_image,-23);
c = fix(c);
c = bitand(c,bitcmp(0,5));
c = c/max(c(:));

imshow(c,<span class="string">'InitialMagnification'</span>,200)
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/steve/2013/default_image_again_03.png" alt=""> <p>Thanks for the suggestions, Cleve!</p><p style="text-align:right;font-size:xx-small;font-weight:lighter;font-style:italic;color:gray;"><br /><a rel="nofollow"><span style="font-size:x-small;font-style:italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><img src="http://feeds.feedburner.com/~r/SteveOnImageProcessing/~4/RcXYG0kN6v4" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
      <item>
         <title>Giving by Taking: File Exchange Acknowledgment Trees</title>
         <link>http://feedproxy.google.com/~r/mathworks/desktop/~3/WNc6_QSbheI/</link>
         <description>One of the virtues of a good programmer (as observed by Larry Wall) is laziness. Don&amp;#8217;t write code that you don&amp;#8217;t have to! In this spirit, the File Exchange is a boon to the lazy. Whenever you sit down to code, listen to the voice that says &amp;#8220;someone must have written this already.&amp;#8221; Because it&amp;#8217;s [...]</description>
         <guid isPermaLink="false">http://blogs.mathworks.com/community/?p=2015</guid>
         <pubDate>Tue, 15 Jan 2013 20:20:27 +0000</pubDate>
         <content:encoded><![CDATA[<p>One of the virtues of a good programmer (as <a rel="nofollow" target="_blank" href="http://c2.com/cgi/wiki?LazinessImpatienceHubris">observed by Larry Wall</a>) is <em>laziness</em>. Don&#8217;t write code that you don&#8217;t have to! In this spirit, the File Exchange is a boon to the lazy. Whenever you sit down to code, listen to the voice that says &#8220;someone <em>must</em> have written this already.&#8221; Because it&#8217;s probably good advice. Sometimes you&#8217;ll find exactly what you need on the File Exchange. Done! Other times you might find something that&#8217;s <em>close</em> to the right thing, but not quite. In those cases, consider taking what you find and adapting it to your needs&#8230; and then consider resubmitting your adapted code to the File Exchange.</p>
<p>It may feel like cheating at first, but the File Exchange has a mechanism to let you acknowledge the person (or people) that you borrowed code from.</p>
<p>When you submit a file to the File Exchange, you come across a section called &#8220;License and Acknowledgments.&#8221; This gives you a place to mention the other files that helped you create yours, either because you borrowed code from them or because you just want to publicly acknowledge your appreciation of their influence.</p>
<p><img class="alignnone size-full wp-image-2017" title="fx-ack" src="http://blogs.mathworks.com/community/files/fx-ack.png" alt="" width="537" height="156"/></p>
<p>Here&#8217;s an example. When <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/22680">Douglas Schwarz</a> wrote his highly regarded <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/11837">Fast and Robust Curve Intersections</a>, he made sure to acknowledge the pre-existing file <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/8908">Curve Intersect 2</a> by <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/15000">Sebastian Hölz</a>. We&#8217;ve had this feature in place for many years, and I decided it was time to take a look at the patterns of attribution that we see.</p>
<p>Of the more than 17,000 files on the File Exchange, there are 2910 separate acknowledgments like the one mentioned above. In one way or another, 2050 files acknowledge their debt to a total of 1870 inspiring files. If you think of each one of these acknowledgments as a pointer from the inspiring file to the inspired file, then the whole site can be thought of as a <a rel="nofollow" target="_blank" href="http://en.wikipedia.org/wiki/Directed_graph">directed graph</a>. Consider the example above. The inspiration doesn&#8217;t stop with Douglas Schwarz&#8217;s file. That one went on to inspire others. Here&#8217;s a look at the acknowledgment tree.</p>
<p><img class="alignnone size-full wp-image-2029" title="acktree_8908" src="http://blogs.mathworks.com/community/files/acktree_8908.png" alt="" width="511" height="290"/></p>
<p>In this picture, each box is a different submission labeled with the author&#8217;s last name. Isn&#8217;t that lovely? It&#8217;s exciting to see the &#8220;footprints&#8221; of good ideas as they move through the site.</p>
<p>These patterns of acknowledgment can be extensive and visually striking. Some of the trees are deep and some are wide. Here&#8217;s a wide one that starts with Oliver Woodford&#8217;s <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig">exportfig</a>.</p>
<p><img class="alignnone size-full wp-image-2031" title="acktree_23629" src="http://blogs.mathworks.com/community/files/acktree_23629.png" alt="" width="600" height="78"/></p>
<p>With our link data, we can figure out which is the single most influential file in terms of link count. And the answer is&#8230; <a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/69">one of the oldest files on the site</a> from Christophe Couvreur. Take a look at how wide this one is.</p>
<p><img class="alignnone size-full wp-image-2033" title="acktree_69" src="http://blogs.mathworks.com/community/files/acktree_69.png" alt="" width="600" height="53"/></p>
<p>The largest fully-connected subnet of files has over 200 files in it, all of them connected to each other through a series of links, each link a thoughtful token of respect.</p>
<p>If we go from a file-centric to an author-centric view, we can determine the most influential authors. Who has the most acknowledgments considering all the files they submitted (we ignore self-linking for this analysis). In other words, which authors are the most influential?</p>
<ol>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/679">John D&#8217;Errico</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/1034">Christophe COUVREUR</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">Yair Altman</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/10584">Jos</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/3777">Scott Hirsch</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/22524">Yi Cao</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/120528">Robert Bemis</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/22680">Douglas Schwarz</a></li>
<li><a rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/29180">Dirk-Jan Kroon</a></li>
</ol>
<p>These people are heroes of the MATLAB Community. They have freely given, and we have all benefited.</p>
<p>I want to see your name on this list!</p>
<p>Let&#8217;s say you agree. Let&#8217;s say you&#8217;re ready to let people start building on your code. How do you start? Paradoxically, a good way to start is by borrowing someone else&#8217;s code. You&#8217;ll learn good coding practices by borrowing from the best, and you&#8217;re likelier to build something worth borrowing by standing on the shoulders of others. You&#8217;ll also be bound more deeply into the community. And soon you&#8217;ll see how satisfying it is to have someone use your code as a springboard for something wonderful that never would have occurred to you. So give by taking. You&#8217;ll be surprised how far it gets you.</p>
<img src="http://feeds.feedburner.com/~r/mathworks/desktop/~4/WNc6_QSbheI" height="1" width="1"/>]]></content:encoded>
         <category>Uncategorized</category>
      </item>
   </channel>
</rss>
<!-- fe1.yql.bf1.yahoo.com compressed/chunked Tue Jun 18 04:53:46 UTC 2013 -->
