<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.1" --><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Loren on the Art of MATLAB</title>
	<link>http://blogs.mathworks.com/loren</link>
	<description>Loren Shure  works on design of the MATLAB language at &lt;a href="http://www.mathworks.com/"&gt;The MathWorks&lt;/a&gt;. She writes here about once a week on MATLAB programming and related topics. &lt;br&gt;&lt;br&gt;&lt;a href="/images/loren-full.jpg"&gt;&lt;img src="/images/loren.jpg"&gt;&lt;/a&gt;</description>
	<pubDate>Thu, 19 Nov 2009 21:34:57 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Coordinating Zero Removals from Multiple Arrays</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/bmya0EQb9sw/</link>
		<comments>http://blogs.mathworks.com/loren/2009/11/19/coordinating-zero-removals-from-multiple-arrays/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 21:34:57 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Indexing]]></category>

		<category><![CDATA[Vectorization]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/11/19/coordinating-zero-removals-from-multiple-arrays/</guid>
		<description><![CDATA[
   
      I've fielded some questions recently about how to coordinate multiple arrays changing simultaneously.  One example is removing
         elements for two arrays in the case where either array holds a zero for the location. This is a good [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I've fielded some questions recently about how to coordinate multiple arrays changing simultaneously.  One example is removing
         elements for two arrays in the case where either array holds a zero for the location. This is a good opportunity to reiterate
         the use of logical arrays and some useful associated functions (such as <tt>any</tt> and <tt>all</tt>).
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Identify Pairs to Remove</a></li>
         <li><a href="#3">First Algorithm</a></li>
         <li><a href="#5">Second Algorithm</a></li>
         <li><a href="#7">Always Tradeoffs</a></li>
      </ul>
   </div>
   <h3>Identify Pairs to Remove<a name="1"></a></h3>
   <p>Let's say I have 2 arrays</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">a = [ 1  4  9  0 25  0 49  0]
b = [ 1  0  3  0  0  6  7  8]</pre><pre style="font-style:oblique">a =
     1     4     9     0    25     0    49     0
b =
     1     0     3     0     0     6     7     8
</pre><p>and I would like to delete the corresponding elements in <tt>a</tt> and <tt>b</tt> when either of them contains a zero value.
   </p>
   <h3>First Algorithm<a name="3"></a></h3>
   <p>There are several possible algorithms, each with their own trade-offs. Here's the first one.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">anyzero = any([a;b] == 0)
a(anyzero) = []
b(anyzero) = []</pre><pre style="font-style:oblique">anyzero =
     0     1     0     1     1     1     0     1
a =
     1     9    49
b =
     1     3     7
</pre><p>This algorithm combines the two arrays into one, a potentially costly move if the arrays are large.  Then check for values
      that equal zero.  And finally, check columnwise, using the function <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/any.html"><tt>any</tt></a>, to identify the columns that have at least one zero.  Finally, use this array of logical indices to delete the appropriate
      elements of <tt>a</tt> and <tt>b</tt>.
   </p>
   <h3>Second Algorithm<a name="5"></a></h3>
   <p>This algorithm (courtesy of Mirek L. in <a href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/263299">this post</a> doesn't suffer from combining the two arrays.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">x1 = a(a.*b ~= 0)
y1 = b(a.*b ~= 0)</pre><pre style="font-style:oblique">x1 =
     1     9    49
y1 =
     1     3     7
</pre><p>But it calculates the same temporary array twice (and it's the size of one of the vectors).  To be able to recalculate the
      temporary array this way, I can't overwrite the initial arrays as you see in the first algorithm.  And finally, is there is
      a <tt>NaN</tt> or <tt>Inf</tt> corresponding to a <tt>0</tt>, this algorithm won't find it.
   </p>
   <h3>Always Tradeoffs<a name="7"></a></h3>
   <p>There are always tradeoffs to make like the ones I mention here, at least when I program.  How do <b>you</b> choose which tradeoffs to make?  Which one would you choose here? Or would you choose an entirely different algorithm (which
      I hope you'll post).  Let us know <a href="http://blogs.mathworks/com/loren/?p=206#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_56a53b98f587445dab291e6d53aaed03() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='56a53b98f587445dab291e6d53aaed03 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 56a53b98f587445dab291e6d53aaed03';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_56a53b98f587445dab291e6d53aaed03()"><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; 7.9<br /></p>
</div>
<!--
56a53b98f587445dab291e6d53aaed03 ##### SOURCE BEGIN #####
%% Coordinating Zero Removals from Multiple Arrays
% I've fielded some questions recently about how to coordinate multiple
% arrays changing simultaneously.  One example is removing elements for two
% arrays in the case where either array holds a zero for the location.
% This is a good opportunity to reiterate the use of logical arrays and
% some useful associated functions (such as |any| and |all|).


%% Identify Pairs to Remove
% Let's say I have 2 arrays
a = [ 1  4  9  0 25  0 49  0]
b = [ 1  0  3  0  0  6  7  8]
%%
% and I would like to delete the corresponding elements in |a| and |b| when
% either of them contains a zero value.
%% First Algorithm
% There are several possible algorithms, each with their own trade-offs.
% Here's the first one.
anyzero = any([a;b] == 0)
a(anyzero) = []
b(anyzero) = []
%%
% This algorithm combines the two arrays into one, a potentially costly move
% if the arrays are large.  Then check for values that equal zero.  And
% finally, check columnwise, using the function 
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/any.html |any|>,
% to identify the columns that have at least one zero.  Finally, use this
% array of logical indices to delete the appropriate elements of |a| and
% |b|.
%% Second Algorithm
% This algorithm (courtesy of Mirek L. in
% <http://www.mathworks.com/matlabcentral/newsreader/view_thread/263299 this post>
% doesn't suffer from combining the two arrays. 
x1 = a(a.*b ~= 0)
y1 = b(a.*b ~= 0)
%%
% But it calculates the same temporary array twice (and it's the size of
% one of the vectors).  To be able to recalculate the temporary
% array this way, I can't overwrite the initial arrays as you see in the
% first algorithm.  And finally, is there is a |NaN| or |Inf| corresponding
% to a |0|, this algorithm won't find it.
%% Always Tradeoffs
% There are always tradeoffs to make like the ones I mention here, at least
% when I program.  How do *you* choose which tradeoffs to make?  Which one
% would you choose here? Or would you choose an entirely different
% algorithm (which I hope you'll post).  Let us know
% <http://blogs.mathworks/com/loren/?p=206#respond here>.

##### SOURCE END ##### 56a53b98f587445dab291e6d53aaed03
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/bmya0EQb9sw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/11/19/coordinating-zero-removals-from-multiple-arrays/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/11/19/coordinating-zero-removals-from-multiple-arrays/</feedburner:origLink></item>
		<item>
		<title>Empty Arrays with Flow of Control and Logical Operators</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/o75L3fJJypY/</link>
		<comments>http://blogs.mathworks.com/loren/2009/11/12/empty-arrays-with-flow-of-control-and-logical-operators/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:54:54 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Robustness]]></category>

		<category><![CDATA[empty arrays]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/11/12/empty-arrays-with-flow-of-control-and-logical-operators/</guid>
		<description><![CDATA[
   
      After reading last week's post on calculating with empty arrays, one of my colleagues mentioned some other behaviors with empty arrays that have tripped
         him up in the past. Today I will discuss how empty arrays work in [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>After reading <a href="http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/">last week's post</a> on calculating with empty arrays, one of my colleagues mentioned some other behaviors with empty arrays that have tripped
         him up in the past. Today I will discuss how empty arrays work in the contexts of flow of control expressions (both conditional
         and looping, i.e., <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html"><tt>if</tt></a> and <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/while.html"><tt>while</tt></a>) and short-circuit operators (i.e., <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorsshortcircuit.html">&amp;&amp; and | |</a>).
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Empty Arrays in Flow of Control</a></li>
         <li><a href="#6">Empty Arrays with Logical Operators</a></li>
         <li><a href="#8">Short-circuit Logical Operators (| | and &amp;&amp;)</a></li>
         <li><a href="#11">Examples</a></li>
         <li><a href="#20">References</a></li>
         <li><a href="#21">Empty Thoughts?</a></li>
      </ul>
   </div>
   <h3>Empty Arrays in Flow of Control<a name="1"></a></h3>
   <p>Let me first start with plain empty arrays in flow of control situations. For example, what will this code do?</p><pre>    E = [];
    if E
       disp('Empty is true')
    else
       disp('Empty is false')
    end</pre><p>Readers who remember my comment on last week's blog will correctly guess that the empty expression for the <tt>if</tt> statement is treated as <tt>false</tt>. Why?  The way I think about it is this.  If I am looking for locations of some condition in an array, and I don't find them,
      I end up with an empty output.  This very output is the kind of expression I am likely to want to use, somehow, in an <tt>if</tt> statement.  Let's try it to be sure.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">E = [];
<span style="color: #0000FF">if</span> E
    disp(<span style="color: #A020F0">'Empty is true'</span>)
<span style="color: #0000FF">else</span>
    disp(<span style="color: #A020F0">'Empty is false'</span>)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Empty is false
</pre><p>The situation gets a bit more complicated if there is a logical expression for the <tt>if</tt> or <tt>while</tt> statement that has an empty array as one of its elements.  Let me show you what I mean.  Paraphrasing the documentation,
   </p><pre> There are some conditions however under which while evaluates as true
 on an empty array. Two examples of this are</pre><pre>                  A = [];
                  while all(A), doSomething, end
                  while 1|A, doSomething, end</pre><p>Let's see what's going on in each of these examples.  In the first one, the function <tt>all</tt> is being called with an empty input.  According to the second reference below (on empty arrays), the function <tt>all</tt> is one of the functions that returns a nonzero value for empty input.  Let's see.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">allE = all(E)
allEislogical = islogical(allE)</pre><pre style="font-style:oblique">allE =
     1
allEislogical =
     1
</pre><p>The way I think about this is that there are no <tt>false</tt> values in <tt>E</tt>, hence the <tt>true</tt> result.
   </p>
   <h3>Empty Arrays with Logical Operators<a name="6"></a></h3>
   <p>The second expression involves an elementwise logical operator ( | ).  In this case, the first part of the expression, <tt>1</tt>, is true, so the second part, after the elementwise <tt>or</tt>, is never evaluated. So the fact that an empty result returns <tt>false</tt> never comes into play here. Why?  Because &amp; and | operators short-circuit <i>when and only when they are in the context of <tt>if</tt> or <tt>while</tt> expressions</i>.  Otherwise, the elementwise operators do <b>not</b> short-circuit.
   </p>
   <p>In contrast, the logical operators, &amp;&amp; and | |, always short-circuit, regardless of context.</p>
   <h3>Short-circuit Logical Operators (| | and &amp;&amp;)<a name="8"></a></h3>
   <p>The next important idea to remember is that the short-circuit logical operators expect scalars as the inputs for the expressions.
       This means that an empty array, not being a scalar, may cause you some grief if you are unprepared for that situation.  Let
      me show you what I mean.  Compare the following 2 code snippets.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">true || E</pre><pre style="font-style:oblique">ans =
     1
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">try</span>
    E || true
<span style="color: #0000FF">catch</span> ME
    disp(ME.message)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Operands to the || and &amp;&amp; operators must be convertible to logical scalar values.
</pre><p>In the second snippet, the expression                E || true</p>
   <p>produced an error, because E isn't a scalar value.  Once the error occurs, the second operand is never evaluated.  Contrast
      that with the snippet, where the first input evaluates to <tt>true</tt>.  Short-circuiting then takes over and the second operand, which would cause an error in this context, is never evaluated.
   </p>
   <h3>Examples<a name="11"></a></h3>
   <p>Here are a few more code examples to help you see the patterns.  Try to figure out the answers before reading the results.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">if</span> []
    disp(<span style="color: #A020F0">'hello'</span>)
<span style="color: #0000FF">else</span>
    disp(<span style="color: #A020F0">'bye'</span>)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">bye
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">true | []</pre><pre style="font-style:oblique">ans =
     []
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">[] | true</pre><pre style="font-style:oblique">ans =
     []
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">true || []</pre><pre style="font-style:oblique">ans =
     1
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">try</span>
    [] || true
<span style="color: #0000FF">catch</span> ME
    disp(ME.message)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Operands to the || and &amp;&amp; operators must be convertible to logical scalar values.
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">if</span> true | []
    disp(<span style="color: #A020F0">'hello'</span>)
<span style="color: #0000FF">else</span>
    disp(<span style="color: #A020F0">'bye'</span>)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">hello
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">if</span> [] | true
    disp(<span style="color: #A020F0">'hello'</span>)
<span style="color: #0000FF">else</span>
    disp(<span style="color: #A020F0">'bye'</span>)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">bye
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">if</span> true || []
    disp(<span style="color: #A020F0">'hello'</span>)
<span style="color: #0000FF">else</span>
    disp(<span style="color: #A020F0">'bye'</span>)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">hello
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">try</span>
    <span style="color: #0000FF">if</span> [] || true
        disp(<span style="color: #A020F0">'hello'</span>)
    <span style="color: #0000FF">else</span>
        disp(<span style="color: #A020F0">'bye'</span>)
    <span style="color: #0000FF">end</span>
<span style="color: #0000FF">catch</span> ME
    disp(ME.message)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Operands to the || and &amp;&amp; operators must be convertible to logical scalar values.
</pre><h3>References<a name="20"></a></h3>
   <p>Here are a bunch of references to the MATLAB documentation where all of this information is covered.</p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brqy1c1-1.html">Program Control Statements</a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-86359.html#f1-86384">Empty Matrices, Scalars, and Vectors</a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/while.html">while statements</a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html">if statements</a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorselementwise.html">Elementwise Logical Operators</a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorsshortcircuit.html">Short-circuit Logical Operators</a></li>
      </ul>
   </div>
   <h3>Empty Thoughts?<a name="21"></a></h3>
   <p>The behaviors with empties in MATLAB are, I believe, consistent and useful. Nonetheless, the behaviors have lots of details
      to master and can be confusing. If you have any thoughts on the matter, please respond <a href="http://blogs.mathworks.com/loren/?p=205#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_2dc14d48f43d4c9abf0452554923c38a() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='2dc14d48f43d4c9abf0452554923c38a ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 2dc14d48f43d4c9abf0452554923c38a';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_2dc14d48f43d4c9abf0452554923c38a()"><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; 7.9<br /></p>
</div>
<!--
2dc14d48f43d4c9abf0452554923c38a ##### SOURCE BEGIN #####
%% Empty Arrays with Flow of Control and Logical Operators
% After reading
% <http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/ last week's post>
% on calculating with empty arrays, one of my colleagues mentioned some
% other behaviors with empty arrays that have tripped him up in the past.
% Today I will discuss how empty arrays work in the contexts of flow of 
% control expressions (both conditional and looping, i.e.,  
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html |if|> 
% and <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/while.html |while|>)
% and short-circuit operators (i.e.,
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorsshortcircuit.html &#038;& and | |>).
%% Empty Arrays in Flow of Control
% Let me first start with plain empty arrays in flow of control situations.
% For example, what will this code do?
%
%      E = [];
%      if E
%         disp('Empty is true')
%      else
%         disp('Empty is false')
%      end
%
%%
% Readers who remember my comment on last week's blog will correctly guess
% that the empty expression for the |if| statement is treated as |false|.
% Why?  The way I think about it is this.  If I am looking for locations of
% some condition in an array, and I don't find them, I end up with an empty
% output.  This very output is the kind of expression I am likely to want
% to use, somehow, in an |if| statement.  Let's try it to be sure.
E = [];
if E
    disp('Empty is true')
else
    disp('Empty is false')
end
%% 
% The situation gets a bit more complicated if there is a logical
% expression for the |if| or |while| statement that has an empty array as
% one of its elements.  Let me show you what I mean.  Paraphrasing the
% documentation,
%
%   There are some conditions however under which while evaluates as true
%   on an empty array. Two examples of this are
%
%                    A = [];
%                    while all(A), doSomething, end
%                    while 1|A, doSomething, end
%%
% Let's see what's going on in each of these examples.  In the first one,
% the function |all| is being called with an empty input.  According to the
% second reference below (on empty arrays), the function |all| is one of
% the functions that returns a nonzero value for empty input.  Let's see.
allE = all(E)
allEislogical = islogical(allE)
%%
% The way I think about this is that there are no |false| values in |E|,
% hence the |true| result.
%% Empty Arrays with Logical Operators
% The second expression involves an elementwise logical operator ( | ).  In
% this case, the first part of the expression, |1|, is true, so the second
% part, after the elementwise |or|, is never evaluated. So the fact that an
% empty result returns |false| never comes into play here.
% Why?  Because &#038; and | operators
% short-circuit _when and only when they are in the context of |if| or 
% |while| expressions_.  Otherwise, the elementwise operators do *not*
% short-circuit.
%%
% In contrast, the logical operators, &#038;& and | |, always short-circuit,
% regardless of context.
%% Short-circuit Logical Operators (| | and &#038;&)
% The next important idea to remember is that the short-circuit logical
% operators expect scalars as the inputs for the expressions.  This means
% that an empty array, not being a scalar, may cause you some grief if you
% are unprepared for that situation.  Let me show you what I mean.  Compare
% the following 2 code snippets.
true || E
%%
try
    E || true
catch ME
    disp(ME.message)
end
%%
% In the second snippet, the expression
%                E || true
%
% produced an error, because E isn't a scalar value.  Once the error
% occurs, the second operand is never evaluated.  Contrast that with the
% snippet, where the first input evaluates to |true|.  Short-circuiting
% then takes over and the second operand, which would cause an error in
% this context, is never evaluated.
%% Examples
% Here are a few more code examples to help you see the patterns.  Try to
% figure out the answers before reading the results.
if []
    disp('hello')
else
    disp('bye')
end

%%
true | []
%%
[] | true
%%
true || []
%%
try
    [] || true
catch ME
    disp(ME.message)
end
%%
if true | []
    disp('hello')
else
    disp('bye')
end
%%
if [] | true
    disp('hello')
else
    disp('bye')
end
%%
if true || []
    disp('hello')
else
    disp('bye')
end
%%
try 
    if [] || true
        disp('hello')
    else
        disp('bye')
    end
catch ME
    disp(ME.message)
end
%% References
% Here are a bunch of references to the MATLAB documentation where all of
% this information is covered.
%
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brqy1c1-1.html Program Control Statements>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-86359.html#f1-86384 Empty Matrices, Scalars, and Vectors>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/while.html while statements>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html if statements>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorselementwise.html Elementwise Logical Operators>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logicaloperatorsshortcircuit.html Short-circuit Logical Operators>
%

%% Empty Thoughts?
% The behaviors with empties in MATLAB are, I believe, consistent and useful.
% Nonetheless, the behaviors have lots of details to master and can be
% confusing. If you have any thoughts on the matter, please respond
% <http://blogs.mathworks.com/loren/?p=205#respond here>.
##### SOURCE END ##### 2dc14d48f43d4c9abf0452554923c38a
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/o75L3fJJypY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/11/12/empty-arrays-with-flow-of-control-and-logical-operators/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/11/12/empty-arrays-with-flow-of-control-and-logical-operators/</feedburner:origLink></item>
		<item>
		<title>Calculus with Empty Arrays</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/3OCpt7t-shs/</link>
		<comments>http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 19:30:53 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Less Used Functionality]]></category>

		<category><![CDATA[Robustness]]></category>

		<category><![CDATA[Vectorization]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/</guid>
		<description><![CDATA[
   
      MATLAB has had empty arrays since before I started using the program. When I started, the only size empty array was 0x0.  When version 5 was released, empty arrays came along for the N-dimensional ride and got more shapely.
      
 [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>MATLAB has had empty arrays since before I started using the program. When I started, the only size empty array was <tt>0x0</tt>.  When version 5 was released, empty arrays came along for the N-dimensional ride and got more shapely.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#2">From the Newsgroup</a></li>
         <li><a href="#4">Dimensions Matter in MATLAB</a></li>
         <li><a href="#11">Empty Array Shapes</a></li>
         <li><a href="#12">Reference</a></li>
         <li><a href="#13">Got an Empty Question?</a></li>
      </ul>
   </div>
   <p>Even relatively simple expressions involving empty arrays cause confusion from time to time, especially in concert with other
      rules in MATLAB (such as <tt>NaN</tt> values usually propagate from inputs to outputs).  Let's play around a little with some empty arrays to get some insight.
   </p>
   <h3>From the Newsgroup<a name="2"></a></h3>
   <p>This <a href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/263290#687525">post</a> on the MATLAB newsgroup motivated me to talk about empty arrays.  Here's is an excerpt from the original post:
   </p><pre> I knew that Nan+4 = NaN, but why is []+4 = [] ? Is there more 'black hole
 behaviour' I should know about?</pre><h3>Dimensions Matter in MATLAB<a name="4"></a></h3>
   <p>Dimensions matter in MATLAB and you will get error messages when dimensions don't agree.  Early on, we found it was convenient
      to treat scalars as an exception with operators (e.g., <tt><b>,.</b></tt>) and to treat them as if they were expanded to the size of the other operand.  So
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">rand(3,3) + pi</pre><pre style="font-style:oblique">ans =
          4.10648118878907          4.09875960183274          3.28347899221701
          3.29920573526734          3.62696830231263          3.56335393621607
          4.11218543535041          3.94187312247859          4.05732817877886
</pre><p>adds the value <tt>pi</tt> to the random <tt>3x3</tt> just created.  It's as if a <tt>3x3</tt> constant array filled with the value <tt>pi</tt> was created and added elementwise to the other array.
   </p>
   <p>So what does that mean for an empty operand?  Its size has at least one 0 value.  So MATLAB expands <tt>pi</tt> in this expression <tt>[] + pi</tt> to be the same size as <tt>[]</tt> (which happens to be <tt>0x0</tt> here).  When that happens, MATLAB creates a second empty array, and then adds the two empty arrays. Hence we get
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">[] + pi</pre><pre style="font-style:oblique">ans =
     []
</pre><p>returing an empty output.</p>
   <p>MATLAB applies the scalar expansion rule to operators.  So, for example, <i>size(anything+scalar)</i> is <i>size(anything)</i>.  As a logical but sometimes surprising consequence, empty arrays often (but not always) propagate through calculations.
       When doesn't that happen?  With some functions where mathematically logical analysis demands different results.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">sum([])</pre><pre style="font-style:oblique">ans =
     0
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">prod([])</pre><pre style="font-style:oblique">ans =
     1
</pre><p>So, why is the sum zero and the product 1?  Because they are the identity elements (as in group theory) for sum and product
      respectively.  Think about how to start the computation for a sum or a product and how you would initialize the first value.
       That's the value given before adding or multiplying any of the array elements, hence the values 0 and 1 respectively.
   </p>
   <h3>Empty Array Shapes<a name="11"></a></h3>
   <p>Empty arrays can be N-dimensional, and don't need all dimensions to be 0. However, they still must obey the rules about dimensions
      needing to agree.  There are consequences that may surprise you, but they do follow logically.  Here's an example of trying
      to add two empty arrays, ending up in an error!
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">a = zeros(0,1)
b = zeros(1,0)
<span style="color: #0000FF">try</span>
    a+b
<span style="color: #0000FF">catch</span> MEplus
    fprintf(<span style="color: #A020F0">'\n'</span>)
    disp(MEplus.message)
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">a =
   Empty matrix: 0-by-1
b =
   Empty matrix: 1-by-0

Matrix dimensions must agree.
</pre><h3>Reference<a name="12"></a></h3>
   <p>For more information about empty arrays, check out <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-86359.html#f1-86384">this page</a> in the documentation.
   </p>
   <h3>Got an Empty Question?<a name="13"></a></h3>
   <p>Got any empty questions (really, questions about empty!)?  Or comments? Post them <a href="http://blogs.mathworks.com/loren/?p=204#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_99a0320200324b5cac73992d594d08c9() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='99a0320200324b5cac73992d594d08c9 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 99a0320200324b5cac73992d594d08c9';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_99a0320200324b5cac73992d594d08c9()"><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; 7.9<br /></p>
</div>
<!--
99a0320200324b5cac73992d594d08c9 ##### SOURCE BEGIN #####
%% Calculus with Empty Arrays
% MATLAB has had empty arrays since before I started using the program.
% When I started, the only size empty array was |0x0|.  When
% version 5 was released, empty arrays came along for the N-dimensional
% ride and got more shapely.
%%
% Even relatively simple expressions involving
% empty arrays cause confusion from time to time, especially in concert
% with other rules in MATLAB (such as |NaN| values usually propagate from
% inputs to outputs).  Let's play around a little with some empty arrays to
% get some insight.

%% From the Newsgroup
% This <http://www.mathworks.com/matlabcentral/newsreader/view_thread/263290#687525 post>
% on the MATLAB newsgroup motivated me to talk about empty arrays.  Here's
% is an excerpt from the original post:
%%
% 
%   I knew that Nan+4 = NaN, but why is []+4 = [] ? Is there more 'black hole 
%   behaviour' I should know about?
%% Dimensions Matter in MATLAB
% Dimensions matter in MATLAB and you will get error messages when
% dimensions don't agree.  Early on, we found it was convenient to treat
% scalars as an exception with operators (e.g., |*,.*|) and to treat them
% as if they were expanded to the size of the other operand.  So
rand(3,3) + pi
%%
% adds the value |pi| to the random |3x3| just created.  It's as if a |3x3|
% constant array filled with the value |pi| was created and added
% elementwise to the other array.
%%
% So what does that mean for an empty operand?  Its size has at least one
% 0 value.  So MATLAB expands |pi| in this expression |[] + pi| to be the
% same size as |[]| (which happens to be |0x0| here).  When that happens,
% MATLAB creates a second empty array, and then adds the two empty arrays.
% Hence we get
[] + pi
%%
% returing an empty output.
%%
% MATLAB applies the scalar expansion rule to operators.  So, for example,
% _size(anything+scalar)_ is _size(anything)_.  As a logical but sometimes
% surprising consequence, empty arrays often (but not always) propagate
% through calculations.  When doesn't that happen?  With some functions
% where mathematically logical analysis demands different results.
sum([])
%%
prod([])
%%
% So, why is the sum zero and the product 1?  Because they are the identity
% elements (as in group theory) for sum and product respectively.  Think
% about how to start the computation for a sum or a product and how you
% would initialize the first value.  That's the value given before adding
% or multiplying any of the array elements, hence the values 0 and 1
% respectively.
%% Empty Array Shapes
% Empty arrays can be N-dimensional, and don't need all dimensions to be 0.
% However, they still must obey the rules about dimensions needing to
% agree.  There are consequences that may surprise you, but they do follow
% logically.  Here's an example of trying to add two empty arrays, ending
% up in an error!
a = zeros(0,1)
b = zeros(1,0)
try
    a+b
catch MEplus
    fprintf('\n')
    disp(MEplus.message)
end
%% Reference
% For more information about empty arrays, check out
% <http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-86359.html#f1-86384 this page>
% in the documentation.
%% Got an Empty Question?
% Got any empty questions (really, questions about empty!)?  Or comments?
% Post them <http://blogs.mathworks.com/loren/?p=204#respond here>.


##### SOURCE END ##### 99a0320200324b5cac73992d594d08c9
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/3OCpt7t-shs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/11/04/calculus-with-empty-arrays/</feedburner:origLink></item>
		<item>
		<title>Dealing with Cells</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/QrCrw0BpPHk/</link>
		<comments>http://blogs.mathworks.com/loren/2009/10/21/dealing-with-cells/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 17:53:32 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Cell Arrays]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/10/21/dealing-with-cells/</guid>
		<description><![CDATA[
   
      A customer recently asked me this question at the MATLAB Virtual Conference.
      
   
   Contents
   
      
         Question about Summing Cell Rows
 [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>A customer recently asked me this question at the <a href="http://events.unisfair.com/rt/matlab~virtualconf?code=hp-listing">MATLAB Virtual Conference</a>.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Question about Summing Cell Rows</a></li>
         <li><a href="#2">Example</a></li>
         <li><a href="#3">Answer</a></li>
         <li><a href="#8">Cell Array Questions</a></li>
      </ul>
   </div>
   <h3>Question about Summing Cell Rows<a name="1"></a></h3><pre>  I was hoping you would cover cells some day. Here is a particular
  problem I was hoping to have a more elegant solutions for.</pre><pre>  A is a cell that has String (say names) in the first column, Numbers
  (say scores in tests 1 and 2) in the next two columns. Assume that each
  cell has only one value. Is there an easier way to calculate, say the
  sum of the two test scores than a for loop?</pre><h3>Example<a name="2"></a></h3>
   <p>Let's make some sample data.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">c(1:4,1) = {<span style="color: #A020F0">'Fred'</span> <span style="color: #A020F0">'Alice'</span> <span style="color: #A020F0">'Lucy'</span> <span style="color: #A020F0">'Tom'</span>};
c(1:4,2) = { 90  80  55 102 };
c(1:4,3) = { 43  91  80  44 }</pre><pre style="font-style:oblique">c = 
    'Fred'     [ 90]    [43]
    'Alice'    [ 80]    [91]
    'Lucy'     [ 55]    [80]
    'Tom'      [102]    [44]
</pre><h3>Answer<a name="3"></a></h3>
   <p>To sum the entries in a row for this <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-98.html"><tt>cell array</tt></a>, I can simply turn the numeric values into a numeric array via comma-separated list notation, and then sum the rows.  Let's
      see the pieces for clarity.  Here's the comma-separated list.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">c{:,2:3}</pre><pre style="font-style:oblique">ans =
    90
ans =
    80
ans =
    55
ans =
   102
ans =
    43
ans =
    91
ans =
    80
ans =
    44
</pre><p>Now place the results into a vector.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">vec = [c{:,2:3}]</pre><pre style="font-style:oblique">vec =
    90    80    55   102    43    91    80    44
</pre><p>Reshape the vector appropriately into a matrix.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">array = reshape(vec,[],2)</pre><pre style="font-style:oblique">array =
    90    43
    80    91
    55    80
   102    44
</pre><p>Now sum the results along the rows.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tot = sum(array,2)</pre><pre style="font-style:oblique">tot =
   133
   171
   135
   146
</pre><p>Or, in one bigger statement, try this.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tot = sum(reshape([c{:,2:3}],[],2),2)</pre><pre style="font-style:oblique">tot =
   133
   171
   135
   146
</pre><h3>Cell Array Questions<a name="8"></a></h3>
   <p>Do you use cell arrays?  Can you do what you want without undo contortions?  Let me know <a href="http://blogs.mathworks.com/loren/?p=203#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_6f695f938464405ea30ed8125cd1b1ef() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='6f695f938464405ea30ed8125cd1b1ef ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 6f695f938464405ea30ed8125cd1b1ef';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_6f695f938464405ea30ed8125cd1b1ef()"><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; 7.9<br /></p>
</div>
<!--
6f695f938464405ea30ed8125cd1b1ef ##### SOURCE BEGIN #####
%% Dealing with Cells
% A customer recently asked me this question at the 
% <http://events.unisfair.com/rt/matlab~virtualconf?code=hp-listing MATLAB Virtual Conference>.
%
%% Question about Summing Cell Rows
%    I was hoping you would cover cells some day. Here is a particular
%    problem I was hoping to have a more elegant solutions for. 
%
%    A is a cell that has String (say names) in the first column, Numbers
%    (say scores in tests 1 and 2) in the next two columns. Assume that each
%    cell has only one value. Is there an easier way to calculate, say the
%    sum of the two test scores than a for loop?
%% Example
% Let's make some sample data.
c(1:4,1) = {'Fred' 'Alice' 'Lucy' 'Tom'};
c(1:4,2) = { 90  80  55 102 };
c(1:4,3) = { 43  91  80  44 }
%% Answer
% To sum the entries in a row for this 
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-98.html |cell array|>, 
% I can simply turn the numeric values into a numeric array
% via comma-separated list notation, and then sum the rows.  Let's see
% the pieces for clarity.  Here's the comma-separated list.
c{:,2:3}
%%
% Now place the results into a vector.
vec = [c{:,2:3}]
%%
% Reshape the vector appropriately into a matrix.
array = reshape(vec,[],2)
%%
% Now sum the results along the rows.
tot = sum(array,2)
%%
% Or, in one bigger statement, try this.
tot = sum(reshape([c{:,2:3}],[],2),2)

%% Cell Array Questions
% Do you use cell arrays?  Can you do what you want without undo
% contortions?  Let me know
% <http://blogs.mathworks.com/loren/?p=203#respond here>.

##### SOURCE END ##### 6f695f938464405ea30ed8125cd1b1ef
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/QrCrw0BpPHk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/10/21/dealing-with-cells/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/10/21/dealing-with-cells/</feedburner:origLink></item>
		<item>
		<title>Concatenating structs</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/vZ95fGBo-JQ/</link>
		<comments>http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 18:18:06 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Structures]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/</guid>
		<description><![CDATA[
   
      From time to time, I get asked or see queries about how to concatenate two struct arrays to merge the fields.  There's even a section in the documentation covering this topic. I thought I'd show it here to help people out.
     [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>From time to time, I get asked or see queries about how to concatenate two <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/struct.html"><tt>struct</tt></a> arrays to merge the fields.  There's even a section in the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-38.html#br04bw6-78">documentation</a> covering this topic. I thought I'd show it here to help people out.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Example Data</a></li>
         <li><a href="#10">mergeStruct</a></li>
         <li><a href="#11">Do You Need to Merge struct data?</a></li>
      </ul>
   </div>
   <h3>Example Data<a name="1"></a></h3>
   <p>Suppose I've got some system for which I have collected information on a couple of individuals, including their names and
      ages.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">s1.name = <span style="color: #A020F0">'fred'</span>;
s1.age = 42;
s1(2).name = <span style="color: #A020F0">'alice'</span>;
s1(2).age = 29;</pre><p>Later, I go back and collect the individual's heights (in cm).</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">s2.height = 170;
s2(2).height = 160;</pre><p>It would be great to merge these arrays now.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">s1
s2</pre><pre style="font-style:oblique">s1 = 
1x2 struct array with fields:
    name
    age
s2 = 
1x2 struct array with fields:
    height
</pre><p>Let me collect the field names.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">fn1 = fieldnames(s1);
fn2 = fieldnames(s2);
fn = [fn1; fn2];</pre><p>Next, I ensure the fieldnames are unique.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">ufn = length(fn) == unique(length(fn))</pre><pre style="font-style:oblique">ufn =
     1
</pre><p>Next let me convert the data in my structs into cell arrays using <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/struct2cell.html"><tt>struct2cell</tt></a>.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">c1 = struct2cell(s1)
c2 = struct2cell(s2)</pre><pre style="font-style:oblique">c1(:,:,1) = 
    'fred'
    [  42]
c1(:,:,2) = 
    'alice'
    [   29]
c2(:,:,1) = 
    [170]
c2(:,:,2) = 
    [160]
</pre><p>Next I merge the data from the 2 cell arrays.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">c = [c1;c2]</pre><pre style="font-style:oblique">c(:,:,1) = 
    'fred'
    [  42]
    [ 170]
c(:,:,2) = 
    'alice'
    [   29]
    [  160]
</pre><p>And finally, I construct the new struct using <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cell2struct.html"><tt>cell2struct</tt></a>.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">s = cell2struct(c,fn,1)</pre><pre style="font-style:oblique">s = 
1x2 struct array with fields:
    name
    age
    height
</pre><p>I can check the output now.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">s(1)
s(2)</pre><pre style="font-style:oblique">ans = 
      name: 'fred'
       age: 42
    height: 170
ans = 
      name: 'alice'
       age: 29
    height: 160
</pre><h3>mergeStruct<a name="10"></a></h3>
   <p>Here's the function <tt>mergeStruct</tt> that I created to encapsulate the steps in this process, including some error checks.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">dbtype <span style="color: #A020F0">mergeStruct</span></pre><pre style="font-style:oblique">
1     function sout = mergestruct(varargin)
2     %MERGESTRUCT Merge structures with unique fields.
3     
4     %   Copyright 2009 The MathWorks, Inc.
5     
6     % Start with collecting fieldnames, checking implicitly 
7     % that inputs are structures.
8     fn = [];
9     for k = 1:nargin
10        try
11            fn = [fn ; fieldnames(varargin{k})];
12        catch MEstruct
13            throw(MEstruct)
14        end
15    end
16    
17    % Make sure the field names are unique.
18    if length(fn) ~= length(unique(fn))
19        error('mergestruct:FieldsNotUnique',...
20            'Field names must be unique');
21    end
22    
23    % Now concatenate the data from each struct.  Can't use 
24    % structfun since input structs may not be scalar.
25    c = [];
26    for k = 1:nargin
27        try
28            c = [c ; struct2cell(varargin{k})];
29        catch MEdata
30            throw(MEdata);
31        end
32    end
33    
34    % Construct the output.
35    sout = cell2struct(c, fn, 1);
</pre><h3>Do You Need to Merge struct data?<a name="11"></a></h3>
   <p>Do you ever need to merge data stored in structs when you gather new information?  Or are your structs static in nature? 
      If the information you collect is always the same sort of information, then you probably know the form of the structure when
      you start, even if all the data isn't available at first.
   </p>
   <p>There is <a href="http://www.mathworks.com/matlabcentral/fileexchange/7842">code</a> on the File Exchange to concatenate structures; I confess I have not tried it, but it is highly rated.  Does this post or
      the File Exchange contribution help your work?  Let me know <a href="http://blogs.mathworks.com/loren/?p=XXX#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_60deb70ff18c4179be87db0fb4a2118f() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='60deb70ff18c4179be87db0fb4a2118f ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 60deb70ff18c4179be87db0fb4a2118f';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_60deb70ff18c4179be87db0fb4a2118f()"><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; 7.9<br /></p>
</div>
<!--
60deb70ff18c4179be87db0fb4a2118f ##### SOURCE BEGIN #####
%% Concatenating Structs
% From time to time, I get asked or see queries about how to concatenate
% two
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/struct.html |struct|>
% arrays to merge the fields.  There's even a section in the
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-38.html#br04bw6-78 documentation> covering this topic.
% I thought I'd show it here to help people out.
%% Example Data
% Suppose I've got some system for which I have collected information on a
% couple of individuals, including their names and ages.  
s1.name = 'fred';
s1.age = 42;
s1(2).name = 'alice';
s1(2).age = 29;
%%
% Later, I go back and collect the individual's heights (in cm).
s2.height = 170;
s2(2).height = 160;
%%
% It would be great to merge these arrays now.
s1
s2
%%
% Let me collect the field names.
fn1 = fieldnames(s1);
fn2 = fieldnames(s2);
fn = [fn1; fn2];
%%
% Next, I ensure the fieldnames are unique.
ufn = length(fn) == unique(length(fn))
%%
% Next let me convert the data in my structs into cell arrays using
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/struct2cell.html |struct2cell|>.
c1 = struct2cell(s1)
c2 = struct2cell(s2)
%%
% Next I merge the data from the 2 cell arrays.
c = [c1;c2]
%%
% And finally, I construct the new struct using 
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cell2struct.html |cell2struct|>.
s = cell2struct(c,fn,1)
%%
% I can check the output now.
s(1)
s(2)
%% mergeStruct
% Here's the function |mergeStruct| that I created to encapsulate the steps
% in this process, including some error checks.
dbtype mergeStruct
%% Do You Need to Merge struct data?
% Do you ever need to merge data stored in structs when you gather new
% information?  Or are your structs static in nature?  If the information
% you collect is always the same sort of information, then you probably
% know the form of the structure when you start, even if all the data isn't
% available at first.  
%%
% There is
% <http://www.mathworks.com/matlabcentral/fileexchange/7842 code> on the
% File Exchange to concatenate structures; I confess I have not tried it,
% but it is highly rated.  Does this post or the File Exchange contribution
% help your work?  Let me know
% <http://blogs.mathworks.com/loren/?p=XXX#respond here>.


##### SOURCE END ##### 60deb70ff18c4179be87db0fb4a2118f
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/vZ95fGBo-JQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/</feedburner:origLink></item>
		<item>
		<title>Handling Discrete Data</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/D0RplIr36fY/</link>
		<comments>http://blogs.mathworks.com/loren/2009/10/09/handling-discrete-data/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 15:46:08 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Best Practice]]></category>

		<category><![CDATA[Less Used Functionality]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/10/09/handling-discrete-data/</guid>
		<description><![CDATA[
   
      Discrete data arise in many applications and the data may be numeric, or non-numeric, often referred to as categorical. Not
         all data are strictly numeric, and other characteristics can be pertinent or useful. You can use a variety [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>Discrete data arise in many applications and the data may be numeric, or non-numeric, often referred to as categorical. Not
         all data are strictly numeric, and other characteristics can be pertinent or useful. You can use a variety of techniques and
         data representations in MATLAB for storing and manipulation discrete data.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Example: Periodic Table of Elements</a></li>
         <li><a href="#3">Discrete Data Representation Options</a></li>
         <li><a href="#4">logical</a></li>
         <li><a href="#5">String or Coded Integer</a></li>
         <li><a href="#8">nominal Array</a></li>
         <li><a href="#12">ordinal Array</a></li>
         <li><a href="#16">Integer</a></li>
         <li><a href="#17">Going All the Way</a></li>
         <li><a href="#18">Your Data or Experiment</a></li>
      </ul>
   </div>
   <h3>Example: Periodic Table of Elements<a name="1"></a></h3>
   <p><a href="http://en.wikipedia.org/wiki/Periodic_table">The periodic table of elements</a> provides a rich basis for this discussion.  If you remember your chemistry class (I did, very imperfectly), you probably
      remember that each element has a fixed number of protons associated with it, also called the atomic number.  You might also
      remember that the periodic table is arranged so that certain columns of elements have certain characteristics.  For example,
      apart from Hydrogen, the left-most column holds the alkali metals (such as sodium and potassium) and the left side generally
      contains metallic elements.  The right-most column holds Noble gases, with the next column to their left holding halogens.
      Nonmetals are towards the right side of the table.  At standard temperature and pressure (known as STP), elements are in one
      of three states: solid, liquid, or gas.
   </p>
   <p>We've just talked about 3 different things:</p>
   <li>atomic number (number of protons in the nucleus), positive integers and therefore numeric</li>
   <li>solid, liquid, gas states, which can be considered ordinal (that is, solid &lt; liquid &lt; gas)</li>
   <li>element categories include the metals, nonmetals, etc., and these are simply labels or names, and therefore nominal (notice
      how these categories aren't strictly columnar in the periodic table)
   </li>
   <h3>Discrete Data Representation Options<a name="3"></a></h3>
   <p>I will try to use the periodic table example for each of the possible discrete data representations, but some of these will
      be forced examples.
   </p>
   <h3>logical<a name="4"></a></h3>
   <p>You could imagine use a <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logical.html"><tt>logical</tt></a> variable to indicate elements that are in the Noble category as <tt>true</tt> and <tt>false</tt> for the remainder.
   </p>
   <h3>String or Coded Integer<a name="5"></a></h3>
   <p><tt>logical</tt> variables are fine if you are representing exactly two possible categories.  However, looking at the periodic table, you
      see that I collapsed a subset of categories into "not Noble" (<tt>false</tt>). Rather than collapsing the set of categories into Noble and not Noble, the entire collection might be better represented
      as integers that are arbitrarily given meaning, or by strings.  For example, I could code alkali metals as <tt>'alkali metals'</tt> or as <tt>1</tt>, and so on.  The first 3 elements of the table would be represented with <tt>[8 10 1]</tt> or as <tt>{'other nonmetals' 'noble gases' 'alkali metals'}</tt>.
   </p>
   <p>Coded integers are useful for doing comparisons, for example, subsetting the data, and are memory-efficient. However, integers
      can cause you some mental overhead trying to remember the mapping between them and their labels.
   </p>
   <p>Strings are good for representing the data in a readable form, but are harder to manipulate, especially for an ordered list
      such as phase states.  Also you may prefer to use numeric type operations such as <tt>==</tt>, <tt>~=</tt>, and <tt>&lt;</tt> since they are more direct and show intent.  In addition, strings take more memory, especially when your data comprise many
      repetitions of the same value.
   </p>
   <h3>nominal Array<a name="8"></a></h3>
   <p>You have additional choices with <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/stats/nominal.html"><tt>nominal</tt></a> and <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/stats/ordinal.html"><tt>ordinal</tt></a> arrays from <a href="http://www.mathworks.com/products/statistics/">Statistics Toolbox</a>.
   </p>
   <p>Let's imagine that we create an array representing the element categories by atomic number.  The first 10 elements of this
      array look like this. I collapse some of the traditional categories for brevity.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">catLabels = {<span style="color: #A020F0">'metals'</span>, <span style="color: #A020F0">'metalloids'</span>,<span style="color: #A020F0">'other nonmetals'</span>,<span style="color: #A020F0">'halogens'</span>, <span style="color: #0000FF">...</span>
    <span style="color: #A020F0">'noble gases'</span>, <span style="color: #A020F0">'unknown'</span>};
elemCats = nominal([3 5 1 1 2 3 3 3 4 5]', catLabels, 1:length(catLabels))
elemNames = {<span style="color: #A020F0">'hydrogen'</span>,<span style="color: #A020F0">'helium'</span>,<span style="color: #A020F0">'lithium'</span>,<span style="color: #A020F0">'beryllium'</span>,<span style="color: #A020F0">'boron'</span>, <span style="color: #0000FF">...</span>
    <span style="color: #A020F0">'carbon'</span>,<span style="color: #A020F0">'nitrogen'</span>,<span style="color: #A020F0">'oxygen'</span>,<span style="color: #A020F0">'fluorine'</span>,<span style="color: #A020F0">'neon'</span>}';</pre><pre style="font-style:oblique">elemCats = 
     other nonmetals 
     noble gases 
     metals 
     metals 
     metalloids 
     other nonmetals 
     other nonmetals 
     other nonmetals 
     halogens 
     noble gases 

</pre><p>Here is the list of all possible values for the categories.  Notice that this nominal array carries that information with
      it. (You can modify this by adding, renaming, and deleting as necessary.)
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">getlabels(elemCats)</pre><pre style="font-style:oblique">ans = 
  Columns 1 through 5
    'metals'    'metalloids'    'other nonmetals'    'halogens'    'noble gases'
  Column 6
    'unknown'
</pre><p>Let's find all the 'other nonmetals' in the list.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">nonmets = find(elemCats == <span style="color: #A020F0">'other nonmetals'</span>)
elemNames(nonmets)</pre><pre style="font-style:oblique">nonmets =
     1
     6
     7
     8
ans = 
    'hydrogen'
    'carbon'
    'nitrogen'
    'oxygen'
</pre><h3>ordinal Array<a name="12"></a></h3>
   <p>Let's investigate the states of the first 10 elements now.  For some purposes, the states can be regarded as nominal. However,
      they can also be viewed as an ordered set, <tt>solid &lt; liquid &lt; gas</tt>.  (At STP, only mercury and bromine are in liquid state.)
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">stLabels = {<span style="color: #A020F0">'solid'</span> <span style="color: #A020F0">'liquid'</span> <span style="color: #A020F0">'gas'</span>};
elemSts = ordinal([3 3 1 1 1 1 3 3 3 3]', stLabels, 1:length(stLabels))</pre><pre style="font-style:oblique">elemSts = 
     gas 
     gas 
     solid 
     solid 
     solid 
     solid 
     gas 
     gas 
     gas 
     gas 

</pre><p>Here is the list of all possible values for the states.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">getlabels(elemSts)</pre><pre style="font-style:oblique">ans = 
    'solid'    'liquid'    'gas'
</pre><p>Let's find all the gases in the list.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">gases = find(elemSts &gt; <span style="color: #A020F0">'liquid'</span>) <span style="color: #228B22">% or == 'gas'</span>
elemNames(gases)</pre><pre style="font-style:oblique">gases =
     1
     2
     7
     8
     9
    10
ans = 
    'hydrogen'
    'helium'
    'nitrogen'
    'oxygen'
    'fluorine'
    'neon'
</pre><p>Let's sort the element list by state.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">[sts, elemNo] = sort(elemSts)
[cellstr(sts) elemNames(elemNo)]</pre><pre style="font-style:oblique">sts = 
     solid 
     solid 
     solid 
     solid 
     gas 
     gas 
     gas 
     gas 
     gas 
     gas 

elemNo =
     3
     4
     5
     6
     1
     2
     7
     8
     9
    10
ans = 
    'solid'    'lithium'  
    'solid'    'beryllium'
    'solid'    'boron'    
    'solid'    'carbon'   
    'gas'      'hydrogen' 
    'gas'      'helium'   
    'gas'      'nitrogen' 
    'gas'      'oxygen'   
    'gas'      'fluorine' 
    'gas'      'neon'     
</pre><h3>Integer<a name="16"></a></h3>
   <p>For the given list of elements, the atomic number happens to match exactly with the index into the <tt>elemNames</tt> array.  So I only need to create the relevant integer values 1:10 to represent the atomic number. This list is itself clearly
      ordered, and has numerical meaning (unlike <tt>ordinal</tt> arrays which are ordered but the spacing between elements has no definition).
   </p>
   <h3>Going All the Way<a name="17"></a></h3>
   <p>To continue this example, you can collect all the information together into a single <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/stats/datasetclass.html"><tt>dataset</tt></a> array (from Statistics Toolbox).  The advantages include being able to "index" by the element name!
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">atomicNo = (1:length(elemNames))';
periodicTable = dataset(atomicNo ,elemCats, elemSts, <span style="color: #A020F0">'obsnames'</span>, elemNames)</pre><pre style="font-style:oblique">periodicTable = 
                 atomicNo    elemCats           elemSts
    hydrogen      1          other nonmetals    gas    
    helium        2          noble gases        gas    
    lithium       3          metals             solid  
    beryllium     4          metals             solid  
    boron         5          metalloids         solid  
    carbon        6          other nonmetals    solid  
    nitrogen      7          other nonmetals    gas    
    oxygen        8          other nonmetals    gas    
    fluorine      9          halogens           gas    
    neon         10          noble gases        gas    
</pre><h3>Your Data or Experiment<a name="18"></a></h3>
   <p>Do you have a situation where some of your data can be represented with <tt>nominal</tt> or <tt>ordinal</tt> arrays?  How do you manage that information now? Let me know by posting <a href="http://blogs.mathworks.com/loren/?p=201#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_6065953c077a4b1f82ee8f9ed570810b() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='6065953c077a4b1f82ee8f9ed570810b ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 6065953c077a4b1f82ee8f9ed570810b';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_6065953c077a4b1f82ee8f9ed570810b()"><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; 7.9<br /></p>
</div>
<!--
6065953c077a4b1f82ee8f9ed570810b ##### SOURCE BEGIN #####
%% Handling Discrete Data
% Discrete data arise in many applications and the data may be numeric, or
% non-numeric, often referred to as categorical. Not all data are strictly
% numeric, and other characteristics can be pertinent or useful. You can
% use a variety of techniques and data representations in MATLAB for
% storing and manipulation discrete data.  

%% Example: Periodic Table of Elements
% <http://en.wikipedia.org/wiki/Periodic_table The periodic table of elements>
% provides a rich basis for this discussion.  If you remember your
% chemistry class (I did, very imperfectly), you probably remember that 
% each element has a fixed number of protons associated with it, also
% called the atomic number.  You might also remember that the periodic
% table is arranged so that certain columns of elements have certain
% characteristics.  For example, apart from Hydrogen, the left-most column
% holds the alkali metals (such as sodium and potassium) and the left side
% generally contains metallic elements.  The right-most column holds Noble
% gases, with the next column to their left holding halogens. Nonmetals are
% towards the right side of the table.  At standard temperature and
% pressure (known as STP), elements are in one of three states:
% solid, liquid, or gas.
%% 
% We've just talked about 3 different things:
%
% # atomic number (number of protons in the nucleus), positive integers and
% therefore numeric
% # solid, liquid, gas states, which can be considered ordinal (that is,
% solid < liquid < gas)
% # element categories include the metals, nonmetals, etc., and these are
% simply labels or names, and therefore nominal (notice how these
% categories aren't strictly columnar in the periodic table)

%% Discrete Data Representation Options
% I will try to use the periodic table example for each of the possible
% discrete data representations, but some of these will be forced examples.
%% logical
% You could imagine use a
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/logical.html |logical|>
% variable to indicate elements that are in the Noble category as |true|
% and |false| for the remainder. 
%% String or Coded Integer
% |logical| variables are fine if you are representing exactly two possible
% categories.  However, looking at the periodic table, you see that I
% collapsed a subset of categories into "not Noble" (|false|). Rather than
% collapsing the set of categories into Noble and not Noble, the entire
% collection might be better represented as integers that are arbitrarily
% given meaning, or by strings.  For example, I could code alkali metals as
% |'alkali metals'| or as |1|, and so on.  The first 3 elements of the
% table would be represented with |[8 10 1]| or as |{'other nonmetals'
% 'noble gases' 'alkali metals'}|.
%% 
% Coded integers are useful for doing comparisons, for example, subsetting
% the data, and are memory-efficient. However, integers can cause you some
% mental overhead trying to remember the mapping between them and their
% labels.   
%%
% Strings are good for representing the data in a readable form, but are
% harder to manipulate, especially for an ordered list such as phase
% states.  Also you may prefer to use numeric type operations such
% as |==|, |~=|, and |<| since they are more direct and show intent.  In
% addition, strings take more memory, especially when your data comprise
% many repetitions of the same value.
%% nominal Array
% You have additional choices with 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/stats/nominal.html |nominal|>
% and
% <http://www.mathworks.com/access/helpdesk/help/toolbox/stats/ordinal.html |ordinal|>
% arrays from <http://www.mathworks.com/products/statistics/ Statistics Toolbox>. 

%%
% Let's imagine that we create an array representing the element categories
% by atomic number.  The first 10 elements of this array look like this.
% I collapse some of the traditional categories for brevity.
catLabels = {'metals', 'metalloids','other nonmetals','halogens', ...
    'noble gases', 'unknown'};
elemCats = nominal([3 5 1 1 2 3 3 3 4 5]', catLabels, 1:length(catLabels))
elemNames = {'hydrogen','helium','lithium','beryllium','boron', ...
    'carbon','nitrogen','oxygen','fluorine','neon'}';
    
%%
% Here is the list of all possible values for the categories.  Notice that
% this nominal array carries that information with it. (You can modify this
% by adding, renaming, and deleting as necessary.)
getlabels(elemCats)
%%
% Let's find all the 'other nonmetals' in the list.
nonmets = find(elemCats == 'other nonmetals')
elemNames(nonmets)
%% ordinal Array
% Let's investigate the states of the first 10 elements now.  For some
% purposes, the states can be regarded as nominal. However, they can also
% be viewed as an ordered set, |solid < liquid < gas|.  (At STP, only
% mercury and bromine are in liquid state.)
stLabels = {'solid' 'liquid' 'gas'};
elemSts = ordinal([3 3 1 1 1 1 3 3 3 3]', stLabels, 1:length(stLabels))
    
%%
% Here is the list of all possible values for the states. 
getlabels(elemSts)
%%
% Let's find all the gases in the list.
gases = find(elemSts > 'liquid') % or == 'gas'
elemNames(gases)
%%
% Let's sort the element list by state.
[sts, elemNo] = sort(elemSts)
[cellstr(sts) elemNames(elemNo)]
%% Integer
% For the given list of elements, the atomic number happens to match
% exactly with the index into the |elemNames| array.  So I only need to
% create the relevant integer values 1:10 to represent the atomic number.
% This list is itself clearly ordered, and has numerical meaning (unlike
% |ordinal| arrays which are ordered but the spacing between elements has
% no definition).
%% Going All the Way
% To continue this example, you can collect all the information together
% into a single 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/stats/datasetclass.html |dataset|> 
% array (from Statistics Toolbox).  The advantages include being able to
% "index" by the element name!
atomicNo = (1:length(elemNames))';
periodicTable = dataset(atomicNo ,elemCats, elemSts, 'obsnames', elemNames)
%% Your Data or Experiment
% Do you have a situation where some of your data can be represented with
% |nominal| or |ordinal| arrays?  How do you manage that information now?
% Let me know by posting <http://blogs.mathworks.com/loren/?p=201#respond here>.

##### SOURCE END ##### 6065953c077a4b1f82ee8f9ed570810b
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/D0RplIr36fY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/10/09/handling-discrete-data/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/10/09/handling-discrete-data/</feedburner:origLink></item>
		<item>
		<title>October 14 - Virtual MATLAB Conference</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/kTP1vroi-PU/</link>
		<comments>http://blogs.mathworks.com/loren/2009/10/05/october-14-virtual-matlab-conference/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 13:35:23 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Education]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/10/05/october-14-virtual-matlab-conference/</guid>
		<description><![CDATA[We're having a MATLAB conference on October 14, in the virtual world. There'll be presentations, forums, chats, live discussion, etc.   Please check out the event and join in the fun!



   





Here's the presentation schedule to help you find what you'd like to participate in.




I'm planning to attend some of the forums [...]]]></description>
			<content:encoded><![CDATA[We're having a MATLAB conference on October 14, in the virtual world. There'll be presentations, forums, chats, live discussion, etc.   Please check out the event and <a tooltip="linkalert-tip" href="http://events.unisfair.com/rt/matlab%7Evirtualconf?code=hp-listing">join</a> in the fun!
</p>

<p>
   
</p>

<p>


Here's the <a href="http://events.unisfair.com/microsite24.jsp?eid=461&amp;seid=56&amp;language-code=en&amp;country-code=US&amp;page=1250096730240">presentation schedule</a> to help you find what you'd like to participate in.
</p>

<p>

I'm planning to attend some of the forums and listen to many of the talks, including ones focused on MATLAB for education.  Hope to meet you there!
</p>
<img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/kTP1vroi-PU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/10/05/october-14-virtual-matlab-conference/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/10/05/october-14-virtual-matlab-conference/</feedburner:origLink></item>
		<item>
		<title>Using parfor Loops: Getting Up and Running</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/7cUnXauqT9Y/</link>
		<comments>http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 16:30:13 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Best Practice]]></category>

		<category><![CDATA[parallel]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/</guid>
		<description><![CDATA[
   
      Today I&#8217;d like to introduce a guest blogger, Sarah Wait Zaranek, who is an application engineer here at The MathWorks. Sarah previously has written about speeding up code from a customer to get acceptable performance. She again will be writing about speeding up MATLAB
   [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>Today I&#8217;d like to introduce a guest blogger, <a href="mailto:sarah.zaranek@mathworks.com">Sarah Wait Zaranek</a>, who is an application engineer here at The MathWorks. Sarah previously has <a href="http://blogs.mathworks.com/loren/2008/06/25/speeding-up-matlab-applications/">written</a> about speeding up code from a customer to get acceptable performance. She again will be writing about speeding up MATLAB
         applications, but this time her focus will be on using the parallel computing tools.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Introduction</a></li>
         <li><a href="#2">Method</a></li>
         <li><a href="#4">Background on parfor-loops</a></li>
         <li><a href="#5">Opening the matlabpool</a></li>
         <li><a href="#8">Independence</a></li>
         <li><a href="#11">Globals and Transparency</a></li>
         <li><a href="#12">Classification</a></li>
         <li><a href="#21">Uniqueness</a></li>
         <li><a href="#28">Your examples</a></li>
      </ul>
   </div>
   <h3>Introduction<a name="1"></a></h3>
   <p>I wanted to write a post to help users better understand our parallel computing tools. In this post, I will focus on one of
      the more commonly used functions in these tools: the <tt>parfor</tt>-loop.
   </p>
   <p>This post will focus on getting a parallel code using <tt>parfor</tt> up and running. Performance will not be addressed in this post. I will assume that the reader has a basic knowledge of the
      <tt>parfor</tt>-loop construct. Loren has a very nice introduction to using <tt>parfor</tt> in one of her previous <a href="http://blogs.mathworks.com/loren/2007/10/03/parfor-the-course/">posts</a>. There are also some nice introductory <a href="http://www.mathworks.com/products/parallel-computing/demos.html">videos</a>.
   </p>
   <p><i>Note for clarity</i> : Since Loren's introductory post, the toolbox used for parallel computing has changed names from the Distributed Computing
      Toolbox to the <a href="http://www.mathworks.com/products/parallel-computing/">Parallel Computing Toolbox</a>. These are not two separate toolboxes.
   </p>
   <h3>Method<a name="2"></a></h3>
   <p>In some cases, you may only need to change a <tt>for</tt>-loop to a <tt>parfor</tt>-loop to get their code running in parallel. However, in other cases you may need to slightly alter the code so that <tt>parfor</tt> can work. I decided to show a few examples highlighting the main challenges that one might encounter.  I have separated these
      examples into four encompassing categories:
   </p>
   <div>
      <ul>
         <li>Independence</li>
         <li>Globals and Transparency</li>
         <li>Classification</li>
         <li>Uniqueness</li>
      </ul>
   </div>
   <h3>Background on parfor-loops<a name="4"></a></h3>
   <p>In a <tt>parfor</tt>-loop (just like in a standard <tt>for</tt>-loop) a series of statements known as the loop body are iterated over a range of values. However, when using a <tt>parfor</tt>-loop the iterations are run not on the client MATLAB machine but are run in parallel on MATLAB workers.
   </p>
   <p>Each worker has its own unique workspace.  So, the data needed to do these calculations is sent from the client to workers,
      and the results are sent back to the client and pieced together. The cool thing about <tt>parfor</tt> is this data transfer is handled for the user. When MATLAB gets to the <tt>parfor</tt>-loop, it statically analyzes the body of the <tt>parfor</tt>-loop and determines what information goes to which worker and what variables will be returning to the client MATLAB. Understanding
      this concept will become important when understanding why particular constraints are placed on the use of <tt>parfor</tt>.
   </p>
   <h3>Opening the matlabpool<a name="5"></a></h3>
   <p>Before looking at some examples, I will open up a matlabpool so I can run my loops in parallel.  I will be opening up the
      matlabpool using my default local configuration (i.e. my workers will be running on the dual-core laptop machine where my
      MATLAB has been installed).
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #0000FF">if</span> matlabpool(<span style="color: #A020F0">'size'</span>) == 0 <span style="color: #228B22">% checking to see if my pool is already open</span>
    matlabpool <span style="color: #A020F0">open</span> <span style="color: #A020F0">2</span>
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Starting matlabpool using the 'local' configuration ... connected to 2 labs.
</pre><p><i>Note</i> : The <tt>'size'</tt> option was new in R2008b.
   </p>
   <h3>Independence<a name="8"></a></h3>
   <p>The <tt>parfor</tt>-loop is designed for task-parallel types of problems where each iteration of the loop is independent of each other iteration.
      This is a critical requirement for using a <tt>parfor</tt>-loop. Let's see an example of when each iteration is not independent.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">dependentLoop.m</span></pre><pre style="font-style:oblique">
% Example of a dependent for-loop
a = zeros(1,10);

parfor it = 1:10 
    a(it) = someFunction(a(it-1));
end
</pre><p>Checking the above code using M-Lint (MATLAB's static code analyzer) gives a warning message that these iterations are dependent
      and will not work with the <tt>parfor</tt> construct. M-Lint can either be accessed via the editor or command line. In this case, I use the command line and have defined
      a simple function <tt>displayMlint</tt> so that the display is compact.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">output = mlint(<span style="color: #A020F0">'dependentLoop.m'</span>);
displayMlint(output)</pre><pre style="font-style:oblique">The PARFOR loop cannot run due to 
 the way variable 'a' is used. 

In a PARFOR loop, variable 'a' is 
 indexed in different ways, 
 potentially causing dependencies 
 between iterations. 

</pre><p>Sometimes loops are intrinsically or unavoidably dependent, and therefore <tt>parfor</tt> is not a good fit for that type of calculation. However, in some cases it is possible to reformulate the body of the loop
      to eliminate the dependency or separate it from the main time-consuming calculation.
   </p>
   <h3>Globals and Transparency<a name="11"></a></h3>
   <p>All variables within the body of a <tt>parfor</tt>-loop must be transparent. This means that all references to variables must occur in the text of the program. Since MATLAB
      is statically analyzing the loops to figure out what data goes to what worker and what data comes back, this seems like an
      understandable restriction.
   </p>
   <p>Therefore, the following commands cannot be used within the body of a <tt>parfor</tt>-loop : <tt>evalc</tt>, <tt>eval</tt>, <tt>evalin</tt>, and <tt>assignin</tt>. <tt>load</tt> can also not be used unless the output of load is <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.html">assigned</a> to a variable name. It is possible to use the above functions within a function called by <tt>parfor</tt>, due to the fact that the function has its own workspace. I have found that this is often the easiest workaround for the
      transparency issue.
   </p>
   <p>Additionally, you cannot define global variables or persistent variables within the body of the <tt>parfor</tt> loop. I would also suggest being careful with the use of globals since changes in global values on workers are not automatically
      reflected in local global values.
   </p>
   <h3>Classification<a name="12"></a></h3>
   <p>A detailed description of the <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brdqtjj-1.html">classification</a> of variables in a <tt>parfor</tt>-loop is in the documentation. I think it is useful to view classification as representing the different ways a variable is
      passed between client and worker and the different ways it is used within the body of the <tt>parfor</tt>-loop.
   </p>
   <p><i>Challenges with Classification</i></p>
   <p>Often challenges arise when first converting <tt>for</tt>-loops to <tt>parfor</tt>-loops due to issues with this classification.  An often seen issue is the conversion of nested <tt>for</tt>-loops, where sliced variables are not indexed appropriately.
   </p>
   <p>Sliced variables are variables where each worker is calculating on a different part of that variable. Therefore, sliced variables
      are sliced or divided amongst the workers. Sliced variables are used to prevent unneeded data transfer from client to worker.
   </p>
   <p><i>Using <tt>parfor</tt> with Nested <tt>for</tt>-Loops</i></p>
   <p>The loop below is nested and encounters some of the restrictions placed on <tt>parfor</tt> for sliced variables.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">parforNestTry.m</span></pre><pre style="font-style:oblique">
A1 = zeros(10,10); 

parfor ix = 1:10
    for jx = 1:10
        A1(ix, jx) = ix + jx;
    end
end
</pre><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">output = mlint(<span style="color: #A020F0">'parforNestTry.m'</span>);
displayMlint(output);</pre><pre style="font-style:oblique">The PARFOR loop cannot run due to 
 the way variable 'A1' is used. 

Valid indices for 'A1' are 
 restricted in PARFOR loops. 

</pre><p>In this case, <tt>A1</tt> is a sliced variable. For sliced variables, the restrictions are placed on the first-level variable indices. This allows
      <tt>parfor</tt> to easily distribute the right part of the variable to the right workers.
   </p>
   <p>The first level indexing ,in general, refers to indexing within the first set of parenthesis or braces. This is <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brdqtjj-1.html">explained</a> in more detail in the same section as classification in the documentation.
   </p>
   <p>One of these first-level indices must be the loop counter variable or the counter variable plus or minus a constant.  <i>Every other first-level index must be a constant, a non-loop counter variable, a colon, or an <tt>end</tt>.</i></p>
   <p>In this case, <tt>A1</tt> has an loop counter variable for both first level indices (<tt>ix</tt> and <tt>jx</tt>).
   </p>
   <p>The solution to this is make sure a loop counter variable is only one of the indices of <tt>A1</tt> and make the other index a colon. To implement this, the results of the inner loop can be saved to a new variable and then
      that variable can be saved to the desired variable outside the nested loop.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">A2 = zeros(10,10);

<span style="color: #0000FF">parfor</span> ix = 1:10
    myTemp = zeros(1,10);
    <span style="color: #0000FF">for</span> jx = 1:10
        myTemp(jx) = ix + jx;
    <span style="color: #0000FF">end</span>
    A2(ix,:) = myTemp;
<span style="color: #0000FF">end</span></pre><p>You can also solve this issue by using cells. Since <tt>jx</tt> is now in the second level of indexing, it can be an loop counter variable.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">A3 = cell(10,1);

<span style="color: #0000FF">parfor</span> ix = 1:10
    <span style="color: #0000FF">for</span> jx = 1:10
        A3{ix}(jx) = ix + jx;
    <span style="color: #0000FF">end</span>
<span style="color: #0000FF">end</span>

A3 = cell2mat(A3);</pre><p>I have found that both solutions have their benefits. While cells may be easier to implement in your code, they also result
      in <tt>A3</tt> using more memory due to the additional <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brh72ex-2.html#brh72ex-14">memory</a> requirements for cells. The call to <tt>cell2mat</tt> also adds additional processing time.
   </p>
   <p>A similar technique can be used for several levels of nested <tt>for</tt>-loops.
   </p>
   <h3>Uniqueness<a name="21"></a></h3>
   <p><i>Doing Machine Specific Calculations</i></p>
   <p>This is a way, while using <tt>parfor</tt>-loops, to determine which machine you are on and do machine specific instructions within the loop. An example of why you
      would want to do this is if different machines have data files in different directories, and you wanted to make sure to get
      into the right directory. Do be careful if you make the code machine-specific since it will be harder to port.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #228B22">% Getting the machine host name</span>

[~,hostname] = system(<span style="color: #A020F0">'hostname'</span>);

<span style="color: #228B22">% If the loop iterations are the same as the size of matlabpool, the</span>
<span style="color: #228B22">% command is run once per worker.</span>

<span style="color: #0000FF">parfor</span> ix = 1:matlabpool(<span style="color: #A020F0">'size'</span>)
    [~,hostnameID{ix}] = system(<span style="color: #A020F0">'hostname'</span>);
<span style="color: #0000FF">end</span>

<span style="color: #228B22">% Can then do host/machine specific commands</span>
hostnames = unique(hostnameID);
checkhost = hostnames(1);

<span style="color: #0000FF">parfor</span> ix = 1:matlabpool(<span style="color: #A020F0">'size'</span>)
    [~,myhost] = system(<span style="color: #A020F0">'hostname'</span>);
    <span style="color: #0000FF">if</span> strcmp(myhost,checkhost)
       display(<span style="color: #A020F0">'On Machine 1'</span>)
    <span style="color: #0000FF">else</span>
        display(<span style="color: #A020F0">'NOT on Machine 1'</span>)
    <span style="color: #0000FF">end</span>
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">On Machine 1
On Machine 1
</pre><p>In my case since I am running locally -- all of the workers are on the same machine.</p>
   <p>Here's the same code running on a non-local cluster.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">matlabpool <span style="color: #A020F0">close</span>
matlabpool <span style="color: #A020F0">open</span> <span style="color: #A020F0">speedy</span>
<span style="color: #0000FF">parfor</span> ix = 1:matlabpool(<span style="color: #A020F0">'size'</span>)
    [~,hostnameID{ix}] = system(<span style="color: #A020F0">'hostname'</span>);
<span style="color: #0000FF">end</span>

<span style="color: #228B22">% Can then do host/machine specific commands</span>
hostnames = unique(hostnameID);
checkhost = hostnames(1);

<span style="color: #0000FF">parfor</span> ix = 1:matlabpool(<span style="color: #A020F0">'size'</span>)
    [~,myhost] = system(<span style="color: #A020F0">'hostname'</span>);
    <span style="color: #0000FF">if</span> strcmp(myhost,checkhost)
       display(<span style="color: #A020F0">'On Machine 1'</span>)
    <span style="color: #0000FF">else</span>
        display(<span style="color: #A020F0">'NOT on Machine 1'</span>)
    <span style="color: #0000FF">end</span>
<span style="color: #0000FF">end</span></pre><pre style="font-style:oblique">Sending a stop signal to all the labs ... stopped.
Starting matlabpool using the 'speedy' configuration ... connected to 16 labs.
On Machine 1
On Machine 1
On Machine 1
NOT on Machine 1
On Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
NOT on Machine 1
</pre><p><i>Note</i>: The <tt>~</tt> feature is new in R2009b and discussed as a new feature in one of Loren's previous blog <a href="http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/"> posts</a>.
   </p>
   <p><i>Doing Worker Specific Calculations</i></p>
   <p>I would suggest using the new <tt>spmd</tt> functionality to do worker specific calculations. For more information about <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/spmd.html"><tt>spmd</tt></a>, check out the documentation.
   </p>
   <p>Clean up</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">matlabpool <span style="color: #A020F0">close</span></pre><pre style="font-style:oblique">Sending a stop signal to all the labs ... stopped.
</pre><h3>Your examples<a name="28"></a></h3>
   <p>Tell me about some of the ways you have used <tt>parfor</tt>-loops or feel free to post questions regarding non-performance related issues that haven't been addressed here.  Post your
      questions and thoughts <a href="http://blogs.mathworks.com/loren/?p=199#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_21027c06f45d49c38cb91403012a36e2() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='21027c06f45d49c38cb91403012a36e2 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 21027c06f45d49c38cb91403012a36e2';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_21027c06f45d49c38cb91403012a36e2()"><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; 7.9<br /></p>
</div>
<!--
21027c06f45d49c38cb91403012a36e2 ##### SOURCE BEGIN #####
%% Using |parfor| Loops: Getting Up and Running
% Today Iâ€™d like to introduce a guest blogger, 
% <mailto:sarah.zaranek@mathworks.com Sarah Wait Zaranek>, who is an
% application engineer here at The MathWorks. Sarah previously has <http://blogs.mathworks.com/loren/2008/06/25/speeding-up-matlab-applications/ written>
% about speeding up code from a customer to get acceptable performance.
% She again will be writing about speeding up MATLAB applications, but this
% time her focus will be on using the parallel computing tools. 

%% Introduction
% I wanted to write a post to help users better understand our parallel
% computing tools. In this post, I will focus on one of the more
% commonly used functions in these tools: the |parfor|-loop. 
%
% This post will focus on getting a parallel code using |parfor| up and 
% running. Performance will not be addressed in this post. I will assume
% that the reader has a basic knowledge of the |parfor|-loop construct.
% Loren has a very nice introduction to using |parfor| in one of her
% previous <http://blogs.mathworks.com/loren/2007/10/03/parfor-the-course/ posts>.
% There are also some nice introductory
% <http://www.mathworks.com/products/parallel-computing/demos.html videos>.
%
% _Note for clarity_ : Since Loren's introductory post, the toolbox used
% for parallel computing has changed names from the Distributed Computing
% Toolbox to the <http://www.mathworks.com/products/parallel-computing/ Parallel Computing Toolbox>.  
% These are not two separate toolboxes.

%% Method
% In some cases, you may only need to change a |for|-loop to a |parfor|-loop
% to get their code running in parallel. However, in other cases you 
% may need to slightly alter the code so that |parfor| can work. I decided to show a
% few examples highlighting the main challenges that one might encounter.  I
% have separated these examples into four encompassing categories:
%% 
% * Independence
% * Globals and Transparency
% * Classification
% * Uniqueness

%% Background on |parfor|-loops
% In a |parfor|-loop (just like in a standard |for|-loop) a series of
% statements known as the loop body are iterated over a range of values.
% However, when using a |parfor|-loop the iterations are run not on the
% client MATLAB machine but are run in parallel on MATLAB workers.
%
% Each worker has its own unique workspace.  So, the data needed to do
% these calculations is sent from the client to workers, and the results
% are sent back to the client and pieced together. The cool thing about
% |parfor| is this data transfer is handled for the user. When MATLAB gets to
% the |parfor|-loop, it statically analyzes the body of the |parfor|-loop and
% determines what information goes to which worker and what variables will
% be returning to the client MATLAB. Understanding this concept will become
% important when understanding why particular constraints are placed on
% the use of |parfor|. 

%% Opening the matlabpool
% Before looking at some examples, I will open up a matlabpool
% so I can run my loops in parallel.  I will be opening up the matlabpool
% using my default local configuration (i.e. my workers will be running on
% the dual-core laptop machine where my MATLAB has been installed).
%%

if matlabpool('size') == 0 % checking to see if my pool is already open
    matlabpool open 2
end

%%
% _Note_ : The |'size'| option was new in R2008b.

%% Independence
% The |parfor|-loop is designed for task-parallel types of problems where
% each iteration of the loop is independent of each other iteration.  
% This is a critical requirement for using a |parfor|-loop.
% Let's see an example of when each iteration is not independent.
%
type dependentLoop.m
%%
% Checking the above code using M-Lint (MATLAB's static code analyzer) gives
% a warning message that these iterations are dependent
% and will not work with the |parfor| construct. M-Lint can either
% be accessed via the editor or command line. In this case, I use the command
% line and have defined a simple function |displayMlint| so that the display is
% compact.
%
output = mlint('dependentLoop.m');
displayMlint(output)

%%
% Sometimes loops are intrinsically or unavoidably dependent, and therefore
% |parfor| is not a good fit for that type of calculation. However, in some
% cases it is possible to reformulate the body of the loop to eliminate the
% dependency or separate it from the main time-consuming calculation.  
%
%% Globals and Transparency
% All variables within the body of a |parfor|-loop must be transparent. This
% means that all references to variables must occur in the text of the
% program. Since MATLAB is statically analyzing the loops to figure out
% what data goes to what worker and what data comes back, this seems like
% an understandable restriction.
%
% Therefore, the following commands cannot be used within the body of a
% |parfor|-loop : |evalc|, |eval|, |evalin|, and |assignin|. |load| can
% also not be used unless the output of load is
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.html assigned> 
% to a variable name. It is possible to use the above functions
% within a function called by |parfor|, due to the fact that the function
% has its own workspace. I have found that this is often the easiest workaround for the
% transparency issue. 
%
% Additionally, you cannot define global variables or persistent variables within the body of the
% |parfor| loop. I would also suggest being careful with the use of globals 
% since changes in global values on workers are not automatically reflected in local
% global values. 

%% Classification
%
% A detailed description of the 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brdqtjj-1.html classification> 
% of variables in a |parfor|-loop is in the documentation.
% I think it is useful to view classification as representing the different ways a
% variable is passed between client and worker and the different ways it is
% used within the body of the |parfor|-loop. 
%
%%
% _Challenges with Classification_
%
% Often challenges arise when first converting |for|-loops to |parfor|-loops
% due to issues with this classification.  An often seen issue is the
% conversion of nested |for|-loops, where sliced variables are not indexed
% appropriately.   
%
% Sliced variables are variables where each worker is
% calculating on a different part of that variable. Therefore, sliced
% variables are sliced or divided amongst the workers. Sliced variables are
% used to prevent unneeded data transfer from client to worker. 
% 
%%
% _Using |parfor| with Nested |for|-Loops_
%
% The loop below is nested and encounters some of the restrictions placed
% on |parfor| for sliced variables. 

type parforNestTry.m

%%
output = mlint('parforNestTry.m');
displayMlint(output);

%%
% In this case, |A1| is a sliced variable. For sliced variables, the
% restrictions are placed on the first-level variable indices.
% This allows |parfor| to easily distribute the right part of the variable
% to the right workers. 
%
% The first level indexing ,in general, refers to indexing within the first set 
% of parenthesis or braces. This is 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brdqtjj-1.html explained>  
% in more detail in the same section as classification in the documentation. 
%
% One of these first-level indices must be the loop counter variable or the
% counter variable plus or minus a constant.  _Every other first-level 
% index must be a constant, a non-loop counter variable, a colon, or an |end|._ 

%%
% In this case, |A1| has an loop counter variable for both
% first level indices (|ix| and |jx|).
%
% The solution to this is make sure a loop counter variable is only one of the indices
% of |A1| and make the other index a colon. To implement this, the
% results of the inner loop can be saved to a new variable and then that variable
% can be saved to the desired variable outside the nested loop.
%%

A2 = zeros(10,10);

parfor ix = 1:10
    myTemp = zeros(1,10); 
    for jx = 1:10
        myTemp(jx) = ix + jx;
    end
    A2(ix,:) = myTemp; 
end

%%
% You can also solve this issue by using cells. Since |jx| is now in the second
% level of indexing, it can be an loop counter variable. 

A3 = cell(10,1); 

parfor ix = 1:10
    for jx = 1:10
        A3{ix}(jx) = ix + jx;
    end
end

A3 = cell2mat(A3);

%%  
% I have found that both solutions have their benefits. While cells may be
% easier to implement in your code, they also result in |A3| using more
% memory due to the additional <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brh72ex-2.html#brh72ex-14 memory> 
% requirements for cells. The call to |cell2mat| also adds additional
% processing time. 
%
% A similar technique can be used for several levels of nested |for|-loops.  

%% Uniqueness
% 
% _Doing Machine Specific Calculations_
%
% This is a way, while using |parfor|-loops, to determine which machine you
% are on and do machine specific instructions within the loop. An example
% of why you would want to do this is if different machines have data files
% in different directories, and you wanted to make sure to get into the
% right directory. Do be careful if you make the code machine-specific
% since it will be harder to port.

%% 

% Getting the machine host name

[~,hostname] = system('hostname');

% If the loop iterations are the same as the size of matlabpool, the
% command is run once per worker. 

parfor ix = 1:matlabpool('size')
    [~,hostnameID{ix}] = system('hostname');
end   

% Can then do host/machine specific commands
hostnames = unique(hostnameID);
checkhost = hostnames(1);

parfor ix = 1:matlabpool('size')
    [~,myhost] = system('hostname');
    if strcmp(myhost,checkhost)
       display('On Machine 1')
    else
        display('NOT on Machine 1')
    end
end

%%
% In my case since I am running locally REPLACE_WITH_DASH_DASH all of the workers are on the
% same machine.
%%
% Here's the same code running on a non-local cluster.
matlabpool close
matlabpool open speedy
parfor ix = 1:matlabpool('size')
    [~,hostnameID{ix}] = system('hostname');
end   

% Can then do host/machine specific commands
hostnames = unique(hostnameID);
checkhost = hostnames(1);

parfor ix = 1:matlabpool('size')
    [~,myhost] = system('hostname');
    if strcmp(myhost,checkhost)
       display('On Machine 1')
    else
        display('NOT on Machine 1')
    end
end
%%
% _Note_: The |~| feature is new in R2009b and discussed as a new feature
% in one of Loren's previous blog <http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/  posts>. 

%%
% _Doing Worker Specific Calculations_
%
% I would suggest using the new |spmd| functionality to do worker specific 
% calculations. For more
% information about <http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/spmd.html |spmd|>, 
% check out the documentation.  
%%
% Clean up
matlabpool close


%% Your examples
% Tell me about some of the ways you have used |parfor|-loops or feel free to
% post questions regarding non-performance related issues that haven't been
% addressed here.  Post your questions and thoughts
% <http://blogs.mathworks.com/loren/?p=199#respond here>.




##### SOURCE END ##### 21027c06f45d49c38cb91403012a36e2
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/7cUnXauqT9Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/</feedburner:origLink></item>
		<item>
		<title>MATLAB Release 2009b - Best New Feature or ~?</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/YydACyi7Iqc/</link>
		<comments>http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 14:13:25 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Best Practice]]></category>

		<category><![CDATA[New Feature]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/</guid>
		<description><![CDATA[
   
      MATLAB R2009b was recently released.  My favorite new language feature is the introduction of the ~ notation to denote missing inputs in function declarations, and missing outputs in calls to functions.  Let me show you how this works.
      
 [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p><a href="http://www.mathworks.com/products/new_products/latest_features.html">MATLAB R2009b</a> was recently released.  My favorite new language feature is the introduction of the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/bresuxt-1.html#br67dkp-1"><tt>~</tt> notation</a> to denote missing inputs in function declarations, and missing outputs in calls to functions.  Let me show you how this works.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Unused Outputs</a></li>
         <li><a href="#4">Unused Inputs</a></li>
         <li><a href="#6">Can M-Lint Help?</a></li>
         <li><a href="#11">What's Your Favorite New Feature?</a></li>
      </ul>
   </div>
   <h3>Unused Outputs<a name="1"></a></h3>
   <p>I have occasionally found that I would like the indices from sorting a vector, but I don't need the sorted values.  In the
      past, I wrote one of these code variants :
   </p><pre>          [dummy, ind] = sort(X)
          [ind, ind] = sort(X)</pre><p>In the first case, I end up with a variable <tt>dummy</tt> in my workspace that I don't need. If my data to sort, <tt>X</tt>, has a large number of elements, I will have an unneeded large array hanging around afterwards.  In the second case, I am
      banking on MATLAB assigning outputs in order, left to right, and I create somewhat less legible code, but I don't have an
      extra array hanging around afterwards.
   </p>
   <p>Now you can write this instead:</p><pre>          [~, ind] = sort(X)</pre><p>and I hope you find your code readable, with the clear intention to not use the first output variable.</p>
   <h3>Unused Inputs<a name="4"></a></h3>
   <p>You can similarly designate unused inputs with <tt>~</tt> in function declarations.  Here's how you'd define the interface where the second input is ignored.
   </p><pre>          function out = mySpecialFunction(X,~,dim)</pre><p>You might ask why that is useful.  If I don't use the second input, why put it in at all?  The answer is that your function
      might be called by some other function that expects to send three inputs.  This happens for many GUI callbacks, and particularly
      those you generate using <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/guide.html"><tt>guide</tt></a>. So your function needs to take three inputs. But if it is never going to use the second input, you can denote the second
      one with <tt>~</tt>.
   </p>
   <h3>Can M-Lint Help?<a name="6"></a></h3>
   <p>Yes!  Consider this function <tt>mySpecialFunction</tt> shown here.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">mySpecialFunction</span></pre><pre style="font-style:oblique">
function ind = mySpecialFunction(X,second,dim)
% mySpecialFunction Function to illustrate ~ for inputs and outputs.

[dummy,ind] = sort(X,dim);
</pre><p>Running <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/mlint.html"><tt>mlint</tt></a> on this code produces two messages.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">msgs = mlint(<span style="color: #A020F0">'mySpecialFunction'</span>);
disp(msgs(1).message(1:50))
disp(msgs(1).message(51:end))
disp(<span style="color: #A020F0">' '</span>)
disp(msgs(2).message(1:49))
disp(msgs(2).message(50:end))</pre><pre style="font-style:oblique">Input argument 'second' might be unused, although 
a later one is used.  Consider replacing it by ~.
 
The value assigned here to 'dummy' appears to be 
unused.  Consider replacing it by ~.
</pre><p>Since M-Lint is running continuously in the editor, you would see these messages as you edit the file.  Here's a cleaned up
      version of the file.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">mySpecialFunction1</span></pre><pre style="font-style:oblique">
function ind = mySpecialFunction1(X,~,dim)
% mySpecialFunction Function to illustrate ~ for inputs and outputs.

[~,ind] = sort(X,dim);
</pre><p>And let's see what M-Lint finds.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">mlint <span style="color: #A020F0">mySpecialFunction1</span></pre><p>It finds nothing at all.</p>
   <h3>What's Your Favorite New Feature?<a name="11"></a></h3>
   <p>Have you looked through the <a href="http://www.mathworks.com/products/matlab/whatsnew.html">new features</a> for R2009b?  What's your favorite?  Let me know <a href="http://blogs.mathworks.com/loren/?p=198#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_27713d2e85df444bb2fce1ee020e0067() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='27713d2e85df444bb2fce1ee020e0067 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 27713d2e85df444bb2fce1ee020e0067';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_27713d2e85df444bb2fce1ee020e0067()"><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; 7.9<br /></p>
</div>
<!--
27713d2e85df444bb2fce1ee020e0067 ##### SOURCE BEGIN #####
%% MATLAB Release 2009b - Best New Feature or ~?
% <http://www.mathworks.com/products/new_products/latest_features.html MATLAB R2009b>
% was recently released.  My favorite new language feature is
% the introduction of the 
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/bresuxt-1.html#br67dkp-1 |~| notation>
% to denote missing inputs in function declarations, and missing outputs in
% calls to functions.  Let me show you how this works.
%% Unused Outputs
% I have occasionally found that I would like the indices from sorting a
% vector, but I don't need the sorted values.  In the past, I wrote one of
% these code variants :
%
%            [dummy, ind] = sort(X)
%            [ind, ind] = sort(X)
%%
% In the first case, I end up with a variable |dummy| in my workspace that
% I don't need. If my data to sort, |X|, has a large number of elements, I
% will have an unneeded large array hanging around afterwards.  In the
% second case, I am banking on MATLAB assigning outputs in order, left to
% right, and I create somewhat less legible code, but I don't have an extra
% array hanging around afterwards.  
%%
% Now you can write this instead:
%
%            [~, ind] = sort(X)
%
% and I hope you find your code readable, with the clear intention to not
% use the first output variable.
%% Unused Inputs
% You can similarly designate unused inputs with |~| in function
% declarations.  Here's how you'd define the interface where the second
% input is ignored.
%
%            function out = mySpecialFunction(X,~,dim)
%
%%
% You might ask why that is useful.  If I don't use the second input, why
% put it in at all?  The answer is that your function might be called by
% some other function that expects to send three inputs.  This happens for
% many GUI callbacks, and particularly those you generate using 
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/guide.html |guide|>.
% So your function needs to take three inputs. But if it is never going to
% use the second input, you can denote the second one with |~|.
%% Can M-Lint Help?
% Yes!  Consider this function |mySpecialFunction| shown here.
type mySpecialFunction
%%
% Running <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/mlint.html |mlint|>
% on this code produces two messages.
msgs = mlint('mySpecialFunction');
disp(msgs(1).message(1:50))
disp(msgs(1).message(51:end))
disp(' ')
disp(msgs(2).message(1:49))
disp(msgs(2).message(50:end))
%%
% Since M-Lint is running continuously in the editor, you would see these
% messages as you edit the file.  Here's a cleaned up version of the file.
type mySpecialFunction1
%%
% And let's see what M-Lint finds.
mlint mySpecialFunction1
%%
% It finds nothing at all.
%% What's Your Favorite New Feature?
% Have you looked through the
% <http://www.mathworks.com/products/matlab/whatsnew.html new features> for
% R2009b?  What's your favorite?  Let me know
% <http://blogs.mathworks.com/loren/?p=198#respond here>.

##### SOURCE END ##### 27713d2e85df444bb2fce1ee020e0067
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/YydACyi7Iqc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/</feedburner:origLink></item>
		<item>
		<title>Rounding Results</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/Mq6sv7LgnHE/</link>
		<comments>http://blogs.mathworks.com/loren/2009/09/03/rounding-results/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 14:38:27 +0000</pubDate>
		<dc:creator>Loren</dc:creator>
		
		<category><![CDATA[Numerical Accuracy]]></category>

		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2009/09/03/rounding-results/</guid>
		<description><![CDATA[
   
      There are frequent questions on the MATLAB newsgroup about rounding results to a certain number of decimal places.  MATLAB itself doesn't provide this functionality explicitly,
         though it is easy to accomplish.
      
 [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>There are frequent questions on the <a href="http://www.mathworks.com/matlabcentral/newsreader/">MATLAB newsgroup</a> about rounding results to a certain number of decimal places.  MATLAB itself doesn't provide this functionality explicitly,
         though it is easy to accomplish.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Sidetrack : A Little MathWorks History</a></li>
         <li><a href="#2">Example</a></li>
         <li><a href="#7">Tools for Rounding Solutions</a></li>
         <li><a href="#9">Question for You</a></li>
      </ul>
   </div>
   <h3>Sidetrack : A Little MathWorks History<a name="1"></a></h3>
   <p>MathWorks' first Massachusetts office phone number was 653-1415 (ignoring country and area codes). The astute reader will
      notice that the last 5 digits are an approximation for <img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/197/rounding_eq11731.png">  (or, in MATLAB, <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/pi.html"><tt>pi</tt></a>). A local resident called one day to say that she kept getting calls for MathWorks and she wasn't sure why.  But it was quite
      inconvenient for her because she spent lots of time on the second floor of her home, and the phone was on the first floor.
       The excess round-trips were taxing her! To understand what was happening, you should know that in some of the early MathWorks
      materials, the phone number was listed as <img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/197/rounding_eq41424.png">  <img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/197/rounding_eq11731.png"> .
   </p>
   <h3>Example<a name="2"></a></h3><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">format <span style="color: #A020F0">long</span>
x = 1.23456789</pre><pre style="font-style:oblique">x =
   1.234567890000000
</pre><p>Use <tt>round</tt>. Here we get no decimals at all.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">round(x)</pre><pre style="font-style:oblique">ans =
     1
</pre><p>There are many ways to get the number of decimals you want. Here's one way to round to 3 decimals.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">round(x*1000)/1000</pre><pre style="font-style:oblique">ans =
   1.235000000000000
</pre><p>Here's another way.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">sprintf(<span style="color: #A020F0">'%0.3f'</span>,x)</pre><pre style="font-style:oblique">ans =
1.235
</pre><p>And another.  In this case, using the "easy" way to specify the format, you need to know how many integral digits there are
      as well.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">str2num(num2str(x,4))</pre><pre style="font-style:oblique">ans =
   1.235000000000000
</pre><h3>Tools for Rounding Solutions<a name="7"></a></h3>
   <p>There are a lot of tools for helping you round numbers.  The functions I list here for MATLAB form the basis of many, if not
      all, of the specific solutions.
   </p>
   <p>MATLAB</p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/round.html"><tt>round</tt></a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fix.html"><tt>fix</tt></a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/floor.html"><tt>floor</tt></a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ceil.html"><tt>ceil</tt></a></li>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sprintf.html"><tt>sprintf</tt></a></li>
      </ul>
   </div>
   <p>Mapping Toolbox</p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/access/helpdesk/help/toolbox/map/roundn.html"><tt>roundn</tt></a></li>
      </ul>
   </div>
   <p>File Exchange Rounding Tools</p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/matlabcentral/fileexchange/?term=round+decimal">Search : 'round decimal'</a></li>
         <li><a href="http://www.mathworks.com/matlabcentral/fileexchange/24213">Solution: round to power</a></li>
         <li><a href="http://www.mathworks.com/matlabcentral/fileexchange/23949">Solution: round to significant figures</a></li>
      </ul>
   </div><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #228B22">% N= num2str(X,SF);</span>
<span style="color: #228B22">% N= str2num(N);</span></pre><h3>Question for You<a name="9"></a></h3>
   <p>When you round values, do you want this for display only, or wanted for calculations?  Some applications I can think of might
      include processing data that has a smaller number of bits of precision to start with.  What applications do you need rounding
      for in your calculations?  Post <a href="http://blogs.mathworks.com/loren/?p=197#respond">here</a> with your thoughts.
   </p><script language="JavaScript">
<!--

    function grabCode_67a09b17dc6e4bee9bb4d02ab1aa4e1f() {
        // Remember the title so we can use it in the new page
        title = document.title;

        // Break up these strings so that their presence
        // in the Javascript doesn't mess up the search for
        // the MATLAB code.
        t1='67a09b17dc6e4bee9bb4d02ab1aa4e1f ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 67a09b17dc6e4bee9bb4d02ab1aa4e1f';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

        // Use /x3C/g instead of the less-than character to avoid errors 
        // in the XML parser.
        // Use '\x26#60;' instead of '<' so that the XML parser
        // doesn't go ahead and substitute the less-than character. 
        code_string = code_string.replace(/\x3C/g, '\x26#60;');

        author = 'Loren Shure';
        copyright = 'Copyright 2009 The MathWorks, Inc.';

        w = window.open();
        d = w.document;
        d.write('<pre>\n');
        d.write(code_string);

        // Add author and copyright lines at the bottom if specified.
        if ((author.length > 0) || (copyright.length > 0)) {
            d.writeln('');
            d.writeln('%%');
            if (author.length > 0) {
                d.writeln('% _' + author + '_');
            }
            if (copyright.length > 0) {
                d.writeln('% _' + copyright + '_');
            }
        }

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_67a09b17dc6e4bee9bb4d02ab1aa4e1f()"><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; 7.8<br /></p>
</div>
<!--
67a09b17dc6e4bee9bb4d02ab1aa4e1f ##### SOURCE BEGIN #####
%% Rounding Results
% There are frequent questions on the
% <http://www.mathworks.com/matlabcentral/newsreader/ MATLAB newsgroup>
% about rounding results to a certain number of decimal places.  MATLAB
% itself doesn't provide this functionality explicitly, though it is easy
% to accomplish.
%% Sidetrack : A Little MathWorks History
% MathWorks' first Massachusetts office phone number was 653-1415 (ignoring
% country and area codes). The astute reader will notice that the last 5
% digits are an approximation for $\pi$ (or, in MATLAB,
% <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/pi.html |pi|>).
% A local resident called one day to say that she kept getting calls for
% MathWorks and she wasn't sure why.  But it was quite inconvenient for her
% because she spent lots of time on the second floor of her home, and the
% phone was on the first floor.  The excess round-trips were taxing her! To
% understand what was happening, you should know that in some of the early
% MathWorks materials, the phone number was listed as $65$ $\pi$.
%% Example
format long
x = 1.23456789
%%
% Use |round|. Here we get no decimals at all.
round(x)
%%
% There are many ways to get the number of decimals you want. Here's one
% way to round to 3 decimals.
round(x*1000)/1000
%% 
% Here's another way.
sprintf('%0.3f',x)
%% 
% And another.  In this case, using the "easy" way to specify the format,
% you need to know how many integral digits there are as well.
str2num(num2str(x,4))

%% Tools for Rounding Solutions
% There are a lot of tools for helping you round numbers.  The functions I
% list here for MATLAB form the basis of many, if not all, of the specific
% solutions.
%%
% MATLAB
%
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/round.html |round|>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fix.html |fix|>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/floor.html |floor|>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ceil.html |ceil|>
% * <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sprintf.html |sprintf|>
%
% Mapping Toolbox
%
% * <http://www.mathworks.com/access/helpdesk/help/toolbox/map/roundn.html |roundn|>
%
% File Exchange Rounding Tools
%
% * <http://www.mathworks.com/matlabcentral/fileexchange/?term=round+decimal Search : 'round decimal'>
% * <http://www.mathworks.com/matlabcentral/fileexchange/24213 Solution: round to power>
% * <http://www.mathworks.com/matlabcentral/fileexchange/23949 Solution: round to significant figures>

% N= num2str(X,SF);
% N= str2num(N);

%% Question for You
% When you round values, do you want this for display only, or wanted for
% calculations?  Some applications I can think of might include processing
% data that has a smaller number of bits of precision to start with.  What
% applications do you need rounding for in your calculations?  Post
% <http://blogs.mathworks.com/loren/?p=197#respond here> with your
% thoughts.

##### SOURCE END ##### 67a09b17dc6e4bee9bb4d02ab1aa4e1f
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/Mq6sv7LgnHE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2009/09/03/rounding-results/feed/</wfw:commentRss>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2009/09/03/rounding-results/</feedburner:origLink></item>
	</channel>
</rss>
